【Spring AI Alibaba实战Demo】通过Spring AI Alibaba接入本地部署的大模型和线上大模型,实现流式简单对话
文章目录
- 工具
- SpringAIAlibaba接入本地大模型
- SpringAIAlibaba接入线上大模型
- 流式对话实现
工具
- IDEA
- springBoot 3.x
- Java 17
- ollama
本地大模型使用ollama部署的deepseek-r1:1.5b,线上使用阿里百炼的大模型,具体本地部署步骤可参考:我的博客
SpringAIAlibaba接入本地大模型
- 创建SpringBoot项目
- 添加pom依赖
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-ollama-spring-boot-starter</artifactId></dependency>
- 写配置文件
spring:ai:ollama:base-url: http://localhost:11434chat:model: deepseek-r1:1.5b
- 接口层
@RestController
@RequestMapping("/ai")
public class ChatController {private final ChatClient chatClient;public ChatController(ChatClient.Builder chatClient) {this.chatClient = chatClient.build();}/*** 处理普通聊天请求,接收用户输入并返回模型的响应。* * @param input 用户输入的文本内容* @return 模型生成的响应内容*/@GetMapping(value = "/chat")public String chat(@RequestParam(value = "input") String input) {// 使用 ChatClient 发起一个用户消息请求,并同步获取模型的响应内容return this.chatClient.prompt().user(input) // 设置用户输入的内容.call() // 触发模型调用.content(); // 获取模型返回的内容}
}
- 启动项目后测试接口
###
GET http://localhost:8088/ai/chat?input=你是谁
- 结果输出
成功接入
SpringAIAlibaba接入线上大模型
此处不再赘述,只需更改两个地方:
- pom依赖中
<!-- <dependency>-->
<!-- <groupId>org.springframework.ai</groupId>-->
<!-- <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>-->
<!-- </dependency>--><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId></dependency>
注意要注释掉原来的ollama依赖
- 新增配置
spring:application:name: alibaba-deepseek-demoai:ollama:base-url: http://localhost:11434chat:model: deepseek-r1:1.5bdashscope:api-key: (填入你的apiKey)#base-url: https://dashscope.aliyuncs.com/compatible-mode/v1chat:options:model: qwen-max
记得填入你自己的apiKey
最后启动即可:
至此,我们就完成了通过SpringAIAlibaba接入本地和线上大模型两种方式,来进行简单的对话了!接下来用流式实现对话
流式对话实现
/*** 流式对话接口,通过SSE返回逐字生成的回复内容* @param input 用户输入的提示词* @return Flux<String> 以流式方式返回生成的回复内容片段*/@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)public Flux<String> stream(String input) {// 使用ChatClient构建流式请求:// 1. 创建prompt上下文// 2. 设置用户输入// 3. 启动流式推理// 4. 提取内容流return this.chatClient.prompt().user(input).stream().content();}
postman测试:
不得不感叹,springai接口封装的的太好了,只要调用就能实现这个功能了