ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Spring AI 接入 DeepSeek Chat 模型

Spring AI 接入 DeepSeek Chat 模型 本文介绍如何在 Spring Boot 项目中使用 Spring AI 接入 DeepSeek Chat 模型实现一个简单的对话接口。示例包含 Maven 依赖、application.yml配置、ChatClient调用代码以及常见问题排查。示例基于当前 Spring AI 2.0.x 的自动配置方式。Spring AI 和 DeepSeek 的模型名称会随版本变化实际使用时请以对应版本的官方文档为准。一、准备工作开始之前需要准备JDK 17 或更高版本Maven 3.9一个 Spring Boot 项目一个 DeepSeek API Key。DeepSeek API Key 可以在 DeepSeek API Keys 页面 创建。不要把 API Key 直接提交到 Git 仓库。推荐通过环境变量、配置中心或密钥管理服务注入。二、创建项目并添加 Maven 依赖下面给出一个完整的pom.xml关键配置。Spring AI 官方当前稳定版本为 2.0.x示例使用2.0.0BOM如果项目使用其他 Spring AI 版本只需要将 BOM 版本替换为项目实际版本。?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion4.0.0/versionrelativePath//parentgroupIdcom.example/groupIdartifactIdspring-ai-deepseek-demo/artifactIdversion0.0.1-SNAPSHOT/versionnamespring-ai-deepseek-demo/namepropertiesjava.version17/java.versionspring-ai.version2.0.0/spring-ai.version/propertiesdependencyManagementdependenciesdependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-bom/artifactIdversion${spring-ai.version}/versiontypepom/typescopeimport/scope/dependency/dependencies/dependencyManagementdependencies!-- Web 接口 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- Spring AI DeepSeek Chat 自动配置 --dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-starter-model-deepseek/artifactId/dependency!-- 测试依赖 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project版本说明Spring AI 2.0.x 对应 Spring Boot 4.0.x/4.1.x如果项目仍然使用 Spring Boot 3.x 请选择与之匹配的 Spring AI 1.x 版本不建议只修改 Spring Boot 或 Spring AI 的单个版本号最好按照 Spring AI 官方兼容矩阵整体调整。三、配置application.yml在src/main/resources/application.yml中添加以下内容server:port:8080spring:application:name:spring-ai-deepseek-demoai:deepseek:# 从环境变量中读取 API Key避免将密钥写入源码api-key:${DEEPSEEK_API_KEY}# DeepSeek OpenAI 兼容接口的基础地址base-url:https://api.deepseek.comchat:# 当前 API 文档推荐使用 deepseek-flash也可以根据账户能力选择其他模型model:deepseek-flash# 编程、数学类任务可以使用较低的 temperaturetemperature:0.7# 是否启用思考模式 按模型和 Spring AI 版本支持情况选择thinking:type:enabled在 Linux 或 macOS 中设置环境变量exportDEEPSEEK_API_KEY你的 DeepSeek API KeyWindows PowerShell$env:DEEPSEEK_API_KEY 你的 DeepSeek API Key关于模型名称不同时间点的 DeepSeek API 和 Spring AI 版本可能使用不同的模型名称。例如新版 DeepSeek API 文档中可见deepseek-flash、deepseek-v4-pro部分旧版示例使用deepseek-chat、deepseek-reasonerSpring AI 某些版本的默认值或示例可能出现deepseek-v4-flash、deepseek-v4-pro。如果启动后出现模型不存在、模型已下线等错误应以 DeepSeek 控制台和当前 API 文档中的可用模型列表为准并修改spring.ai.deepseek.chat.model。四、编写启动类packagecom.example.deepseek;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;SpringBootApplicationpublicclassDeepSeekApplication{publicstaticvoidmain(String[]args){SpringApplication.run(DeepSeekApplication.class,args);}}添加spring-ai-starter-model-deepseek后Spring Boot 会自动创建 DeepSeek Chat 模型相关 Bean同时提供可注入的ChatClient.Builder。五、使用ChatClient调用 DeepSeek推荐使用 Spring AI 的ChatClient它提供了简洁的链式 API。packagecom.example.deepseek.controller;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassChatController{privatefinalChatClientchatClient;publicChatController(ChatClient.BuilderchatClientBuilder){this.chatClientchatClientBuilder.build();}GetMapping(/ai/chat)publicStringchat(RequestParam(valuemessage,defaultValue请介绍一下 Spring AI)Stringmessage){returnchatClient.prompt().user(message).call().content();}}启动项目mvn spring-boot:run调用接口curl--gethttp://localhost:8080/ai/chat\--data-urlencodemessageSpring AI 的 ChatClient 有什么作用返回结果就是 DeepSeek 模型生成的文本 。六、设置系统提示词在实际项目中通常需要通过系统提示词约束模型的角色和输出风格。例如让模型始终以 Java 专家的身份回答问题packagecom.example.deepseek.config;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;ConfigurationpublicclassAiConfig{BeanpublicChatClientchatClient(ChatClient.Builderbuilder){returnbuilder.defaultSystem(你是一名资深 Java 专家请使用简洁、准确的中文回答问题。).build();}}此时控制器可以直接注入已经配置好的ChatClientpackagecom.example.deepseek.controller;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassChatController{privatefinalChatClientchatClient;publicChatController(ChatClientchatClient){this.chatClientchatClient;}GetMapping(/ai/java-question)publicStringjavaQuestion(RequestParamStringquestion){returnchatClient.prompt().user(question).call().content();}}七、使用 Service 层封装调用逻辑如果项目规模较大建议不要把所有 AI 调用逻辑写在 Controller 中可以通过 Service 统一封装packagecom.example.deepseek.service;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.stereotype.Service;ServicepublicclassDeepSeekService{privatefinalChatClientchatClient;publicDeepSeekService(ChatClient.Builderbuilder){this.chatClientbuilder.defaultSystem(你是一个专业、严谨的中文智能助手。).build();}publicStringchat(Stringmessage){returnchatClient.prompt().user(message).call().content();}}Controllerpackagecom.example.deepseek.controller;importcom.example.deepseek.service.DeepSeekService;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassDeepSeekController{privatefinalDeepSeekServicedeepSeekService;publicDeepSeekController(DeepSeekServicedeepSeekService){this.deepSeekServicedeepSeekService;}GetMapping(/ai/ask)publicStringask(RequestParamStringmessage){returndeepSeekService.chat(message);}}八、在运行时覆盖模型参数除了在application.yml中设置默认参数也可以针对某一次请求使用运行时选项覆盖模型和温度。不同 Spring AI 版本的选项构造器 API 可能略有变化下面给出常见写法importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.ai.deepseek.DeepSeekChatOptions;publicStringcreativeChat(ChatClientchatClient,Stringmessage){returnchatClient.prompt().user(message).options(DeepSeekChatOptions.builder().model(deepseek-flash).temperature(1.2).build()).call().content();}如果编译器提示DeepSeekChatOptions的构造方法或方法名不匹配请以当前 Spring AI 版本的 JavaDoc 为准因为不同版本可能使用withModel、withTemperature或新的 builder 方法命名。九、异常处理建议生产环境不要把完整异常堆栈直接返回给前端可以统一处理异常并记录请求 IDpackagecom.example.deepseek.handler;importorg.springframework.http.HttpStatus;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ResponseStatus;importorg.springframework.web.bind.annotation.RestControllerAdvice;importjava.util.Map;RestControllerAdvicepublicclassGlobalExceptionHandler{ExceptionHandler(Exception.class)ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)publicMapString,StringhandleException(Exceptionex){// 实际项目中应使用日志框架记录 ex不建议将详细异常返回给客户端returnMap.of(message,AI 服务调用失败请稍后重试);}}对于网络抖动、临时服务不可用等问题可以结合 Spring AI 的spring.ai.retry配置调整重试策略spring:ai:retry:max-attempts:3backoff:initial-interval:1smultiplier:2max-interval:10s# 是否对客户端 4xx 错误进行重试通常保持 falseon-client-errors:false不要对无效 API Key、参数错误等 4xx 错误进行无限重试否则可能放大问题并增加调用成本。十、常见问题1. 启动时报 API Key 为空确认环境变量已经设置并且启动 Spring Boot 的终端能够读取到该变量echo$DEEPSEEK_API_KEY也可以临时在本地application.yml中配置但不要提交到公共仓库spring:ai:deepseek:api-key:sk-xxxxxxxx2. 返回 401 Unauthorized通常表示 API Key 无效、已撤销或请求使用了错误的账号密钥。重新检查 DeepSeek 控制台中的 Key并确认没有多余的空格和引号。3. 返回模型不存在检查spring.ai.deepseek.chat.model。模型名称会随着 DeepSeek API 版本调整优先使用账户当前可用的模型名。旧教程中的deepseek-chat不一定适用于当前账号或当前 API。4. 找不到ChatClient.Builder确认已添加spring-ai-starter-model-deepseekSpring AI BOM 与 starter 版本一致没有错误地使用旧版模块名项目确实启用了 Spring Boot 自动配置。5. 为什么不直接使用 WebClient 调用接口直接使用 WebClient 当然可以但需要自己处理请求结构、响应解析、重试、模型选项和消息抽象。Spring AI 的价值在于提供统一的 Chat Model 和ChatClient抽象后续切换其他模型时业务代码改动更小。十一、项目目录示例spring-ai-deepseek-demo ├── pom.xml └── src └── main ├── java │ └── com/example/deepseek │ ├── DeepSeekApplication.java │ ├── config │ │ └── AiConfig.java │ ├── controller │ │ └── ChatController.java │ └── service │ └── DeepSeekService.java └── resources └── application.yml十二、总结使用 Spring AI 接入 DeepSeek 的核心步骤只有三步在pom.xml中引入spring-ai-starter-model-deepseek在application.yml中配置spring.ai.deepseek.api-key和模型名称注入ChatClient.Builder通过prompt().user(...).call().content()发起调用。完整调用代码非常简洁returnchatClient.prompt().user(message).call().content();在生产环境中还应进一步完善 API Key 管理、超时控制、重试策略、日志脱敏、调用限流、Token 成本统计以及敏感内容审核等机制。参考资料Spring AI DeepSeek Chat 官方文档Spring AI Getting StartedSpring AI ChatClient 官方文档DeepSeek API 官方文档DeepSeek API Keys
返回列表