尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
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
RELATED

相关推荐

SPFA 算法简介及经典实例

SPFA 算法简介及经典实例

● SPFA 算法 (1)SPFA 算法,即最短路径快速算法,是基于 Bellman-Ford 算法优化而来的单源最短路径算法,适用于带负权边、无负权环的有向图或无向图,在算法竞赛中应用广泛。 (2)SPFA …

📅 2026/9/30 2:46:39
GCC 参数记不住?这份语法速查 + 多参数组合示例,收藏就够

GCC 参数记不住?这份语法速查 + 多参数组合示例,收藏就够

代码写得没问题,一编译却蹦出一堆 undefined reference to xxx。改了半天,最后发现是命令里库的顺序写反了。今天把 GCC 语法、核心参数、多参数组合,以及最容易踩的链接顺序坑,一篇讲清。 一、gcc 基本语法 一条 gcc 命令长这样…

📅 2026/9/30 2:46:39
Kubernetes 1.30 从零安装实战:架构、二进制与 kubeadm 全解析

Kubernetes 1.30 从零安装实战:架构、二进制与 kubeadm 全解析

一、前置规划(集群设计) 1.网络规划 根据自己资源合理规划 2. 网络规划 集群 Pod 网段:10.244.0.0/16(Flannel/Calico 默认网段) 集群 Service 网段:10.96.0.0/12(K8s 默认 Service 网段&a…

📅 2026/9/30 2:46:38
MORE NEWS

更多资讯

📰

视觉SLAM全流程实战:从算法原理到嵌入式部署与调优

1. 视觉SLAM到底在解决什么问题:先把需求想清楚再谈算法聊视觉SLAM之前,我更愿意先说清楚它到底在干什么。一句话概括:让一台只有摄像头的设备,在完全陌生的环境里,一边走一边算出自己在哪儿、朝向哪,同时把…

📰

从零手搓AI工程:数据管线、模型推理优化与FastAPI服务部署实战

1. 从零手搓AI工程:为什么我不建议你直接调包很多人一听到“AI工程”这四个字,第一反应就是打开某个云平台,拖几个预训练模型出来,拼一个API调用链,然后对外宣称自己做了个AI应用。我早期也这么干过,结果在…

📰

护网行动红蓝对抗实战:从攻击链路到防御体系的完整指南

📌写在前面 “护网行动是什么?”“红队和蓝队分别做什么?”“怎么准备护网?” 护网行动(网络攻防演练)是国内规模最大的网络安全实战演习。红队模拟攻击者,从外网打点到内网渗透;蓝队…

📰

Model-Optimizer:大模型GPU推理的工程方法论与实战调优

1. “Model-Optimizer”不是工具名,而是工程共识的具象化表达 你搜“Model-Optimizer”,首页跳出来的全是TensorRT、vLLM、TensorRT-LLM这些词——没有独立官网、没有GitHub star破万的仓库、没有PyPI上可pip install的包。这恰恰说明一件事&#xff1a…

📰

大模型推理优化实战:TensorRT、vLLM与Model-Optimizer工程方法论

1. 项目概述:Model-Optimizer 不是工具名,而是一类工程实践的统称 “Model-Optimizer”这个词在当前技术社区里,经常被误当成某个具体软件或开源项目的名字——比如有人搜“Model-Optimizer 下载”“Model-Optimizer 官网”,结果…

📰

TensorFlow 2024实操指南:从安装到部署的完整避坑手册

我记得大概从2022年开始,网上聊到深度学习框架,声音几乎是清一色的PyTorch。论文代码是PyTorch,开源项目是PyTorch,就连招聘JD里都恨不得把PyTorch写在第一行。那TensorFlow呢?在很多人的认知里,它已经成了…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬