個人學習心得,僅供參考
軟件環境:
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/