赞
踩
- 注意:修改pom文件,重新下载spring ai依赖需要科学上网,请确保网络连接没有问题
<properties> <java.version>21</java.version> <spring-ai.version>0.8.1</spring-ai.version> </properties> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </pluginRepository> </pluginRepositories>
spring:
application:
name: Chat
ai:
openai:
api-key: hk-xxx
base-url: https://api.openai-hk.com #请根据自己的api-key自定义配置
chat:
options:
model: gpt-3.5-turbo #默认model为 gpt-3.5-turbo
temperature: 0.5
server:
port: 8080
import jakarta.annotation.Resource; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @RestController public class ChatController { @Resource private OpenAiChatClient openAiChatClient; @RequestMapping("/ai/chat") public String chat(@RequestParam(value = "msg") String msg){ return openAiChatClient.call(msg); } @RequestMapping("/ai/chat2") public String chatCall(@RequestParam(value = "msg") String msg){ ChatResponse response = openAiChatClient.call(new Prompt(msg)); return response.getResult().getOutput().getContent(); } @RequestMapping("/ai/chat4") public String chatCall2(@RequestParam(value = "msg") String msg){ //可选参数可以覆盖 项目配置文件中的参数(以代码中内容为准) ChatResponse response = openAiChatClient.call( new Prompt( msg, OpenAiChatOptions.builder() .withModel("gpt-4-vision-preview") //gpt版本 可以填写字符串或者使用OpenAiApi.ChatModel中提供的常量 .withTemperature(0.8F) //温度高,回答创新型越高;越低,越准确 .build() ) ); return response.getResult().getOutput().getContent(); } @RequestMapping("/ai/chat5") public Object chatStream(@RequestParam(value = "msg") String msg){ Flux<ChatResponse> flux = openAiChatClient.stream(new Prompt(msg, OpenAiChatOptions.builder() .withModel(OpenAiApi.ChatModel.GPT_4_VISION_PREVIEW.getValue()) //gpt版本 "gpt-4-vision-preview" .withTemperature(0.5F) //温度高,回答创新型越高;越低,越准确 .withMaxTokens(4096) //显示最大token .build() ) ); flux.toStream().forEach(chatResponse -> { System.out.print(chatResponse.getResult().getOutput().getContent()); }); return flux.collectList(); } }
http://localhost:8080/ai/chat4?msg=河南大学大礼堂被烧毁了,请作一首诗表示悲痛
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。