跳到主要内容
Spring AI 框架入门:从 DeepSeek 集成到 RAG 实战 | 极客日志
Java AI java 算法
Spring AI 框架入门:从 DeepSeek 集成到 RAG 实战 Spring AI 是 Java 生态下的 AI 工程框架,其核心功能与实战用法。内容涵盖 DeepSeek 云端集成、本地 Ollama 部署、阿里云 DashScope 接入,以及 ChatClient 与 ChatModel 的使用差异。此外还包含函数调用机制、图像与语音模型示例,重点讲解了 RAG 检索增强生成的实现流程,并通过智能简历筛选案例展示了知识库构建与 Agent 开发技巧。适合希望快速掌握大模型应用开发的 Java 工程师参考。
FlinkHero 发布于 2026/3/28 更新于 2026/4/25 1 浏览Spring AI 框架入门:从 DeepSeek 集成到 RAG 实战
在当今的技术浪潮中,人工智能已成为行业标配。作为主流 Java 开发框架,Spring 社区紧跟趋势推出了 Spring AI 框架,旨在将 Spring 的设计原则应用于 AI 领域。
1. Spring AI 简介
1.1 什么是 Spring AI
Spring AI 是一个面向 AI 工程的应用程序框架。它的核心目标是将 Spring 生态系统的可移植性和模块化设计思想引入 AI 开发,让开发者能用 POJO 构建 AI 应用。简单来说,它提供了一套友好的 API 和抽象模型,简化了大模型应用的开发工作,使得在不同 AI 组件间切换变得轻而易举。
目前版本包括预览版 (PRE)、快照版 (SNAPSHOT) 和正式版 (GA)。对于生产环境,建议优先使用 GA 版本以确保稳定性。
1.2 主要功能
多模型支持 :涵盖 OpenAI、DeepSeek、Ollama、Google HuggingFace 等主流供应商。
多模态能力 :支持聊天、文生图、文转音等多种模型类型。
向量数据库集成 :内置对 Azure Vector Search、Milvus、Redis、PostgreSQL/PGVector 等的支持。
函数调用 :原生支持 Function Calling,方便与大模型交互外部工具。
自动配置 :基于 Spring Boot 的自动配置,快速启动 AI 模型。
2. 快速入门:集成 DeepSeek
2.1 准备工作
DeepSeek 是一款高性能的国产大模型,凭借极具竞争力的定价和开源策略,在技术圈备受关注。要将其集成到 Java 应用中,我们可以借助 Spring AI。
首先需要在 DeepSeek 开放平台注册账号并创建 API Key。登录官网后,进入 API 管理页面即可获取密钥。记得完成实名认证以便充值使用。
2.2 搭建 SpringBoot 工程
创建一个 SpringBoot 项目(父模块 springAiProject)及子模块 springai_hello。注意 Spring AI 对 JDK 版本有要求,建议使用 JDK 17 及以上。
2.2.1 引入依赖
在父模块的 pom.xml 中添加公共依赖管理:
<properties >
<maven.compiler.source > 17</maven.compiler.source >
<maven.compiler.target > 17</maven.compiler.target >
<spring-ai.version > 1.0.0-M5</spring-ai.version >
</properties >
<dependencies >
<dependency >
org.springframework.boot
spring-boot-starter-web
org.springframework.ai
spring-ai-openai-spring-boot-starter
org.projectlombok
lombok
1.18.30
org.springframework.ai
spring-ai-bom
${spring-ai.version}
pom
import
<groupId >
</groupId >
<artifactId >
</artifactId >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<version >
</version >
</dependency >
</dependencies >
<dependencyManagement >
<dependencies >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<version >
</version >
<type >
</type >
<scope >
</scope >
</dependency >
</dependencies >
</dependencyManagement >
2.2.2 配置文件 在子模块的 application.properties 中配置 API Key 和基础信息:
server.port=8899
spring.application.name=spring-ai-deepseek-demo
# DeepSeek 的 Api key
spring.ai.openai.api-key=sk-****************
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
这里的 temperature 参数控制生成文本的多样性。值越高越随机,值越低越稳定。
2.2.3 编写代码 创建启动类 SpringAiHelloApplication 和 Controller ChatDeepSeekController:
@SpringBootApplication
public class SpringAiHelloApplication {
public static void main (String[] args) {
SpringApplication.run(SpringAiHelloApplication.class, args);
}
}
package com.atguigu.ai.controller;
import jakarta.annotation.Resource;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChatDeepSeekController {
@Resource
private OpenAiChatModel chatModel;
@GetMapping("/ai/generate")
public String generate (@RequestParam(value = "message", defaultValue = "hello") String message) {
String response = this .chatModel.call(message);
System.out.println("response: " + response);
return response;
}
}
访问 localhost:8899/ai/generate?message=尚硅谷 即可测试接口。
3. 聊天模型详解 Spring AI 提供了两种主要的聊天模型交互方式:ChatClient 和 ChatModel。
3.1 ChatClient 接口 ChatClient 是更高级的客户端接口,适合构建复杂的对话流。它允许我们灵活设置请求规范。
3.1.1 简单对话 通过 ChatClient.Builder 注入客户端,使用链式调用发送请求:
@GetMapping("/chat")
public String chat (@RequestParam(value = "message", defaultValue = "你是谁") String message) {
return this .chatClient.prompt()
.user(message)
.call()
.content();
}
3.1.2 角色预设 我们可以通过配置 Bean 来设定默认的系统角色,这样每次对话都会带上预设背景:
@Configuration
public class AIConfig {
@Bean
public ChatClient chatClient (ChatClient.Builder builder) {
return builder.defaultSystem("你是一名 Java 技术专家,精通 Spring 框架。" ).build();
}
}
3.1.3 流式响应 非流式输出需要等待模型生成完毕,而流式输出 (stream) 则逐个字符返回,用户体验更佳,尤其在大模型推理较慢时:
@GetMapping(value = "/chat/stream", produces = "text/html;charset=UTF-8")
public Flux<String> chatStream (@RequestParam(value = "message") String message) {
return chatClient.prompt().user(message).stream().content();
}
3.2 ChatModel 接口 ChatModel 是更底层的接口,直接继承自 Model<Prompt, ChatResponse>。虽然 ChatClient 底层也是基于它,但在某些需要精细控制 Prompt 的场景下,直接使用 ChatModel 更方便。
@GetMapping("/chatModel02")
public String chatModel02 (@RequestParam("message") String message) {
ChatResponse call = chatModel.call(new Prompt (
message,
OpenAiChatOptions.builder()
.model("deepseek-chat" )
.temperature(0.8 )
.build()
));
return call.getResult().getOutput().getContent();
}
4. 函数调用 (Function Calling) 函数调用允许大模型在回答时触发预定义的外部函数,比如查询数据库或执行计算。这是实现 Agent 智能体的关键能力。
4.1 自定义 Function 我们需要定义一个 Java 函数,并用 @Bean 标注,同时添加描述信息供模型理解:
@Configuration
public class CalculatorService {
public record AddOperation (int a, int b) {}
public record MulOperation (int m, int n) {}
@Bean
@Description("加法运算")
public Function<AddOperation, Integer> addOperation () {
return request -> {
log.info("执行加法运算:{} + {} = {}" , request.a, request.b, request.a + request.b);
return request.a + request.b;
};
}
@Bean
@Description("乘法运算")
public Function<MulOperation, Integer> mulOperation () {
return request -> {
log.info("执行乘法运算:{} * {} = {}" , request.m, request.n, request.m * request.n);
return request.m * request.n;
};
}
}
4.2 启用函数调用 在 Controller 中,通过 .functions() 方法告知模型可以使用哪些函数,并配合 System Prompt 引导其行为:
@GetMapping(value = "/function", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public String ragJsonText (@RequestParam(value = "message") String message) {
return ChatClient.builder(chatModel).build()
.prompt()
.system("""
您是算术计算器的代理。您能够支持加法运算、乘法运算等操作。
当用户询问数学计算时,您必须调用相应的函数来处理。
支持的函数:
- addOperation: 加法运算,需要两个数字参数
- mulOperation: 乘法运算,需要两个数字参数
请用中文回复,并在适当的时候调用函数。
""" )
.user(message)
.functions("addOperation" , "mulOperation" )
.call()
.content();
}
5. 本地部署 Ollama 如果不想依赖云端 API,可以使用 Ollama 在本地运行开源模型。
5.1 安装与配置 下载并安装 Ollama 客户端,设置环境变量 OLLAMA_MODELS 指定模型存储路径。拉取模型示例:
ollama pull deepseek-r1:1.5b
启动服务后,默认监听 http://localhost:11434。
5.2 Spring AI 集成 引入 spring-ai-ollama-spring-boot-starter 依赖,配置 base-url 指向本地地址:
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=deepseek-r1:1.5b
代码逻辑与云端类似,只需注入 OllamaChatModel 即可。
6. Spring AI Alibaba 针对国内开发者,阿里云推出了 Spring AI Alibaba,深度集成了通义千问系列模型。
6.1 快速接入 申请阿里云百炼 API Key,引入 spring-ai-alibaba-starter 依赖。注意排除默认的 OpenAI 自动配置以避免冲突:
spring.autoconfigure.exclude=org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration
spring.ai.dashscope.api-key=sk-*****cf
6.2 代码示例 利用 ChatClient 结合 Advisor 实现对话记忆和日志记录:
this .dashScopeChatClient = chatClientBuilder
.defaultSystem(DEFAULT_PROMPT)
.defaultAdvisors(new MessageChatMemoryAdvisor (new InMemoryChatMemory ()))
.defaultAdvisors(new SimpleLoggerAdvisor ())
.defaultOptions(DashScopeChatOptions.builder().withTopP(0.7 ).build())
.build();
7. 其他模型能力 除了文本对话,Spring AI 还支持图像生成和语音合成。
7.1 图像模型 使用 ImageModel 接口,输入文本提示词即可生成图片。例如生成一只小猫:
@GetMapping("/generate-image")
public void getImage (@RequestParam(value = "msg", defaultValue = "生成一只小猫") String msg, HttpServletResponse res) {
ImageResponse response = imageModel.call(new ImagePrompt (
msg,
DashScopeImageOptions.builder()
.withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
.withN(1 )
.withHeight(1024 )
.withWidth(1024 )
.build()
));
}
7.2 语音模型 通过 SpeechSynthesisModel 将文本转为音频文件,支持语速、音调调节:
DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()
.withSpeed(1.0 )
.withPitch(0.9 )
.withVolume(60 )
.build();
8. RAG 检索增强生成 RAG (Retrieval-Augmented Generation) 能有效解决大模型知识滞后和幻觉问题。
8.1 核心流程
向量化 :将文档转换为高维向量。
检索 :在向量数据库中查找相似片段。
生成 :将检索结果作为上下文提供给 LLM。
8.2 实现步骤 配置 SimpleVectorStore 加载文档,并使用 QuestionAnswerAdvisor 增强 ChatClient:
@Bean
VectorStore vectorStore (@Qualifier("dashscopeEmbeddingModel") EmbeddingModel embeddingModel) {
SimpleVectorStore simpleVectorStore = SimpleVectorStore.builder(embeddingModel).build();
List<Document> documents = List.of(new Document ("产品说明:名称:Java 开发语言..." ));
simpleVectorStore.add(documents);
return simpleVectorStore;
}
return dashScopeChatClient.prompt()
.user(userInput)
.advisors(new QuestionAnswerAdvisor (vectorStore))
.call()
.content();
9. 综合案例:智能简历筛选 结合 RAG 知识库与函数调用,我们可以构建一个招聘助手。
9.1 知识库构建 TokenTextSplitter splitter = new TokenTextSplitter (1200 , 350 , 5 , 100 , true );
splitter.apply(documents);
simpleVectorStore.add(documents);
9.2 工具与 Prompt 定义查询岗位的函数 recruitServiceFunction,并在 Prompt 中明确人设和限制条件:
String systemPrompt = """
角色与目标:你是一个招聘助手,会针对用户的问题,结合候选人经历,岗位匹配度等专业知识,给用户提供指导。
指导原则:你需要确保给出的建议合理科学,不会对候选人的表现有言论侮辱。
限制:在提供建议时,需要强调在个性建议方面用户仍然需要线下寻求专业咨询。
""" ;
9.3 测试 调用接口 localhost:8896/ai/agent?query=java 语言有哪些特性,系统会自动检索简历内容并结合工具返回结果进行回答。
通过以上步骤,我们完成了从基础集成到复杂 RAG 应用的全流程实践。Spring AI 极大地降低了 Java 开发者接入大模型的门槛,让 AI 能力能像普通业务代码一样被优雅地编排和管理。
相关免费在线工具 Keycode 信息 查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
Escape 与 Native 编解码 JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
JavaScript / HTML 格式化 使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
JavaScript 压缩与混淆 Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online