一: Spring AI 是什么?
1.1:简介
Spring AI 是 Spring 团队推出的 AI 应用开发框架,它把大模型能力封装成 Spring Boot 风
格,让我们像使用 RestTemplate
、JdbcTemplate
一样调用 LLM(大语言模型)
简单理解:
👉 Spring AI = Spring Boot + AI SDK + Prompt/RAG 封装
1.2:定位
大模型调用框架:支持 OpenAI、Ollama、Azure OpenAI、HuggingFace 等
Spring Boot 风格:配置驱动,提供 ChatClient
、PromptTemplate
等常用 API
应用层封装:支持 Prompt 模板、向量数据库(RAG)、结构化输出
1.3:对比 Python 的生态
Python 有 LangChain
Java 生态就有 Spring AI 和 LangChain4j
二:环境准备
2.1:依赖配置
springAi依赖
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>1.0.0-M2</version>
</dependency>
如果你想用本地模型(Ollama):
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
<version>1.0.0-M2</version>
</dependency>
2.2:配置文件
在 application.yml
里配置 API Key 或模型:
spring:
ai:
openai:
api-key: sk-xxxx # 你的 OpenAI Key
base-url: https://api.openai.com/v1
本地运行 Ollama:
spring:
ai:
ollama:
base-url: http://localhost:11434
model: llama3
三:快速上手:第一个 AI 接口
Spring AI 提供了 ChatClient
,我们只需要注入即可使用
@RestController
@RequiredArgsConstructor
public class ChatController {
private final ChatClient chatClient;
@GetMapping("/chat")
public String chat(@RequestParam String msg) {
return chatClient
.prompt()
.user(msg)
.call()
.content();
}
}
启动项目后访问:
http://localhost:8080/chat?msg=你好
就能得到模型的回复
四:Spring AI 核心功能
4.1:Prompt 模板
支持占位符和变量替换:
@GetMapping("/summary")
public String summarize(@RequestParam String text) {
String template = "请用一句话总结以下文本: {input}";
return chatClient.prompt()
.user(template, Map.of("input", text))
.call()
.content();
}
4.2:结构化输出
让大模型输出 JSON,Spring AI 会帮你转成 Java 对象:
@Data
public class WeatherInfo {
private String location;
private String forecast;
private int temperature;
}
@GetMapping("/weather")
public WeatherInfo getWeather(@RequestParam String place) {
return chatClient.prompt()
.user("请提供 {place} 的天气情况", Map.of("place", place))
.call()
.entity(WeatherInfo.class);
}
4.3 向量数据库 + RAG
Spring AI 内置了 VectorStore,可接入 Milvus、PgVector、Redis 等
@Autowired
private VectorStore vectorStore;
@PostConstruct
public void init() {
vectorStore.add(List.of(
new Document("Spring 是一个流行的 Java 框架"),
new Document("Spring AI 支持 OpenAI、Ollama 等模型")
));
}
@GetMapping("/ask")
public String ask(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.options(ChatOptions.builder()
.withDocuments(vectorStore.similaritySearch(question))
.build())
.call()
.content();
}
这样就实现了 基于知识库的问答
五:资料
官方文档:Spring AI
GitCode 示例:右击代码仓