【AI】Spring AI 整合谷歌 Gemini 大模型:从零构建智能对话系统的实战指南
1. 为什么选择Spring AI整合Gemini大模型最近两年大模型技术爆发式发展谷歌推出的Gemini系列模型凭借其强大的多模态能力和性价比优势已经成为开发者构建智能应用的热门选择。而Spring AI作为Spring生态中专门为AI集成设计的框架能够让我们Java开发者以最熟悉的方式快速接入这些前沿技术。我在实际项目中使用Spring AI整合Gemini时发现这套组合有三大突出优势首先是开发效率高Spring Boot的自动配置特性让我们只需几行代码就能完成对接其次是扩展性强基于Spring的依赖注入机制可以轻松实现功能模块化最后是性能稳定Spring的WebClient为流式响应提供了可靠支持。2. 开发环境准备2.1 基础环境配置在开始之前我们需要准备以下开发环境JDK 17或更高版本推荐使用Amazon Corretto或OpenJDKMaven 3.6或Gradle 7.xIntelliJ IDEA或VS Code等现代IDESpring Boot 3.2.x建议使用SDKMAN来管理Java版本sdk install java 17.0.10-amzn sdk install maven 3.9.62.2 创建Spring Boot项目通过Spring Initializr快速创建项目访问start.spring.io选择Project: MavenLanguage: JavaSpring Boot: 3.2.5添加依赖Spring WebSpring AI (需要手动添加)或者使用命令行curl https://start.spring.io/starter.tgz \ -d typemaven-project \ -d languagejava \ -d bootVersion3.2.5 \ -d baseDirgemini-demo \ -d groupIdcom.example \ -d artifactIdgemini-demo \ -d namegemini-demo \ -d dependenciesweb \ -d javaVersion17 \ | tar -xzvf -3. Gemini API配置详解3.1 获取API密钥访问Google AI Studio (https://aistudio.google.com)使用Google账号登录在API密钥管理页面创建新密钥复制生成的密钥格式如AIzaSyD...注意密钥需要妥善保管建议通过环境变量配置而非直接写在代码中3.2 计费与配额设置Gemini Pro模型当前提供以下免费额度每分钟60次请求每分钟32,000 tokens每天1,000次请求超出免费额度后的计费标准输入$0.00025/1K tokens输出$0.0005/1K tokens建议在Google Cloud控制台设置用量提醒避免意外超额。4. Spring AI集成实战4.1 添加必要依赖在pom.xml中添加Spring AI Gemini starterdependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-gemini-spring-boot-starter/artifactId version0.8.1/version /dependency同时确保Spring Boot父POM版本匹配parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version3.2.5/version /parent4.2 基础配置在application.yml中配置spring: ai: gemini: api-key: ${GEMINI_API_KEY} model: gemini-pro chat: options: temperature: 0.7 top-p: 0.9更安全的做法是通过环境变量注入密钥export GEMINI_API_KEYyour_api_key_here5. 实现智能对话功能5.1 基础对话实现创建ChatControllerRestController RequestMapping(/api/chat) public class ChatController { private final ChatClient chatClient; public ChatController(ChatClient chatClient) { this.chatClient chatClient; } PostMapping public String generate(RequestBody String prompt) { return chatClient.call(prompt); } }测试请求curl -X POST http://localhost:8080/api/chat \ -H Content-Type: application/json \ -d 用通俗语言解释量子计算5.2 高级对话管理实现多轮对话GetMapping(/stream) public FluxString streamChat(RequestParam String question) { Prompt prompt new Prompt(new UserMessage(question)); return chatClient.stream(prompt) .map(response - response.getResult().getOutput().getContent()); }前端可以通过SSE连接const eventSource new EventSource(/api/chat/stream?question如何学习Spring); eventSource.onmessage (e) { console.log(e.data); };6. 生产环境优化建议6.1 性能调优连接池配置spring: ai: gemini: client: connect-timeout: 10s read-timeout: 30s max-in-memory-size: 10MB启用响应缓存Bean Cacheable(geminiResponses) public ChatClient cachedChatClient(ChatClient chatClient) { return chatClient; }6.2 异常处理全局异常处理器ControllerAdvice public class AiExceptionHandler { ExceptionHandler(AiClientException.class) public ResponseEntityString handleAiException(AiClientException ex) { return ResponseEntity.status(502) .body(AI服务暂时不可用: ex.getMessage()); } }7. 实际应用案例7.1 知识问答系统实现带来源验证的问答public String answerWithCitation(String question) { var options GeminiChatOptions.builder() .withGrounding(true) .build(); Prompt prompt new Prompt(question, options); ChatResponse response chatClient.call(prompt); return response.getResult().getOutput().getContent() \n\n来源: response.getMetadata().get(groundingSources); }7.2 多模态处理处理图片输入public String analyzeImage(byte[] imageBytes, String question) { var media new Media(MimeTypeUtils.IMAGE_PNG, imageBytes); var userMessage new UserMessage(question, List.of(media)); return chatClient.call(new Prompt(userMessage)) .getResult() .getOutput() .getContent(); }8. 调试与监控8.1 日志配置在logback-spring.xml中添加logger nameorg.springframework.ai levelDEBUG/8.2 指标监控集成Micrometer监控Bean public MeterRegistryCustomizerMeterRegistry aiMetrics() { return registry - { registry.config().meterFilter( new MeterFilter() { Override public DistributionStatisticConfig configure( Meter.Id id, DistributionStatisticConfig config) { if (id.getName().startsWith(spring.ai)) { return DistributionStatisticConfig.builder() .percentiles(0.5, 0.95) .build() .merge(config); } return config; } }); }; }9. 安全最佳实践9.1 输入验证Validated public class ChatRequest { NotBlank Size(max 1000) private String message; // getters/setters }9.2 内容过滤配置安全策略Bean public ChatOptions safetyOptions() { return GeminiChatOptions.builder() .withSafetySettings( SafetySetting.HARM_CATEGORY_HATE_SPEECH, SafetySetting.BlockThreshold.MEDIUM) .build(); }10. 进阶功能探索10.1 函数调用定义工具函数Bean public FunctionCallback weatherFunction() { return new FunctionCallback(getCurrentWeather, Get the current weather in a given location , args - { String location args.get(location); // 调用天气API return Sunny, 25°C; }); }10.2 自定义模型适配实现ChatModel接口public class CustomGeminiAdapter implements ChatModel { private final GeminiService service; Override public ChatResponse call(Prompt prompt) { // 自定义转换逻辑 GeminiRequest request convertPrompt(prompt); GeminiResponse response service.generate(request); return convertResponse(response); } }在实际项目中我发现合理设置temperature参数对生成质量影响很大。对于事实性问答建议0.3-0.5创意生成可以0.7-1.0。同时要注意及时更新Spring AI版本新版本通常会修复已知问题并提升性能。