一、在阿里云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();
}
});
}
}