package com.alatus.springai.controller;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.ai.openai.OpenAiChatClient;
import reactor.core.publisher.Flux;
@RestController
public class ChatController {
@Resource
private OpenAiChatClient openAiChatClient;
@RequestMapping(value = "/ai/chat")
public String chat(@RequestParam(value = "msg") String msg){
return openAiChatClient.call(msg);
}
@RequestMapping(value = "/ai/chat2")
public Object chat2(@RequestParam(value = "msg")String msg){
ChatResponse call = openAiChatClient.call(new Prompt(msg));
return call.getResult().getOutput().getContent();
//第二个是获取完整对象用的
// return call;
}
@RequestMapping(value = "/ai/chat3")
public Object chat3(@RequestParam(value = "msg")String msg){
// 可选参数如果配置文件和代码中都出现了,以代码配置为准
ChatResponse call = openAiChatClient.call(new Prompt(msg,
OpenAiChatOptions.builder()
// .withModel("gpt-4-32k")//GPT版本,32K是参数
.withTemperature(0.1F)//温度越高,回答越不精确,温度越低越精确
.build()));
return call.getResult().getOutput().getContent();
//第二个是获取完整对象用的
// return call;
}
@RequestMapping(value = "/ai/chat4")
public Object chat4(@RequestParam(value = "msg")String msg){
// flux将结果以序列返回
Flux<ChatResponse> flux = openAiChatClient.stream(new Prompt(msg,
OpenAiChatOptions.builder()
// .withModel("gpt-4-32k")//GPT版本,32K是参数
.withTemperature(0.1F)//温度越高,回答越不精确,温度越低越精确
.build()));
// 数据的序列,一序列的数据,一个一个的数据返回
flux.toStream().forEach(chatResponse -> {
System.out.print(chatResponse.getResult().getOutput().getContent());
});
return flux.collectList();
}
}
标签:WEB,AI,Spring,value,ai,call,springframework,msg,import
From: https://blog.51cto.com/u_16322355/12228648