java springboot 集成 阿里通义千问

一、在阿里云https://www.aliyun.com官网直接搜索“通义千问”,点击“开通DashScope”进行服务激活
二、加入Maven依赖

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>dashscope-sdk-java</artifactId>
  <version>2.15.3</version>
</dependency>

三、在yml中配置中配置key

ai:
  api:
    key: ###########################

四、在config目录添加配置 TongYiAiConfiguration.java

@Configuration
public class TongYiAiConfiguration {

    @Bean
    public Generation generation(){
        return new Generation();
    }

五、实现聊天

@RestController
@RequestMapping("/aiChat")
public class ChatController {
    private final Generation generation;

    @Value("${ai.api.key}")
    private String appKey;

    @Autowired
    public ChatController(Generation generation) {
        this.generation = generation;
    }

    @PostMapping("/send1")
    public GenerationResult chat1(@RequestBody String question, HttpServletResponse response) throws NoApiKeyException, InputRequiredException {

        List<Message> messages = new ArrayList<>();
        Message systemMsg =
                Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content(question).build();
        messages.add(systemMsg);
        messages.add(userMsg);
        GenerationParam param =
                GenerationParam.builder().model(Generation.Models.QWEN_TURBO).messages(messages)
                        .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                        .build();
        GenerationResult result = generation.call(param);
        return result;
    }

    @PostMapping("/send2")
    public Flux<ServerSentEvent<String>> chat2(@RequestBody String question, HttpServletResponse response) throws NoApiKeyException, InputRequiredException {
        // 构建ai对象
        Message message = Message.builder().role(Role.USER.getValue()).content(question).build();
        // 构建通义千问推送消息对象
        GenerationParam qwenParam = GenerationParam.builder()
                // 设置通义千问的类型模型
                .model(Generation.Models.QWEN_PLUS)
                // 转化为一个新的List集合
                .messages(Arrays.asList(message))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                // 是否联网进行查询
                .apiKey(appKey)
                .build();
        // 执行方法获取流式返回数据
        Flowable<GenerationResult> result = generation.streamCall(qwenParam);
        return Flux.from(result).map(m -> {
            // GenerationResult对象中输出流(GenerationOutput)的choices是一个列表,存放着生成的数据。
            String content = m.getOutput().getChoices().get(0).getMessage().getContent();
            return ServerSentEvent.<String>builder().data(content).build();
        }).publishOn(Schedulers.boundedElastic())
                .doOnError(e -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", "400");
                    map.put("message", "has mistake "+e.getMessage());
                    try {
                        // 设置流式处理webFlux
                        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
                        response.setCharacterEncoding("UTF-8");
                        response.getOutputStream().print(JsonUtils.toJson(map));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                });
    }

}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cesske

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值