1. 什么是 Spring AI?
Spring AI 是 Spring 官方团队推出的开源项目,目标是为各种人工智能模型(如 OpenAI GPT、Hugging Face、本地LLM等)提供统一的 API 抽象层。其核心定位是:
- 开箱即用:通过 Spring Boot Starter 快速集成主流AI服务
- 标准化交互:统一不同模型的请求响应接口,降低学习成本
- 模块化设计:支持灵活扩展新模型(如 Llama3、Claude3)
- 开发者友好:沿用 Spring 熟悉的依赖注入和配置管理风格
当前(2024年7月)Spring AI 1.0 版本已正式发布,支持以下核心功能:
模块类型 | 功能示例 |
---|---|
大语言模型 |文本生成、多轮对话、信息抽取 | | |
多模态模型 |图像生成(如 Stable Diffusion)、视觉问答 | | |
向量数据库 |语义检索、RAG应用开发 | | |
工具链 |提示词管理、输出格式解析、流式响应 | |
2. 核心特性解析
2.1 统一的 API 抽象
无论对接 OpenAI、Azure AI 还是本地部署的 Llama3,Spring AI 通过 ChatClient
接口屏蔽底层差异:
<JAVA>
@Autowired
private ChatClient chatClient;
public String generatePoem(String topic) {
// 使用相同API调用不同模型
return chatClient.call(
Prompt.builder()
.text("为以下主题创作七言绝句:{}", topic)
.build()
).getResult();
}
2.2 声明式提示词模板
通过 PromptTemplate
实现动态内容生成和结构化输出:
<JAVA>
// 定义模板(支持 SpEL 表达式)
PromptTemplate template = new PromptTemplate("""
你是一位{role},请根据用户问题生成回答:
问题:{question}
回答语言:{lang}
""");
// 填充变量
Prompt prompt = template.create(Map.of(
"role", "技术专家",
"question", "如何设计高并发系统?",
"lang", "中文"
));
String answer = chatClient.call(prompt).getResult();
2.3 模型自由切换
只需修改配置文件,无需改动业务代码即可切换AI提供者:
<PROPERTIES>
# application-openai.properties
spring.ai.openai.api-key=sk-xxx
spring.ai.openai.model=gpt-4-turbo
# application-azure.properties
spring.ai.azure.endpoint=https://xxxx.openai.azure.com
spring.ai.azure.api-key=xxxxx
spring.ai.azure.deployment-name=my-gpt4
2.4 流式响应支持
处理长文本生成时降低响应延迟:
<JAVA>
Flux<String> streamResponse = chatClient.stream(
Prompt.builder().text("讲解Java Stream API").build()
);
streamResponse.subscribe(
chunk -> System.out.print(chunk), // 实时输出片段
error -> log.error("生成失败", error),
() -> System.out.println("\n生成完成")
);
3. 快速入门示例
3.1 项目初始化
通过 Spring Initializr 添加依赖:
<XML>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- OpenAI 集成(也可选azure-ai/ollama等) -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
3.2 基础配置
<YAML>
spring:
ai:
openai:
api-key: ${OPENAI_API_KEY}
model: gpt-4o
temperature: 0.7
# 可选高级参数
max-tokens: 1000
response-format: json_object
3.3 创建RESTful服务
<JAVA>
@RestController
@RequestMapping("/ai")
public class AIController {
@Autowired
private ChatClient chatClient;
@PostMapping("/ask")
public String answerQuestion(@RequestBody String question) {
return chatClient.call(
Prompt.builder().text(question).build()
).getResult();
}
}
4. 企业级应用场景
4.1 智能客服系统
<JAVA>
@Service
public class CustomerService {
@Retryable(maxAttempts=3, backoff=@Backoff(1000))
public String handleInquiry(String question) {
// 1. 意图识别
String intent = detectIntent(question);
// 2. 查询知识库
if (knowledgeBaseExists(intent)) {
return fetchFromKB(intent);
}
// 3. 动态生成回答
return chatClient.call(buildPrompt(intent, question));
}
}
4.2 智能文档处理
4.3 RAG 知识库增强
结合向量数据库(如 Redis、PgVector):
<JAVA>
ragTemplate.retrieve("查询")
.addDocuments(vectorStore.search(query))
.stream()
.map(chatClient::call)
.collect(Collectors.joining("\n\n"));
5. 进阶功能扩展
5.1 自定义模型接入
继承 ChatClient
实现本地模型支持:
<JAVA>
@Bean
public ChatClient myLocalModelClient() {
return new ChatClient() {
@Override
public String call(Prompt prompt) {
// 调用本地 HTTP 或 gRPC 接口
return myLLM.generate(prompt.getText());
}
};
}
5.2 输出内容安全审查
集成审查过滤器:
<JAVA>
@Bean
public OutputFilter profanityFilter() {
return response -> {
if (containsSensitiveWords(response)) {
throw new ContentBlockedException("包含违禁内容");
}
return response;
};
}
6. 性能优化技巧
- 批量处理:使用
BatchPrompt
合并多个请求 - 缓存机制:对高频问题开启结果缓存
- 连接池优化:调整 HTTP 客户端参数
<YAML>
spring:
ai:
openai:
client:
connect-timeout: 10s
max-in-memory-size: 10MB
结语
Spring AI 通过优雅的设计哲学,将复杂的AI模型交互转化为符合Spring开发者直觉的编程模式。无论是快速验证AI创意还是构建企业级智能系统,其模块化架构和标准化接口都能显著提升研发效率。随着Spring生态的持续发展,Spring AI 或将成为Java领域AI应用开发的事实标准。
下一步行动:
- 访问 Spring AI 官方文档
- 克隆示例仓库:
git clone https://github.com/spring-projects/spring-ai-samples