跳到主要内容
Spring AI 框架入门与实战指南 | 极客日志
Java AI java
Spring AI 框架入门与实战指南 Spring AI 是 Spring 生态系统面向人工智能领域的扩展框架,旨在简化大模型应用的开发。本文涵盖环境搭建、聊天模型(ChatClient/ChatModel)、函数调用、本地部署(Ollama)、阿里云集成(DashScope)以及图像语音模型的使用。重点讲解了 RAG(检索增强生成)的实现流程,并通过简历筛选案例展示了综合应用。内容包含依赖配置、代码示例及关键注意事项,帮助开发者快速上手 Java AI 应用开发。
FrontendX 发布于 2026/3/26 0 浏览Spring AI 框架入门与实战指南
1. Spring AI 简介
Spring AI 是 Spring 生态系统面向人工智能领域的扩展框架,旨在将 Spring 的设计原则(如可移植性和模块化)应用于 AI 领域。它提供了开发 AI 大模型应用所需的基本抽象模型,使得开发者可以用很少的代码改动就能实现组件的轻松替换。
1.1 核心特性
多模型支持 :兼容主流 AI 供应商,如 OpenAI、DeepSeek、Ollama、Google 等。
多种模态 :支持聊天、文本到图像、文本到声音等模型类型。
向量数据库集成 :内置对 Embedding Models 和向量数据库的支持,如 Milvus、Redis、PostgreSQL 等。
函数调用 :支持 Function Calling,允许模型触发外部函数。
自动配置 :基于 Spring Boot 的自动配置,便于快速启动和管理。
2. 环境搭建与快速入门
2.1 准备工作
在开始之前,需要准备好 API Key。以 DeepSeek 为例,访问其开放平台注册账号并创建 API Key。确保已完成实名认证并根据需求充值。
2.2 创建工程
使用 IDEA 创建一个 SpringBoot 项目。注意 Spring AI 对 SpringBoot 和 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 >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
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
<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 和基础 URL:
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 编写代码 @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 角色预设 可以在配置类中定义默认的 System Prompt,设定 AI 的人设:
@Configuration
public class AIConfig {
@Bean
public ChatClient chatClient (ChatClient.Builder builder) {
return builder.defaultSystem("你是一名 Java 开发专家,精通技术细节。" ).build();
}
}
3.1.3 流式响应 对于长文本生成,流式输出能显著提升用户体验。使用 stream() 方法替代 call():
@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 接口,继承自 Model<Prompt, ChatResponse>。它更接近底层实现,适合需要精细控制 Prompt 结构的场景。
@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 定义函数 只需定义一个返回 java.util.Function 并用 @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() 方法告知 ChatClient 要使用的函数名称:
@GetMapping(value = "/function")
public String ragJsonText (@RequestParam(value = "message") String message) {
return ChatClient.builder(chatModel).build()
.prompt()
.system("您是算术计算器的代理。当用户询问数学计算时,您必须调用相应的函数来处理。" )
.user(message)
.functions("addOperation" , "mulOperation" )
.call()
.content();
}
5. 本地部署与 Ollama Ollama 是一个用于本地化部署和管理大型语言模型的工具,方便开发者在本地运行开源模型。
5.1 安装与拉取
下载并安装 Ollama。
设置环境变量 OLLAMA_MODELS 指定模型存储路径。
执行命令拉取模型,例如:ollama pull deepseek-r1:1.5b。
启动服务:ollama run deepseek-r1:1.5b。
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
代码部分与 OpenAI 类似,只需注入 OllamaChatModel 即可。
6. Spring AI Alibaba Spring AI Alibaba 是阿里云通义系列模型在 Java 领域的最佳实践,提供了完整的开源配套。
6.1 快速入门
申请阿里云 API Key。
引入 spring-ai-alibaba-starter 依赖。
配置 spring.ai.dashscope.api-key。
排除默认 OpenAI 自动配置以避免冲突。
@Autowired
private ChatClient dashScopeChatClient;
@GetMapping("/simple/chat")
public String simpleChat (@RequestParam("query") String query) {
return dashScopeChatClient.prompt(query).call().content();
}
7. 其他模型能力 除了文本聊天,Spring AI 还支持图像生成和语音合成。
7.1 图像模型 使用 ImageModel 接口,输入文本提示词,输出图片 URL 或二进制数据。
@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 将文本转换为音频文件。
@GetMapping("/tts")
public void tts () throws IOException {
DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()
.withSpeed(1.0 )
.withPitch(0.9 )
.withVolume(60 )
.build();
SpeechSynthesisResponse response = speechSynthesisModel.call(new SpeechSynthesisPrompt (TEXT, options));
}
8. RAG (检索增强生成) RAG 结合了检索系统和生成模型,利用外部知识库帮助大模型生成更准确、有依据的回答,解决知识局限性和幻觉问题。
8.1 工作流程
向量化 :将文档内容转换为高维向量。
检索 :根据用户问题向量,在向量数据库中查找相似片段。
构建上下文 :将检索到的片段与系统提示词结合。
生成回答 :LLM 基于上下文生成最终答案。
8.2 实现步骤
创建 VectorStore Bean,加载文档并初始化嵌入模型。
在 Controller 中使用 QuestionAnswerAdvisor 关联向量存储。
@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;
}
9. 综合案例:智能简历筛选助手 本案例整合了 RAG 知识库、函数调用和人设设定,构建一个招聘助手。
9.1 知识库构建 将候选人简历文本放入 resource 目录,通过 TextReader 读取并切分后存入向量库。
9.2 工具与功能 定义查询岗位的工具函数,并在 Prompt 中启用。
9.3 人设设定 在 System Prompt 中明确助手的角色、指导原则及限制条件,确保回答专业且合规。
9.4 测试 调用接口传入查询语句,系统会自动检索简历信息并结合工具返回结果生成建议。
通过以上步骤,你可以快速掌握 Spring AI 的核心用法,从简单的聊天机器人到复杂的 RAG 应用,都能利用该框架高效实现。
相关免费在线工具 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
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online