Administrator
yesterday 8130bed63a505cf718481c0d95d3fcf7b037db96
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
package cc.mrbird.febs.ai.strategy.Impl;
 
import cc.mrbird.febs.ai.strategy.LlmStrategyService;
import cc.mrbird.febs.ai.strategy.enumerates.LlmApplicationAppIdEnum;
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.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.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.app.FlowStreamMode;
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 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;
 
@Component("AliApplicationLlmStrategyServiceImpl")
public class AliApplicationLlmStrategyServiceImpl implements LlmStrategyService {
 
    private static final String apiKey = "sk-babdcf8799144134915cee2683794b2f";
 
    private final String bizParam_1 = "prompt_ai_system";
    private final String bizParam_2 = "question";
    private final String bizParam_3 = "query";
 
    private HashMap getPrompt(List<LlmStrategyDto> dto) {
        HashMap<String, String> bizParamsMap = new HashMap<>();
        for (LlmStrategyDto dtoItem : dto){
            if (StrUtil.equals(dtoItem.getRole(), Role.SYSTEM.getValue())){
                bizParamsMap.put(bizParam_1, dtoItem.getContent());
            }
            if (StrUtil.equals(dtoItem.getRole(),Role.ASSISTANT.getValue())){
                bizParamsMap.put(bizParam_2, dtoItem.getContent());
            }
            if (StrUtil.equals(dtoItem.getRole(),Role.USER.getValue())){
                bizParamsMap.put(bizParam_3, dtoItem.getContent());
            }
        }
        return bizParamsMap;
    }
 
    private String getQuery(List<LlmStrategyDto> dto) {
        String query = null;
        for (LlmStrategyDto dtoItem : dto){
            if (StrUtil.equals(dtoItem.getRole(),Role.USER.getValue())){
                query = dtoItem.getContent();
                break;
            }
        }
        return query;
    }
 
    private String getAppId(List<LlmStrategyDto> dto) {
        String appId = null;
        for (LlmStrategyDto dtoItem : dto){
            if (StrUtil.equals(dtoItem.getRole(),Role.TOOL.getValue())){
                int code = Integer.parseInt(dtoItem.getContent());
                appId = LlmApplicationAppIdEnum.HIGH_LIGHT.getAppIdByCode(code);
                break;
            }
        }
        return appId;
    }
 
    @Override
    public FebsResponse llmInvokeNonStreaming(List<LlmStrategyDto> dto) {
        return null;
    }
 
    @Override
    public Flux<FebsResponse> llmInvokeStreamingWithThink(List<LlmStrategyDto> dto) {
 
        if (CollUtil.isEmpty(dto)){
            throw new FebsException("百炼大模型初始化异常");
        }
        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());
            }
        }
 
        GenerationParam generationParam = GenerationParam.builder()
                // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(apiKey)
                // 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .enableThinking(true)
                .incrementalOutput(true)
                .build();
 
        long startTime = System.currentTimeMillis();
        Generation gen = new Generation();
        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("百炼工作流初始化异常");
        }
        HashMap prompt = getPrompt(dto);
        String query = getQuery(dto);
        String appId = getAppId(dto);
        if (prompt == null || prompt.size() == 0){
            throw new FebsException("百炼工作流初始化异常");
        }
        if (query == null){
            throw new FebsException("百炼工作流初始化异常");
        }
        if (appId == null){
            throw new FebsException("百炼工作流初始化异常");
        }
        long startTime = System.currentTimeMillis();
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(apiKey)
                .appId(appId) //替换为实际的应用 ID
                .flowStreamMode(FlowStreamMode.MESSAGE_FORMAT)
                .prompt(query)
                .bizParams(JsonUtils.toJsonObject( prompt))
                .build();
 
        Application application = new Application();
        Flowable<ApplicationResult> result;
        try {
            result = application.streamCall(param);
        } catch (NoApiKeyException | InputRequiredException e) {
            throw new FebsException(StrUtil.format("百炼工作流输出失败:{}",e.getMessage()));
        }
 
        return Flux.from(result)
                .map(message -> {
                    HashMap<String, String> stringStringHashMap = new HashMap<>();
                    if (!message.getOutput().getFinishReason().equals("stop")){
                        stringStringHashMap.put(LlmStrategyContextEnum.CONTENT.name(),message.getOutput().getWorkflowMessage().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));
                });
    }
}