【Spring AI】-Spring AI 概述与环境搭建
Spring AI 概述与环境搭建
引言
在人工智能技术飞速发展的今天,将AI能力集成到企业应用中已成为提升产品竞争力的关键手段。Spring AI作为Spring生态系统中的一员新将,为Java开发者提供了一套标准、易用的API,让复杂的AI能力集成变得简单而优雅。
无论您是希望快速构建AI聊天机器人的初学者,还是寻求在现有企业应用中集成AI功能的资深开发者,Spring AI都能为您提供强大的支持。它屏蔽了不同AI模型间的差异,让您专注于业务逻辑的实现,而非底层技术的复杂细节。
本文将引导您从零开始搭建Spring AI开发环境,并构建您的第一个AI应用,为后续深入学习打下坚实基础。
什么是 Spring AI
Spring AI 是 Spring 生态系统中的一个新兴项目,旨在简化 AI 应用程序的开发。它提供了一套标准的 API 和抽象,使得开发者能够以统一的方式与各种大语言模型(LLM)进行交互,而无需关心底层实现细节。
核心概念
- Prompt(提示词) - 向 AI 模型发送的输入文本,是与AI沟通的语言
- Model(模型) - 大语言模型,如 OpenAI、通义千问等,负责处理Prompt并生成响应
- OutputParser(输出解析器) - 将 AI 模型的输出解析为结构化数据,便于程序处理
环境准备
系统要求
- JDK 17 或更高版本
- Maven 3.8+ 或 Gradle 7+
- 支持的 AI 模型 API 访问权限(如OpenAI API Key)
Maven依赖配置
使用Spring Boot 3.x项目,添加以下依赖:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring AI OpenAI Starter --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId></dependency>
</dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>1.0.0-M2</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><releases><enabled>false</enabled></releases></repository>
</repositories>
使用最新版本,这里添加了Spring的仓库,如果你配置了其他仓库,请修改
mirrorOf
配置以排除 Spring 仓库:<mirror><id>my-mirror</id><mirrorOf>*,!spring-snapshots,!central-portal-snapshots</mirrorOf><url>https://my-company-repository.com/maven</url> </mirror>
第一个 Spring AI 应用
配置文件设置
在 application.yml
中添加模型配置:这里使用的质谱AI
spring:ai:openai:api-key: ${YOU_API_KEY}base-url: https://open.bigmodel.cn/api/paaschat:options:model: glm-4.5completions-path: /v4/chat/completions
核心代码实现
创建一个简单的 ChatController:
@RestController
@RequestMapping("/chat")
public class ChatController {private final ChatClient chatClient;public ChatController(ChatClient.Builder chatClientBuilder) {this.chatClient = chatClientBuilder.build();}@GetMappingpublic String chat(@RequestParam String message) {return chatClient.prompt().user(message).call().content();}@PostMapping("/structured")public Map<String, Object> structuredChat(@RequestBody Map<String, String> request) {String message = request.get("message");String response = chatClient.prompt().system("你是一个专业的技术助手,请用简洁明了的语言回答问题").user(message).call().content();Map<String, Object> result = new HashMap<>();result.put("input", message);result.put("response", response);result.put("timestamp", System.currentTimeMillis());return result;}
}
运行测试
启动应用后,通过以下方式测试:
- 简单对话测试:
curl 'http://localhost:8080/chat?message=你好,Spring AI!'## 对中文字符进行 URL 编码
curl 'http://localhost:8080/chat?message=%E4%BD%A0%E5%A5%BD%EF%BC%8CSpring%20AI%EF%BC%81'
- 结构化响应测试:
curl -X POST http://localhost:8080/chat/structured \-H "Content-Type: application/json" \-d '{"message": "Spring AI有什么优势?"}'
实际应用案例
智能客服场景
在实际项目中,我们可以构建一个智能客服系统:
@Service
public class CustomerSupportService {private final ChatClient chatClient;public CustomerSupportService(ChatClient.Builder builder) {this.chatClient = builder.defaultSystem("你是一个电商平台的客服助手,需要礼貌、专业地回答用户问题").build();}public String handleInquiry(String customerQuestion) {return chatClient.prompt().user(u -> u.text("客户咨询:{question}").param("question", customerQuestion)).call().content();}
}@PostMapping("/customer-support")
public Map<String, Object> customerSupport(@RequestBody Map<String, String> request) {String question = request.get("question");String response = customerSupportService.handleInquiry(question);Map<String, Object> result = new HashMap<>();result.put("input", question);result.put("response", response);result.put("timestamp", System.currentTimeMillis());return result;
}curl -X POST http://localhost:8080/chat/customer-support \-H "Content-Type: application/json" \-d '{"question": "我要差评"}'
内容生成场景
用于自动生成产品描述:
@Service
public class ContentGenerationService {private final ChatClient chatClient;public ContentGenerationService(ChatClient.Builder builder) {this.chatClient = builder.defaultSystem("你是一个电商产品描述专家,擅长撰写吸引人的产品介绍").build();}public String generateProductDescription(ProductInfo productInfo) {return chatClient.prompt().user(u -> u.text("请为以下产品生成一段吸引人的描述:\n产品名称:{name}\n产品特点:{features}\n目标用户:{target}").param("name", productInfo.getName()).param("features", String.join(",", productInfo.getFeatures())).param("target", productInfo.getTarget())).call().content();}}@PostMapping("/product-description")
public Map<String, Object> generateProductDescription(@RequestBody ProductInfo productInfo) {String response = contentGenerationService.generateProductDescription(productInfo);Map<String, Object> result = new HashMap<>();result.put("input", productInfo);result.put("response", response);result.put("timestamp", System.currentTimeMillis());return result;
}curl -X POST http://localhost:8080/chat/product-description \-H "Content-Type: application/json" \-d '{"name": "逸安One","features": "采用6.3英寸1.5K柔性直屏,峰值亮度3500nits,搭载逸安龙晶玻璃面板和高强度一体航空铝金属中框。搭载第五代骁龙8至尊版处理器,配备立体环形冷泵散热系统。内置7000mAh硅碳电池,支持100W有线快充和50W无线快充 。影像系统包含5000万像素徕卡三摄,配备四重光学镀膜技术。","target": "青年白领,学生,科技"}'
总结
通过本篇文章,我们了解了 Spring AI 的基本概念,完成了环境搭建,并实现了一个简单的对话应用。这是学习 Spring AI 的第一步,后续我们将深入学习更多高级功能。
Spring AI的价值不仅在于简化了AI集成的复杂性,更在于它将AI能力与Spring生态无缝融合,让Java开发者能够以熟悉的方式构建AI应用。随着AI技术的不断发展,掌握Spring AI将成为Java开发者的重要技能。
后续学习建议
- 探索不同AI模型的接入方式(如通义千问、Anthropic Claude等)
- 学习Prompt工程技巧,提升AI交互质量
- 了解向量数据库集成,实现RAG(检索增强生成)应用
- 掌握输出解析器的使用,处理结构化响应
- 学习如何构建企业级AI应用,包括监控、日志和性能优化
参考资源
- Spring AI官方文档
- Spring AI GitHub仓库
- Spring AI系列文章中的后续章节
互动问题:
您在搭建Spring AI环境时遇到了哪些问题?欢迎在评论区分享您的经验和解决方案!您希望在后续文章中了解Spring AI的哪个特定功能?