Spring AI 使用教程

发布于:2025-05-25 ⋅ 阅读:(22) ⋅ 点赞:(0)

Spring AI 使用教程(2025年5月24日更新)


一、环境搭建与项目初始化
  1. 创建Spring Boot项目

    • 使用IDEA或Spring Initializr创建项目,选择JDK 17或更高版本(推荐21)。
    • 勾选依赖项:Spring WebLombok,Maven或Gradle作为构建工具。
    • 添加Spring AI依赖(以OpenAI为例):
      <dependency>
          <groupId>org.springframework.ai</groupId>
          <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
          <version>1.0.0-M6</version>
      </dependency>
      
  2. 配置API密钥
    application.yml中配置模型服务(以DeepSeek为例):

    spring:
      ai:
        openai:
          api-key: sk-your-api-key
          base-url: https://api.deepseek.com/v1
          chat:
            options:
              model: deepseek-chat
    ```<sup>5</sup><sup>8</sup><sup>11</sup>
    
    

二、基础功能实现
  1. 调用大模型生成文本

    • 通过ChatClient发送请求:
      @RestController
      public class ChatController {
          @Autowired
          private ChatClient chatClient;
          
          @GetMapping("/chat")
          public String chat(@RequestParam String prompt) {
              return chatClient.prompt(prompt).call().content();
          }
      }
      
    • 启动应用后,访问http://localhost:8080/chat?prompt=写一首春天的诗即可获取响应。
  2. 文档处理(ETL)

    • 添加文档处理依赖(如PDF解析):
      <dependency>
          <groupId>org.springframework.ai</groupId>
          <artifactId>spring-ai-tika-document-reader</artifactId>
      </dependency>
      
    • 读取并转换本地文档:
      DocumentReader reader = new TikaDocumentReader();
      List<Document> docs = reader.read("file:///data.pdf");
      

三、高级应用场景
  1. RAG(检索增强生成)

    • 结合本地数据与大模型,实现知识库增强问答:
      • 使用spring-ai-spark集成讯飞星火:
        <dependency>
            <groupId>com.iflytek.spark</groupId>
            <artifactId>spring-ai-spark-spring-boot-starter</artifactId>
            <version>1.0.0-M6-SNAPSHOT</version>
        </dependency>
        
      • 将本地数据向量化存储,通过语义检索生成精准答案。
  2. MCP服务集成

    • 搭建MCP(Model Context Protocol)服务:
      <dependency>
          <groupId>org.springframework.ai</groupId>
          <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
      </dependency>
      
    • 通过JSON-RPC与模型交互,支持多模态输入输出。

四、实战案例:构建网页聊天应用
  1. 前端集成

    • 使用Thymeleaf或React/Vue搭建前端页面,通过WebSocket或SSE与后端通信。
    • 示例代码片段(SSE推送):
      @GetMapping("/stream-chat")
      public SseEmitter streamChat(@RequestParam String prompt) {
          SseEmitter emitter = new SseEmitter();
          chatClient.prompt(prompt).stream().subscribe(content -> {
              emitter.send(content);
          });
          return emitter;
      }
      
  2. 记忆存储与会话管理

    • 使用ChatMemory组件保存上下文:
      @Bean
      public ChatMemory chatMemory() {
          return new InMemoryChatMemory(50); // 保留最近50轮对话
      }
      

五、注意事项与调试技巧
  1. 常见问题

    • 模型响应慢:调整超时配置spring.ai.openai.chat.options.timeout=60s
    • 中文支持不佳:在prompt中明确指定“用中文回答”。
  2. 日志调试

    • 启用详细日志:
      logging:
        level:
          org.springframework.ai: DEBUG
      

六、总结与扩展

Spring AI通过模块化设计,支持快速接入主流模型(如DeepSeek、讯飞星火)和高级功能(RAG、MCP)。开发者可结合业务需求扩展以下场景:

  • 多模型混合调用:通过@Qualifier注解切换不同模型。
  • 工具调用:集成外部API(如天气查询)增强AI能力。
  • 企业级部署:结合Kubernetes实现弹性扩缩容。

网站公告

今日签到

点亮在社区的每一天
去签到