Spring AI 快速入门与实战指南
在当今技术浪潮中,人工智能已成为行业标配。作为主流 Java 开发框架,Spring 社区顺势推出了 Spring AI 框架,旨在将 Spring 生态的设计原则(如可移植性、模块化)应用于 AI 领域,让开发者能用少量代码实现组件替换,轻松构建大模型应用。
1. Spring AI 简介
1.1 核心概念
Spring AI 是一个 AI 工程领域的应用程序框架。它的核心在于提供了开发 AI 大模型应用所需的基本抽象模型,这些抽象拥有多种实现方式。简单来说,它提供了一个友好的 API 和开发 AI 应用的抽象,简化了 AI 大模型应用的开发工作。
目前版本分为预览版 (PRE)、快照版 (SNAPSHOT) 和正式版 (GA)。推荐使用 GA 版本以保证稳定性,SNAPSHOT 则用于持续更新测试。
1.2 主要功能
- 多模型支持:涵盖 OpenAI、DeepSeek、Microsoft、Ollama、Amazon、Google HuggingFace 等主流供应商。
- 多模态能力:支持聊天、文本到图像、文本到声音等模型类型。
- 向量数据库集成:支持 Azure Vector Search、Chroma、Milvus、Neo4j、Redis 等 Embedding Models。
- 函数调用:允许大语言模型触发预定义的外部函数,实现动态数据获取或业务逻辑操作。
- 自动配置:支持 Spring Boot 自动配置,便于运行 AI 模型和管理向量库。
2. 快速入门:集成 DeepSeek
2.1 准备工作
DeepSeek 是一款由深度求索开发的 AI 大模型,基于 Transformer 架构,在成本、性能及多模态处理上表现优异。要集成 DeepSeek,首先需要获取 API Key。
访问 DeepSeek 开放平台注册账号并创建 API Key,同时建议完成实名认证以便充值使用。
2.2 项目搭建
创建一个 SpringBoot 父模块 springAiProject 和一个子模块 springai_hello。注意 Spring AI 对 JDK 版本有要求(建议 JDK 17+)。
引入依赖
在父模块的 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>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配置文件
在子模块的 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 控制生成文本的多样性,值越高越随机,值越低越确定。
编写代码
启动类保持默认即可。Controller 层注入 OpenAiChatModel 进行简单对话:
package com.example.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 的聊天模型 API 为开发者提供了便捷通道,能够无缝集成强大的 AI 驱动聊天功能。
3.1 ChatClient 接口
ChatClient 是定义与聊天服务交互客户端的核心接口。它允许我们定制客户端行为,设置请求规范并发起请求。
简单对话
通过 ChatClient.Builder 注入客户端,使用 prompt() 链式调用设置用户消息:
package com.example.ai.controller;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChatController {
private final ChatClient chatClient;
// 通过构造方法来注入 ChatClient
public ChatController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
@GetMapping("/chat")
public String chat(@RequestParam(value = "message", defaultValue = "你是谁") String message) {
// prompt: 提示词
return this.chatClient.prompt()
.user(message)
.call()
.content();
}
}
角色预设
可以通过配置类设置默认的系统提示词(System Prompt),让 AI 扮演特定角色:
package com.example.ai.config;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AIConfig {
@Bean
public ChatClient chatClient(ChatClient.Builder builder) {
return builder.defaultSystem("你是一名 Java 开发专家,精通 Spring 框架。").build();
}
}
流式响应
非流式输出 (call) 需等待模型生成完整结果,而流式输出 (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 定义了与 AI 模型交互的基本方法。虽然 ChatClient 底层使用了 ChatModel,但在需要更精细控制时(如直接操作 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)
函数调用功能允许大语言模型在生成回答时触发预定义的外部函数,从而实现动态数据获取或业务逻辑操作。
4.1 核心流程
- 定义函数:声明可供模型调用的函数(名称、描述、参数结构)。
- 模型交互:将函数信息与用户输入一起发送给模型,模型决定是否需要调用函数。
- 执行函数:解析模型的函数调用请求,执行对应的业务逻辑。
- 返回结果:将函数执行结果返回给模型,生成最终回答。
4.2 实现示例
自定义一个计算器服务,包含加法和乘法运算:
package com.example.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import java.util.function.Function;
@Slf4j
@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;
};
}
}
在 Controller 中启用这些函数:
@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
Ollama 是一个用于本地化部署和管理大型语言模型的工具,支持多种开源模型。
5.1 安装与配置
- 下载并安装 Ollama。
- 设置环境变量
OLLAMA_MODELS指定模型存储路径。 - 拉取模型,例如:
ollama pull deepseek-r1:1.5b。 - 启动服务,默认监听
http://localhost:11434。
5.2 代码集成
添加 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 是阿里云通义系列模型及服务在 Java AI 应用开发领域的最佳实践,提供了完整的开源配套。
6.1 快速开始
- 申请阿里云 API Key(百炼大模型推理服务)。
- 引入
spring-ai-alibaba-starter依赖。 - 配置
spring.ai.dashscope.api-key。
6.2 代码示例
private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手,请根据用户提问回答!";
private ChatClient dashScopeChatClient;
public SpringAiAlibabaController(ChatClient.Builder chatClientBuilder) {
this.dashScopeChatClient = chatClientBuilder
.defaultSystem(DEFAULT_PROMPT)
.defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
.defaultOptions(DashScopeChatOptions.builder().withTopP(0.7).build())
.build();
}
7. 其他模型能力
7.1 图像模型
Spring AI 提供了 Image Model API,支持文生图功能。通过 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 语音模型
Text-to-Speech API 支持将文字内容转化为语音,可配置语速、音调、音量等参数。
8. RAG 检索增强生成
RAG (Retrieval-Augmented Generation) 结合了检索系统和生成模型,利用外部知识库帮助大模型生成更加准确、有依据的回答,有效解决知识局限性和幻觉问题。
8.1 工作流程
- 用户输入问题。
- 问题向量化:调用 Embedding 模型将问题转换为高维向量。
- 向量数据库检索:检索知识库中相似的文档片段。
- 构建上下文:结合系统提示词和检索结果构造 Prompt。
- 调用 LLM:生成最终回答。
8.2 实现步骤
创建子模块,配置 VectorStore 和 EmbeddingModel,并在 Controller 中使用 QuestionAnswerAdvisor 关联向量库。
@GetMapping(value = "/chat", produces = "text/plain; charset=UTF-8")
public String generation(@RequestParam("userInput") String userInput) {
return dashScopeChatClient.prompt()
.user(userInput)
.advisors(new QuestionAnswerAdvisor(vectorStore))
.call()
.content();
}
9. 综合案例:智能简历筛选
本案例展示如何结合 RAG 知识库、函数调用和人设设定,构建一个招聘助手。
9.1 环境搭建
创建子模块,配置端口及依赖。
9.2 构建知识库
将候选人简历文本放入资源目录,通过 TextReader 读取并切分,存入向量数据库。
9.3 工具与规则
定义查询岗位的工具函数,并编写详细的人设提示词,明确助手的职责、限制及个性化风格。
9.4 整合应用
在 Controller 中串联人设、知识库和工具,接收用户查询后,先检索相关简历信息,再结合工具返回结果生成专业建议。
@GetMapping("/ai/agent")
public String agent(@RequestParam("query") String query) {
// 检索向量库
List<Document> documents = vectorStore.similaritySearch(query);
String info = documents.size() > 0 ? documents.get(0).getContent() : "";
// 构造 Prompt
String systemPrompt = "..."; // 人设描述
String userPrompt = "给你提供一些数据参考:{info},请回答我的问题:{query}。";
// ... 调用 ChatModel
}
通过以上步骤,我们可以快速构建出具备记忆、工具调用及知识库检索能力的复杂 AI 应用。


