Spring AI集成Gemini 2.5的终极指南:5步实现智能对话

Spring AI集成Gemini 2.5的终极指南:5步实现智能对话

在人工智能技术快速迭代的今天,企业开发者需要高效整合前沿模型以构建智能应用。Spring AI作为Spring生态中专注于AI集成的框架,通过简化与大模型的交互流程,显著降低了技术门槛。本文将以Gemini 2.5这一高性能多模态模型为例,系统阐述如何通过5个关键步骤实现基于Spring AI的智能对话系统,覆盖环境配置、API调用、模型优化等核心环节。

一、技术选型与架构设计

1.1 为什么选择Spring AI + Gemini 2.5?

Spring AI的核心价值在于其统一抽象层,开发者可通过同一套API对接不同大模型(如Gemini、GPT、Llama等),避免重复编码。而Gemini 2.5作为谷歌推出的多模态模型,具备以下优势:

  • 多模态支持:可同时处理文本、图像、音频输入,扩展对话场景(如视觉问答)
  • 长上下文记忆:支持128K tokens的上下文窗口,适合复杂对话管理
  • 低延迟响应:通过流式输出实现毫秒级交互

1.2 系统架构设计

推荐采用分层架构:

  1. ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
  2. Client Spring AI Gemini 2.5
  3. (Web/Mobile)│ Service API
  4. └─────────────┘ └─────────────┘ └─────────────┘
  5. └───────────┬───────┘ ┌─────┴─────┐
  6. Data
  7. Storage
  8. └─────────────────────┘
  • Client层:通过REST/WebSocket发起请求
  • Service层:Spring AI处理模型路由、参数转换、响应解析
  • Model层:Gemini 2.5生成回答,数据持久化存储

二、5步集成实现

步骤1:环境准备与依赖管理

1.1 创建Spring Boot项目

使用Spring Initializr(https://start.spring.io/)生成项目,添加以下依赖:

  1. <dependencies>
  2. <!-- Spring AI核心 -->
  3. <dependency>
  4. <groupId>org.springframework.ai</groupId>
  5. <artifactId>spring-ai-starter</artifactId>
  6. <version>0.7.0</version>
  7. </dependency>
  8. <!-- Gemini 2.5专用适配器(需自定义或使用社区实现) -->
  9. <dependency>
  10. <groupId>com.example</groupId>
  11. <artifactId>spring-ai-gemini-adapter</artifactId>
  12. <version>1.0.0</version>
  13. </dependency>
  14. </dependencies>

1.2 配置Gemini API密钥

application.yml中配置:

  1. spring:
  2. ai:
  3. chat:
  4. providers:
  5. - name: gemini
  6. endpoint: https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent
  7. api-key: YOUR_GEMINI_API_KEY
  8. max-tokens: 2048
  9. temperature: 0.7

步骤2:实现Gemini 2.5适配器

2.1 自定义ChatClient实现

  1. @Component
  2. public class GeminiChatClient implements ChatClient {
  3. private final RestTemplate restTemplate;
  4. private final String apiKey;
  5. private final String endpoint;
  6. public GeminiChatClient(
  7. @Value("${spring.ai.chat.providers[0].endpoint}") String endpoint,
  8. @Value("${spring.ai.chat.providers[0].api-key}") String apiKey) {
  9. this.endpoint = endpoint;
  10. this.apiKey = apiKey;
  11. this.restTemplate = new RestTemplate();
  12. }
  13. @Override
  14. public ChatResponse generate(ChatRequest request) {
  15. HttpHeaders headers = new HttpHeaders();
  16. headers.setContentType(MediaType.APPLICATION_JSON);
  17. headers.setBearerAuth(apiKey);
  18. Map<String, Object> body = Map.of(
  19. "contents", List.of(Map.of("parts", List.of(Map.of("text", request.getPrompt()))))
  20. );
  21. HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
  22. ResponseEntity<Map> response = restTemplate.postForEntity(
  23. endpoint, entity, Map.class);
  24. String reply = (String) ((Map) ((List) ((Map) response.getBody()
  25. .get("candidates")).get(0)).get("content")).get("parts").get(0).get("text");
  26. return ChatResponse.builder().reply(reply).build();
  27. }
  28. }

2.2 注册为Spring Bean

  1. @Configuration
  2. public class GeminiConfig {
  3. @Bean
  4. public ChatClient geminiChatClient(
  5. @Value("${spring.ai.chat.providers[0].endpoint}") String endpoint,
  6. @Value("${spring.ai.chat.providers[0].api-key}") String apiKey) {
  7. return new GeminiChatClient(endpoint, apiKey);
  8. }
  9. }

步骤3:构建对话服务层

3.1 定义对话服务接口

  1. public interface DialogService {
  2. String processMessage(String userId, String message);
  3. }

3.2 实现带上下文管理的服务

  1. @Service
  2. public class GeminiDialogService implements DialogService {
  3. private final ChatClient chatClient;
  4. private final Map<String, List<String>> conversationHistory = new ConcurrentHashMap<>();
  5. public GeminiDialogService(ChatClient chatClient) {
  6. this.chatClient = chatClient;
  7. }
  8. @Override
  9. public String processMessage(String userId, String message) {
  10. // 构建带上下文的prompt
  11. String history = conversationHistory.computeIfAbsent(userId, k -> new ArrayList<>())
  12. .stream()
  13. .collect(Collectors.joining("\n"));
  14. String fullPrompt = String.format("""
  15. 用户历史对话:
  16. %s
  17. 当前问题:%s
  18. 请以简洁中文回答:
  19. """, history, message);
  20. ChatRequest request = ChatRequest.builder()
  21. .prompt(fullPrompt)
  22. .build();
  23. ChatResponse response = chatClient.generate(request);
  24. // 更新对话历史(限制长度)
  25. conversationHistory.computeIfPresent(userId, (k, v) -> {
  26. if (v.size() > 10) v.subList(0, 5).clear();
  27. v.add("用户:" + message);
  28. v.add("AI:" + response.getReply());
  29. return v;
  30. });
  31. return response.getReply();
  32. }
  33. }

步骤4:创建REST控制器

  1. @RestController
  2. @RequestMapping("/api/chat")
  3. public class ChatController {
  4. private final DialogService dialogService;
  5. public ChatController(DialogService dialogService) {
  6. this.dialogService = dialogService;
  7. }
  8. @PostMapping
  9. public ResponseEntity<Map<String, String>> chat(
  10. @RequestParam String userId,
  11. @RequestBody Map<String, String> request) {
  12. String reply = dialogService.processMessage(userId, request.get("message"));
  13. return ResponseEntity.ok(Map.of("reply", reply));
  14. }
  15. }

步骤5:测试与优化

5.1 单元测试示例

  1. @SpringBootTest
  2. public class DialogServiceTest {
  3. @Autowired
  4. private DialogService dialogService;
  5. @Test
  6. public void testContextualDialog() {
  7. String userId = "test-user";
  8. String firstReply = dialogService.processMessage(userId, "你好");
  9. assertTrue(firstReply.contains("你好"));
  10. String secondReply = dialogService.processMessage(userId, "今天天气如何?");
  11. assertTrue(secondReply.contains("天气"));
  12. }
  13. }

5.2 性能优化建议

  • 异步处理:使用@Async注解实现非阻塞调用
    1. @Async
    2. public CompletableFuture<String> processMessageAsync(String userId, String message) {
    3. return CompletableFuture.completedFuture(processMessage(userId, message));
    4. }
  • 缓存机制:对高频问题使用Redis缓存回答
  • 流式响应:改造为WebSocket实现逐字输出

三、高级功能扩展

3.1 多模态对话实现

通过扩展ChatRequest支持图像输入:

  1. public class MultimodalChatRequest {
  2. private String text;
  3. private byte[] image; // Base64编码
  4. // getters/setters
  5. }
  6. // 在适配器中处理多模态请求
  7. public ChatResponse generate(MultimodalChatRequest request) {
  8. // 调用Gemini的图像理解API
  9. // ...
  10. }

3.2 安全增强措施

  • 实现请求签名验证
  • 添加内容过滤层(如敏感词检测)

    1. @Component
    2. public class ContentFilter {
    3. private final Set<String> blockedWords = Set.of("暴力", "色情");
    4. public boolean containsBlockedContent(String text) {
    5. return blockedWords.stream()
    6. .anyMatch(text::contains);
    7. }
    8. }

四、部署与监控

4.1 Docker化部署

  1. FROM eclipse-temurin:17-jdk-jammy
  2. COPY target/spring-ai-gemini-0.0.1.jar app.jar
  3. EXPOSE 8080
  4. ENTRYPOINT ["java", "-jar", "app.jar"]

4.2 Prometheus监控指标

添加依赖:

  1. <dependency>
  2. <groupId>io.micrometer</groupId>
  3. <artifactId>micrometer-registry-prometheus</artifactId>
  4. </dependency>

配置监控端点:

  1. management:
  2. endpoints:
  3. web:
  4. exposure:
  5. include: prometheus,health
  6. metrics:
  7. export:
  8. prometheus:
  9. enabled: true

五、最佳实践总结

  1. 模型选择策略:根据场景选择Gemini 2.5的变体(Pro/Flash)
  2. 错误处理:实现重试机制和降级策略
  3. 成本优化:设置合理的max-tokenstemperature参数
  4. 可观测性:记录每次调用的prompt/response用于分析

通过以上5个步骤,开发者可快速构建基于Spring AI和Gemini 2.5的智能对话系统。实际项目中,建议从简单文本对话开始,逐步扩展多模态能力,同时建立完善的监控体系确保服务质量。