Administrator
2025-08-05 f7a1b1996d92d96004a7a1ab1bf289516732c7e4
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
package cc.mrbird.febs.ai.service.impl;
 
import cc.mrbird.febs.ai.entity.AiProductRole;
import cc.mrbird.febs.ai.res.ai.AiResponse;
import cc.mrbird.febs.ai.service.AiProductRoleService;
import cc.mrbird.febs.ai.service.AiService;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionChoice;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
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.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;
 
    @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, "角色配置不完整");
        }
 
        return question(promptTemplate, linkId, content);
    }
 
    @Override
    public AiResponse question(String promptTemplate, String linkId, String content) {
        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);
 
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(linkId)
                .messages(messages)
                .temperature(1.0)
                .topP(0.7)
                .maxTokens(4096)
                .frequencyPenalty(0.0)
                .build();
 
        try {
            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());
 
            return buildSuccessResponse(result);
        } catch (Exception e) {
            log.error("调用AI服务失败,modelId: {}, content: {}", linkId, content, e);
            return buildErrorResponse(CODE_ERROR, "AI服务调用失败");
        }
    }
 
    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;
    }
}