Administrator
2025-09-01 22a3879dcb502e34b287675a2dac27dded499371
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
package cc.mrbird.febs.ai.strategy.Impl;
 
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.StrUtil;
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.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
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("AliLlmStrategyService")
public class AliLlmStrategyServiceImpl implements LlmStrategyService {
 
    private GenerationParam generationParam;
 
    private static final String apiKey = "sk-babdcf8799144134915cee2683794b2f";
    private static final String model = "qwen-plus";
 
    @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();
    }
 
    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);
        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> llmInvokeStreaming(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());
                    }
                    if (StrUtil.isNotEmpty(message.getOutput().getChoices().get(0).getMessage().getContent())){
                        stringStringHashMap.put(LlmStrategyContextEnum.CONTENT.name(),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));
                });
    }
}