Spring AI 简介
Spring AI 是 Spring 官方推出的 AI 应用开发框架,为 Java 生态系统提供与 Python 世界中 LangChain 类似的能力。
什么是 Spring AI?
Spring AI 是一个 AI 工程框架,它提供以下功能:
- 抽象层:统一不同 AI 模型提供商的 API
- RAG 支持:检索增强生成模式开箱即用
- 函数调用:让 LLM 能够调用 Java 方法
- 向量数据库集成:支持多种向量存储
- Spring Boot 集成:与 Spring 生态系统无缝集成
核心特性
1. 模型抽象
java
// 统一的模型接口
ChatModel chatModel = new OpenAiChatModel(apiKey);
// 切换不同模型只需更换实现
// ChatModel chatModel = new AzureOpenAiChatModel(...);
// ChatModel chatModel = new AnthropicChatModel(...);2. Prompt 模板
java
// 类似 Python f-string 的模板
String prompt = """
翻译以下文本为 {language}:
{text}
""";
ChatResponse response = chatModel.call(
new Prompt(prompt, Map.of("language", "中文", "text", "Hello"))
);3. RAG 模式
java
// 向量数据库检索
VectorStore vectorStore = new PgVectorStore(jdbcTemplate, embeddingModel);
List<Document> documents = vectorStore.similaritySearch(
SearchRequest.query("如何使用 Spring AI?").withTopK(5)
);
// 生成回答
String answer = chatModel.call(documents);4. 函数调用
java
// 定义函数
@Bean
public Function<WeatherRequest, WeatherResponse> weatherFunction() {
return request -> {
// 调用天气 API
return new WeatherResponse("晴天", 25);
};
}
// LLM 自动调用
ChatResponse response = chatModel.call(
new Prompt("北京今天天气怎么样?")
.withFunctions(List.of("weatherFunction"))
);支持的模型提供商
- ✅ OpenAI (GPT-3.5, GPT-4)
- ✅ Azure OpenAI
- ✅ Anthropic (Claude)
- ✅ Hugging Face
- ✅ Bedrock (AWS)
- ✅ Vertex AI (Google Cloud)
- ✅ Ollama (本地模型)
向量数据库支持
- SQL 数据库: PostgreSQL (PgVector), MySQL, Oracle
- NoSQL 数据库: MongoDB, Cassandra
- 专用向量库: Milvus, Weaviate, Qdrant
- 云服务: Azure AI Search, Elasticsearch
快速开始
1. 添加依赖
xml
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>1.0.0-M1</version>
</dependency>2. 配置 application.yml
yaml
spring:
ai:
openai:
api-key: ${OPENAI_API_KEY}
chat:
options:
model: gpt-4
temperature: 0.73. 使用
java
@RestController
public class ChatController {
private final ChatModel chatModel;
public ChatController(ChatModel chatModel) {
this.chatModel = chatModel;
}
@PostMapping("/chat")
public String chat(@RequestBody String message) {
return chatModel.call(message);
}
}与 LangChain4j 对比
| 特性 | Spring AI | LangChain4j |
|---|---|---|
| 官方支持 | Spring 官方 | 社区驱动 |
| Spring 集成 | 原生集成 | 需要适配器 |
| 学习曲线 | 低(熟悉 Spring) | 中等 |
| 生态成熟度 | 较新 | 更成熟 |
| 企业级特性 | 完整 | 部分 |
适用场景
Spring AI 适合以下场景:
- Spring 项目集成 - 已经使用 Spring Boot 的应用
- 企业级应用 - 需要完整的依赖注入、配置管理
- 微服务架构 - Spring Cloud 集成
- 团队熟悉 Java - 团队对 Spring 生态熟悉
限制和注意事项
- ⚠️ 版本较新 - 仍在快速迭代中,API 可能有变化
- ⚠️ 功能覆盖 - 不如 LangChain 生态丰富
- ⚠️ 文档 - 相对较少,需要参考源码和示例
相关资源
更新时间: 2026-03-14 分类: Java AI 平台 | Spring AI