Administrator
20 hours ago cee484403a94584ef1fb55bbac641f7bcbfaf6d8
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package cc.mrbird.febs.ai.strategy.Impl;
 
import cc.mrbird.febs.ai.req.agent.AiRequestDto;
import cc.mrbird.febs.ai.strategy.LlmStrategyService;
import cc.mrbird.febs.ai.strategy.enumerates.LlmStrategyContextEnum;
import cc.mrbird.febs.ai.strategy.param.LlmStrategyDto;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.exception.FebsException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
 
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
@Slf4j
@Component("AliLlmStrategyService")
public class AliLlmStrategyServiceImpl implements LlmStrategyService {
 
    private GenerationParam generationParam;
 
    private static final String apiKey = "sk-a2323eba1e584066b3a536aefa804970";
    private static final String model = "qwen-plus";
 
 
    private ApplicationParam applicationParam;
    private ApplicationParam applicationParamSummary;
 
    private static final String appId = "a5d38240f6b94da6b7f1f7fbe563f50c";
    private static final String SummaryAppId = "19da84392c534db5b2e3f10e698758ab";
 
    @PostConstruct
    public void init() {
        this.generationParam = GenerationParam.builder()
                // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(apiKey)
                // 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
                .model(model)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
 
        this.applicationParam = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(apiKey)
                .appId(appId)
                .build();
 
        this.applicationParamSummary = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(apiKey)
                .appId(SummaryAppId)
                .build();
    }
 
    private List<Message> getMessages(List<LlmStrategyDto> dto) {
        List<Message> messages = new ArrayList<>();
        for (LlmStrategyDto dtoItem : dto){
            if (StrUtil.equals(dtoItem.getRole(),Role.SYSTEM.getValue())){
                messages.add(Message.builder()
                        .role(Role.SYSTEM.getValue())
                        .content(dtoItem.getContent())
                        .build());
            }
            if (StrUtil.equals(dtoItem.getRole(),Role.USER.getValue())){
                messages.add(Message.builder()
                        .role(Role.USER.getValue())
                        .content(dtoItem.getContent())
                        .build());
            }
            if (StrUtil.equals(dtoItem.getRole(),Role.ASSISTANT.getValue())){
                messages.add(Message.builder()
                        .role(Role.ASSISTANT.getValue())
                        .content(dtoItem.getContent())
                        .build());
            }
        }
        return messages;
    }
 
    @Override
    public FebsResponse llmInvokeNonStreaming(List<LlmStrategyDto> dto) {
        if (CollUtil.isEmpty(dto)){
            throw new FebsException("百炼大模型初始化异常");
        }
        List<Message> messages = getMessages(dto);
        Generation gen = new Generation();
        generationParam.setMessages(messages);
        generationParam.setEnableThinking( false);
        FebsResponse febsResponse = new FebsResponse();
        try {
            GenerationResult result = gen.call(generationParam);
            if (result != null && result.getOutput() != null && result.getOutput().getChoices().size() > 0){
                febsResponse.success().data(result.getOutput().getChoices().get(0).getMessage().getContent());
            }else{
                febsResponse.fail().message("百炼大模型调用失败");
            }
        } catch (NoApiKeyException e) {
            throw new FebsException(StrUtil.format("百炼大模型调用失败:{}",e.getMessage()));
        } catch (InputRequiredException e) {
            throw new FebsException(StrUtil.format("百炼大模型输出失败:{}",e.getMessage()));
        }
        return febsResponse;
    }
 
    @Override
    public Flux<FebsResponse> llmInvokeStreamingWithThink(List<LlmStrategyDto> dto) {
        if (CollUtil.isEmpty(dto)){
            throw new FebsException("百炼大模型初始化异常");
        }
        List<Message> messages = getMessages(dto);
 
        long startTime = System.currentTimeMillis();
        Generation gen = new Generation();
        generationParam.setMessages(messages);
        generationParam.setResultFormat(GenerationParam.ResultFormat.MESSAGE);
        generationParam.setEnableThinking( true);
        generationParam.setIncrementalOutput( true);
        Flowable<GenerationResult> result;
        try {
            result = gen.streamCall(generationParam);
        } catch (NoApiKeyException | InputRequiredException e) {
            throw new FebsException(StrUtil.format("百炼大模型输出失败:{}",e.getMessage()));
        }
 
        return Flux.from(result)
                .map(message -> {
                    HashMap<String, String> stringStringHashMap = new HashMap<>();
                    if (StrUtil.isNotEmpty(message.getOutput().getChoices().get(0).getMessage().getReasoningContent())){
                        stringStringHashMap.put(LlmStrategyContextEnum.THINK.name(),message.getOutput().getChoices().get(0).getMessage().getReasoningContent());
 
                        System.out.print(message.getOutput().getChoices().get(0).getMessage().getReasoningContent());
                    }
                    if (StrUtil.isNotEmpty(message.getOutput().getChoices().get(0).getMessage().getContent())){
                        stringStringHashMap.put(LlmStrategyContextEnum.CONTENT.name(),message.getOutput().getChoices().get(0).getMessage().getContent());
                        System.out.print(message.getOutput().getChoices().get(0).getMessage().getContent());
                    }
                    return new FebsResponse().success().data(stringStringHashMap);
                })
                .doOnComplete(() -> {
                    long endTime = System.currentTimeMillis();
                    System.out.println("百炼大模型输出:" + (endTime - startTime) + "毫秒");
                })
                .doOnError(error -> {
                    throw new FebsException(StrUtil.format("百炼大模型输出失败:{}",error));
                });
    }
 
    @Override
    public Flux<FebsResponse> llmInvokeStreamingNoThink(List<LlmStrategyDto> dto) {
        if (CollUtil.isEmpty(dto)){
            throw new FebsException("百炼大模型初始化异常");
        }
        List<Message> messages = getMessages(dto);
 
        long startTime = System.currentTimeMillis();
        Generation gen = new Generation();
        generationParam.setMessages(messages);
        generationParam.setResultFormat(GenerationParam.ResultFormat.MESSAGE);
        generationParam.setIncrementalOutput( true);
        generationParam.setEnableThinking( false);
        Flowable<GenerationResult> result;
        try {
            result = gen.streamCall(generationParam);
        } catch (NoApiKeyException | InputRequiredException e) {
            throw new FebsException(StrUtil.format("百炼大模型输出失败:{}",e.getMessage()));
        }
 
        return Flux.from(result)
                .map(message -> {
                    HashMap<String, String> stringStringHashMap = new HashMap<>();
                    if (StrUtil.isNotEmpty(message.getOutput().getChoices().get(0).getMessage().getContent())){
                        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
                        System.out.print( content);
                        stringStringHashMap.put(LlmStrategyContextEnum.CONTENT.name(),content);
                    }
                    return new FebsResponse().success().data(stringStringHashMap);
                })
                .doOnComplete(() -> {
                    long endTime = System.currentTimeMillis();
                    System.out.println("百炼大模型输出:" + (endTime - startTime) + "毫秒");
                })
                .doOnError(error -> {
                    throw new FebsException(StrUtil.format("百炼大模型输出失败:{}",error));
                });
    }
 
    @Override
    public Flux<FebsResponse> llmInvokeStreamingNoThink(AiRequestDto dto) {
        long startTime = System.currentTimeMillis();
        if (ObjectUtil.isEmpty(dto)){
            throw new FebsException("参数异常");
        }
        String talkId = dto.getTalkId();
 
        String rolePrompt = dto.getRolePrompt();
        List<Message> messages = dto.getMessages();
        HashMap<String, Object> userPromptParams = new HashMap<>();
        userPromptParams.put("role_prompt", rolePrompt);
        if(CollUtil.isNotEmpty( messages)){
            userPromptParams.put("message_list", messages);
        }
        HashMap<String, Object> bizParams = new HashMap<>();
        bizParams.put("user_prompt_params", userPromptParams);
 
        List<String> knowledgeIds = dto.getKnowledgeIds();
        List<String> fileIds = dto.getFileIds();
        String prompt = dto.getPrompt();
 
        Application application = new Application();
        applicationParam.setPrompt(prompt);
        applicationParam.setBizParams(JsonUtils.toJsonObject( bizParams));
        // 获取当前的系统时间
        applicationParam.setEnableSystemTime( true);
        // 增量输出
        applicationParam.setIncrementalOutput( true);
        // 思考过程
        applicationParam.setEnableThinking( false);
        // 多轮对话
//        applicationParam.setMessages(messages);
        // 上下文seesionId
//        String sessionId = (String) redisCache.getCacheObject(talkId);
//        if (ObjectUtil.isNotEmpty(sessionId)){
//            applicationParam.setSessionId(talkId);
//        }
 
        RagOptions ragOptions = null;
        if (CollUtil.isEmpty(fileIds)){
            ragOptions = RagOptions.builder()
                    .pipelineIds(knowledgeIds)
                    .build();
        }else{
            ragOptions = RagOptions.builder()
                    .pipelineIds(knowledgeIds)
                    .fileIds(fileIds)
                    .build();
        }
        applicationParam.setRagOptions(ragOptions);
        Flowable<ApplicationResult> result;
        try {
            result = application.streamCall(applicationParam);
        } catch (NoApiKeyException | InputRequiredException e) {
 
            throw new FebsException(StrUtil.format("百炼大模型输出失败:{}",e.getMessage()));
        }
        return Flux.from(result)
                .map(message -> {
                    HashMap<String, Object> stringStringHashMap = new HashMap<>();
                    if (!message.getOutput().getFinishReason().equals("stop")){
                        stringStringHashMap.put(LlmStrategyContextEnum.CONTENT.name(),message.getOutput().getText());
                    }
                    if (message.getOutput().getFinishReason().equals("stop")){
                        log.info("百炼大模型输出:{}",message.getOutput().getSessionId());
                        List<ApplicationUsage.ModelUsage> models = message.getUsage().getModels();
                        long outputTokens = models.stream().mapToLong(ApplicationUsage.ModelUsage::getOutputTokens).sum();
                        log.info("百炼大模型输出:{}",outputTokens);
                        long inputTokens = models.stream().mapToLong(ApplicationUsage.ModelUsage::getInputTokens).sum();
                        log.info("百炼大模型输出:{}",inputTokens);
                        stringStringHashMap.put("inputTokens:",inputTokens);
                        stringStringHashMap.put("outputTokens:",outputTokens);
                        stringStringHashMap.put(LlmStrategyContextEnum.CONTENT.name(),message.getOutput().getText());
                    }
 
                    return new FebsResponse().success().data(stringStringHashMap);
                })
                .doOnComplete(() -> {
                    long endTime = System.currentTimeMillis();
                    System.out.println("百炼大模型输出:" + (endTime - startTime) + "毫秒");
                })
                .doOnError(error -> {
                    throw new FebsException(StrUtil.format("百炼大模型输出失败:{}",error));
                });
    }
}