SpringBoot集成deepseek
pom文件:
4.0.0 org.springframework.boot spring-boot-starter-parent 3.4.5 com.xbs springAI-openAi 0.0.1-SNAPSHOT springAI-openAi springAI-openAi 17 1.0.0-M6 org.springframework.ai spring-ai-bom ${spring-ai.version} pom import org.springframework.boot spring-boot-starter-web org.projectlombok lombok 1.18.22 org.springframework.ai spring-ai-openai-spring-boot-starter <!-- --><!-- com.mysql--><!-- mysql-connector-j--><!-- runtime--><!-- --> org.springframework.boot spring-boot-starter-test test <!-- --><!-- com.baomidou--><!-- mybatis-plus-spring-boot3-starter--><!-- 3.5.10.1--><!-- --> org.springframework.ai spring-ai-pdf-document-reader org.springframework.ai spring-ai-openai org.springframework.boot spring-boot-maven-plugin
yaml配置文件:
spring: ai: openai: base-url: https://api.deepseek.com # DeepSeek的OpenAI式端点 api-key: sk-a26bd8370bf349f3a47313685917fe4d chat.options: model: deepseek-chat # 指定DeepSeek的模型名称
添加配置类:
package com.xp.ai.config;import org.springframework.ai.chat.client.ChatClient;import org.springframework.ai.openai.OpenAiChatModel;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class CommonConfiguration { // 注意参数中的model就是使用的模型,这里用了Ollama,也可以选择OpenAIChatModel @Bean public ChatClient chatClient(OpenAiChatModel model) { return ChatClient.builder(model) // 创建ChatClient工厂 .build(); // 构建ChatClient实例 }}
添加service层:
package com.xp.ai.service;import org.springframework.ai.chat.client.ChatClient;import org.springframework.ai.chat.model.ChatResponse;import org.springframework.stereotype.Service;import reactor.core.publisher.Flux;@Servicepublic class AiChatService { private final ChatClient chatClient; public AiChatService(ChatClient chatClient) { this.chatClient = chatClient; } // 流式响应方法 public Flux streamChat(String message) { return chatClient .prompt() .user(message) .stream() .content(); }}
controller:
package com.xp.ai.controller;import com.xp.ai.service.AiChatService;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.GetMapping;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@RequestMapping(\"/api/chat\")public class ChatController { private final AiChatService aiChatService; public ChatController(AiChatService aiChatService) { this.aiChatService = aiChatService; } @GetMapping(value = \"/stream\", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux streamChat(@RequestParam String message) { return aiChatService.streamChat(message); }}
postman验证: