个人学习心得,仅供参考
软件环境:
JDK 17 你用JDK 11 无法支持SpringBoot 3SpringBoot 3 版本以上才支持spring aimavan 3.6.1
1.获取Deepseek官网的API-key
官网:https://platform.deepseek.com/api_keys
2.创建项目
这样创建
添加依赖
项目结构
下面是源码
application.properties配置文件
spring.ai.openai.api-key= 你复制的API key
spring.ai.openai.base-url=https://api.deepseek.com
spring.ai.openai.chat.options.model=deepseek-chat
spring.ai.openai.chat.options.temperature=0.7
service类
import org.springframework.ai.chat.model.ChatResponse;
import reactor.core.publisher.Flux;public interface DeepSeekService {/* 根据消息直接输出回答 */String chat(String message);/* 根据消息直接输出回答 流式输出 */Flux<ChatResponse> chatFlux(String message);}
service实现类
import com.hpl.service.DeepSeekService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;@Service
public class DeepSeekServiceImpl implements DeepSeekService {@Resourceprivate OpenAiChatModel chatModel;@Overridepublic String chat(String message) {return chatModel.call(message);}@Overridepublic Flux<ChatResponse> chatFlux(String message) {Prompt prompt = new Prompt(new UserMessage(message));return chatModel.stream(prompt);}}
controller类
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatResponse;
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("/ai")
public class DeepSeekController {@Resourceprivate DeepSeekService deepSeekService;@GetMapping(value = "/chat", produces = MediaType.APPLICATION_JSON_VALUE)public String chat(@RequestParam(value = "message") String message) {return deepSeekService.chat(message);}@GetMapping(value = "/chatFlux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)public Flux<ChatResponse> chatFlux(@RequestParam(value = "message") String message) {return deepSeekService.chatFlux(message);}
}
然后启动SpringBoot
去postman测试
http://localhost:8080/ai/chat?message=你是谁
参考文档
spring-ai 官网:https://docs.spring.io/spring-ai/reference/api/chat/deepseek-chat.html
deepseek 官方文档:https://api-docs.deepseek.com/zh-cn/