1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package cc.mrbird.febs.ai.service.impl;
 
import cc.mrbird.febs.ai.entity.AiProductRole;
import cc.mrbird.febs.ai.req.ai.AiRequest;
import cc.mrbird.febs.ai.res.ai.AiResponse;
import cc.mrbird.febs.ai.res.ai.Report;
import cc.mrbird.febs.ai.service.AiProductRoleService;
import cc.mrbird.febs.ai.service.AiService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.volcengine.ark.runtime.model.completion.chat.*;
import com.volcengine.ark.runtime.service.ArkService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * @author Administrator
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiServiceImpl implements AiService {
 
    private static final String CODE_SUCCESS = "200";
    private static final String CODE_NOT_FOUND = "201";
    private static final String CODE_ERROR = "500";
 
    private final AiProductRoleService aiProductRoleService;
    private final ObjectMapper objectMapper;
 
    @Value("${ai.service.ak}")
    private String ak;
 
    @Value("${ai.service.sk}")
    private String sk;
 
    @Value("${ai.service.base-url}")
    private String baseUrl;
 
    private ArkService service;
 
    @PostConstruct
    public void init() {
        ConnectionPool connectionPool = new ConnectionPool(10, 30, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        this.service = ArkService.builder()
                .dispatcher(dispatcher)
                .connectionPool(connectionPool)
                .baseUrl(baseUrl)
                .ak(ak)
                .sk(sk)
                .build();
    }
 
    @PreDestroy
    public void destroy() {
        if (service != null) {
            service.shutdownExecutor();
        }
    }
 
    @Override
    public AiResponse start(String productRoleId, String content) {
        if (!StringUtils.hasText(productRoleId)) {
            log.warn("productRoleId 不能为空");
            return buildErrorResponse(CODE_NOT_FOUND, "AI陪练不存在");
        }
 
        AiProductRole aiProductRole = aiProductRoleService.getById(productRoleId);
        if (aiProductRole == null) {
            log.warn("未找到对应的角色配置,productRoleId: {}", productRoleId);
            return buildErrorResponse(CODE_NOT_FOUND, "AI陪练不存在");
        }
 
        String promptTemplate = aiProductRole.getPromptTemplate();
        String linkId = aiProductRole.getLinkId();
 
        if (!StringUtils.hasText(promptTemplate) || !StringUtils.hasText(linkId)) {
            log.warn("角色配置不完整,promptTemplate 或 linkId 为空,productRoleId: {}", productRoleId);
            return buildErrorResponse(CODE_ERROR, "角色配置不完整");
        }
 
        AiRequest aiRequest = new AiRequest();
        aiRequest.setPromptTemplate(promptTemplate);
        aiRequest.setLinkId(linkId);
        aiRequest.setContent(content);
 
        return question(aiRequest);
    }
 
    @Override
    public AiResponse question(AiRequest aiRequest) {
        String promptTemplate = aiRequest.getPromptTemplate();
        String linkId = aiRequest.getLinkId();
        String content = aiRequest.getContent();
        if (!StringUtils.hasText(promptTemplate) || !StringUtils.hasText(linkId) || !StringUtils.hasText(content)) {
            log.warn("请求参数不完整,promptTemplate: {}, linkId: {}, content: {}", promptTemplate, linkId, content);
            return buildErrorResponse(CODE_ERROR, "请求参数不完整");
        }
 
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(promptTemplate).build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(content).build();
        messages.add(systemMessage);
        messages.add(userMessage);
 
        // 生成 JSON Schema
        String schemaJson = "{\n" +
                "     \"radar_data\": {\n" +
                "       \"problem_understanding\": \"object\",\n" +
                "       \"fluency\": \"object\",\n" +
                "       \"principle_adherence\": \"object\",\n" +
                "       \"logicality\": \"object\",\n" +
                "       \"knowledge_mastery\": \"object\"\n" +
                "     },\n" +
                "     \"evaluation\": {\n" +
                "       \"highlight\": \"object\",\n" +
                "       \"suggestion\": \"object\",\n" +
                "       \"reference_answer\": \"object\",\n" +
                "       \"key_knowledge\": \"object\"\n" +
                "     }\n" +
                "   }";
        try {
            JsonNode schemaNode = objectMapper.readTree(schemaJson);
            // 配置响应格式
            ChatCompletionRequest.ChatCompletionRequestResponseFormat responseFormat = new ChatCompletionRequest.ChatCompletionRequestResponseFormat(
                    "json_schema",
                    new ResponseFormatJSONSchemaJSONSchemaParam(
                            "ai_response",
                            "json数据响应",
                            schemaNode,
                            true
                    )
            );
            ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                    .model(linkId)
                    .messages(messages)
                    .stream(false)
                    .responseFormat(responseFormat)
                    .temperature(1.0)
                    .topP(0.7)
                    .maxTokens(4096)
                    .frequencyPenalty(0.0)
                    .build();
            List<ChatCompletionChoice> choices = service.createChatCompletion(chatCompletionRequest).getChoices();
            String result = choices.stream()
                    .map(choice -> choice.getMessage().getContent())
                    .filter(contentObj -> contentObj != null)
                    .map(Object::toString)
                    .collect(Collectors.joining());
 
            Report report = this.extractReportData(result);
            return buildSuccessResponse(report, result);
        } catch (JsonProcessingException e) {
            log.error("初始化AI服务失败,JSON格式化输出初始化失败", e);
            return buildErrorResponse(CODE_ERROR, "AI服务调用失败");
        } catch (Exception e) {
            log.error("调用AI服务失败,modelId: {}, content: {}", linkId, content, e);
            return buildErrorResponse(CODE_ERROR, "AI服务调用失败");
        }
    }
 
    private static final Pattern JSON_PATTERN = Pattern.compile(
            "<\\|FunctionCallBegin\\|>(.*?)<\\|FunctionCallEnd\\|>",
            Pattern.DOTALL
    );
 
    @Override
    public Report extractReportData(String modelOutput) {
        // 提取JSON部分
        Matcher matcher = JSON_PATTERN.matcher(modelOutput);
        if (!matcher.find()) {
            log.warn("未匹配到FunctionCall内容,原始输出: {}", modelOutput);
            return null;
        }
 
        String jsonContent = matcher.group(1);
        log.debug("提取到的JSON内容: {}", jsonContent);
 
        // 解析JSON到Report对象
        try {
            return objectMapper.readValue(jsonContent, Report.class);
        } catch (JsonProcessingException e) {
            log.error("JSON解析失败,原始内容: {}", jsonContent, e);
            // 尝试修复截断的JSON(可选)
            Report repairedReport = tryRepairTruncatedJson(jsonContent);
            if (repairedReport != null) {
                log.info("成功修复截断的JSON");
                return repairedReport;
            }
            return null;
        }
    }
 
    /**
     * 尝试修复截断的JSON字符串
     * @param truncatedJson 可能被截断的JSON字符串
     * @return 修复后的Report对象,如果无法修复则返回null
     */
    private Report tryRepairTruncatedJson(String truncatedJson) {
        // 简单的修复策略:尝试添加缺失的结束括号
        String[] repairAttempts = {
                truncatedJson + "\"}}}",
                truncatedJson + "}}}",
                truncatedJson + "}}"
        };
 
        for (String attempt : repairAttempts) {
            try {
                return objectMapper.readValue(attempt, Report.class);
            } catch (JsonProcessingException e) {
                log.debug("修复尝试失败: {}", attempt);
                continue;
            }
        }
 
        log.warn("无法修复截断的JSON: {}", truncatedJson);
        return null;
    }
 
    private AiResponse buildErrorResponse(String code, String description) {
        AiResponse response = new AiResponse();
        response.setCode(code);
        response.setDescription(description);
        return response;
    }
 
    private AiResponse buildSuccessResponse(String result) {
        AiResponse response = new AiResponse();
        response.setCode(CODE_SUCCESS);
        response.setDescription("成功");
        response.setResContext(result);
        return response;
    }
 
    private AiResponse buildSuccessResponse(Report report, String result) {
        AiResponse response = new AiResponse();
        response.setCode(CODE_SUCCESS);
        response.setDescription("成功");
        response.setResContext(result);
        response.setReport(report);
        return response;
    }
}