准备
1、API-KEY的获取与配置
前往API-KEY管理,可以点击创建后获取
2、开通DashScope
具体看文档
如何获取通义千问API的KEY_模型服务灵积(DashScope)-阿里云帮助中心 (aliyun.com)
开始
1、安装DashScope SDK
需要:已安装Java8及以上版本
导入依赖 【the-latest-version替换成最新版本,版本可以查看Maven】
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>the-latest-version</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
2、编写接口
package org.mashang.aidemo.controller;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Test {
@PostMapping("/ai")
public GenerationResult callWithMessage(String str)
throws NoApiKeyException, ApiException, InputRequiredException {
Generation gen = new Generation();
Constants.apiKey="sk-xxxxxxxxxxxxxxxxxxxxxxxxxx";//这里填写自己申请的APIKEY
MessageManager msgManager = new MessageManager(10);
Message systemMsg =
Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
Message userMsg = Message.builder().role(Role.USER.getValue()).content(str).build();//这里填写对话内容
msgManager.add(systemMsg);
msgManager.add(userMsg);
QwenParam param =
QwenParam.builder().model(Generation.Models.QWEN_TURBO).messages(msgManager.get())
.resultFormat(QwenParam.ResultFormat.MESSAGE)
.topP(0.8)
.enableSearch(true)
.build();
GenerationResult result = gen.call(param);
return result;
}
}
运行
发送:用postman测试
响应: