Spring AI 应用集成框架
基于 Spring Boot 的大模型应用集成框架,作为后 Java 时代的关键一环,旨在简化大模型在应用中的集成与开发,撼动了 Python 语言在 AI 工程领域的主导地位。
核心特性
- 统一的 API 调用接口,支持多种大模型
- 基于 Spring Boot 自动配置,简化配置
- 提供
PromptTemplate
和结构化提示管理
- 支持流式响应处理
SpringAI 利用 AOP 原理提供 AI 会话流程的拦截和增强,实现 AroundAdvisors ,基于此可以方便管理对话日志,及上下文记忆。
快速开始
基于 SpringBoot 快速上手体验 SpringAI 的便利功能。
环境准备
- Java 17+
- Spring Boot 3.0+
- 大模型 api-key
引入依赖
可以通过新建 Spring Boot 脚手架,自动引入 SpringAI 依赖:
也可以手动引入依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> </repositories> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-openai</artifactId> ---选择你要用的大模型 </dependency>
|
配置 Application.yml
1 2 3 4 5 6 7 8 9
| spring: application: name: SpringAI ai: openai: base-url: https://api.openai-hub.com --- 实际调用地址 api-key: ${OPENAI_API_KEY} --- 填入你的 api-key chat: --- 以 chat 模式为例 model: gpt-4.1
|
创建客户端
配置类
1 2 3 4 5 6 7 8 9
| @Configuration public class CommonConfiguration { @Bean public ChatClient chatClient(OpenAiChatModel chatModel) { return ChatClient.builder(chatModel) .defaultSystem("You are a helpful assistant.") .build(); } }
|
表现层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @RequiredArgsConstructor @RestController @RequestMapping("/chat") public class ChatController {
private final ChatClient chatClient; @RequestMapping(produces = "text/html;charset=UTF-8") public String chat(String prompt) { return chatClient.prompt() .user(prompt) .stream() .content(); } }
|
值得一提的是,流式输出格式默认为为text/event-stream
格式,我们可以修改 RequestMapping 的 produces 来指定输出格式。
启动项目测试
启动项目,访问 http://localhost:8080/chat?prompt=hello
可以看到大模型返回的内容。
