Home
img of docs

springboot 集成ai

chou403

/ Default

/ c:

/ u:

/ 4 min read


一学一个不吱声

Spring AI 是 Spring 生态系统推出的 面向 AI 工程的应用框架,旨在为 Java 开发者提供便捷的 AI 集成方案。它通过标准化接口、模块化设计和深度 Spring 生态集成,简化了生成式 AI(如大语言模型)在 Java 项目中的开发流程。

一、Spring AI 的核心特性

  1. 跨模型兼容性 统一接入 OpenAI、Azure AI、Hugging Face、通义千问、Ollama 等主流模型,无需修改业务代码即可切换服务提供商。
  2. 关键功能支持
    • 提示工程:动态模板(PromptTemplate)支持变量注入,优化模型输入。
    • 多模态交互:支持文本生成、图像生成(如 DALL-E)、语音转文本(如 Whisper)。
    • 检索增强(RAG):内置轻量级 ETL 框架,集成 Redis、PostgreSQL 等向量数据库。
    • 函数调用:通过 FunctionCallback 实现模型与外部 API 的交互(如查询天气、数据库)。
  3. Spring 生态集成 无缝兼容 Spring Boot 自动配置、依赖注入,支持同步/流式响应(如 Flux 流式输出)。

二、Spring Boot 项目迁移至 Spring AI 的步骤

第一步:环境准备

  • 强制要求
    • JDK 17+
    • Spring Boot 3.3+(推荐 3.4.5+)。
  • 依赖管理: 在 pom.xml 中添加 Spring AI BOM 和模型 Starter(以 OpenAI 为例):
       <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>1.0.0</version> <!-- 生产稳定版 -->
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
    若需本地模型(如 Ollama),改用 spring-ai-ollama-spring-boot-starter

第二步:配置认证信息

application.yml 中配置模型参数:

   spring:
  ai:
    openai:
      api-key: YOUR_API_KEY
      base-url: https://api.openai.com # 代理地址(可选)
    ollama: # 本地模型示例
      base-url: http://localhost:11434
      chat:
        model: llama3

第三步:代码集成

  1. 基础对话功能 注入 ChatClient 实现问答:

       @RestController
    public class ChatController {
        private final ChatClient chatClient;
    
        @Autowired
        public ChatController(ChatClient.Builder builder) {
            this.chatClient = builder.build();
        }
    
        @GetMapping("/chat")
        public String chat(@RequestParam String input) {
            return chatClient.call(input); // 同步调用
        }
    
        @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<String> streamChat(String input) {
            return chatClient.stream().content(); // 流式响应
        }
    }
    
  2. 高级功能示例

    • Prompt 动态模板

         PromptTemplate template = new PromptTemplate("总结{title}的核心内容");
      Prompt prompt = template.create(Map.of("title", "Spring AI 文档"));
      String result = chatClient.call(prompt).getResult().getOutput();
      
    • 语音转文本

         @Resource
      private OpenAiAudioTranscriptionModel transcriptionModel;
      
      @PostMapping("/transcribe")
      public String transcribe(@RequestParam Resource audioFile) {
          return transcriptionModel.call(audioFile);
      }
      

三、迁移注意事项

问题类型解决方案
JDK 版本不兼容升级至 JDK 17+,修改 POM 和 CI/CD 环境。
老旧 Spring 依赖升级 Spring Boot 至 3.3+,检查第三方库兼容性。
模型切换成本利用 ChatModel 抽象层,通过配置切换模型(如 OpenAI → Ollama)。
安全与合规避免传输敏感数据,通过函数调用隔离隐私操作。

四、典型应用场景

  • 智能客服:结合 RAG 从企业知识库生成精准回答。
  • 文档分析:自动解析合同/保单,提取风险点(使用 OutputParser 转 POJO)。
  • 多模态交互:文生图(ImageModel)+ 语音交互(AudioTranscriptionModel)。

迁移本质是增量集成:无需重写现有 Spring Boot 项目,仅需在需 AI 能力的模块引入 Spring AI 组件。例如,传统 CRUD 项目添加 ChatController 即可升级为智能问答系统。