Spring AI 使用教程

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


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

    • 使用IDEA或Spring Initializr创建项目,选择JDK 17或更高版本(推荐21)。

    • 勾选依赖项:Spring WebLombok,Maven或Gradle作为构建工具。

    • 添加Spring AI依赖(以OpenAI为例):

      xml 复制代码
      <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为例):

    yaml 复制代码
    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发送请求:

      java 复制代码
      @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解析):

      xml 复制代码
      <dependency>
          <groupId>org.springframework.ai</groupId>
          <artifactId>spring-ai-tika-document-reader</artifactId>
      </dependency>
    • 读取并转换本地文档:

      java 复制代码
      DocumentReader reader = new TikaDocumentReader();
      List<Document> docs = reader.read("file:///data.pdf");

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

    • 结合本地数据与大模型,实现知识库增强问答:
      • 使用spring-ai-spark集成讯飞星火:

        xml 复制代码
        <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)服务:

      xml 复制代码
      <dependency>
          <groupId>org.springframework.ai</groupId>
          <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
      </dependency>
    • 通过JSON-RPC与模型交互,支持多模态输入输出。


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

    • 使用Thymeleaf或React/Vue搭建前端页面,通过WebSocket或SSE与后端通信。

    • 示例代码片段(SSE推送):

      java 复制代码
      @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组件保存上下文:

      java 复制代码
      @Bean
      public ChatMemory chatMemory() {
          return new InMemoryChatMemory(50); // 保留最近50轮对话
      }

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

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

    • 启用详细日志:

      yaml 复制代码
      logging:
        level:
          org.springframework.ai: DEBUG

六、总结与扩展

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

  • 多模型混合调用 :通过@Qualifier注解切换不同模型。
  • 工具调用:集成外部API(如天气查询)增强AI能力。
  • 企业级部署:结合Kubernetes实现弹性扩缩容。
相关推荐
人工智能训练1 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
源于花海1 小时前
迁移学习相关的期刊和会议
人工智能·机器学习·迁移学习·期刊会议
DisonTangor3 小时前
DeepSeek-OCR 2: 视觉因果流
人工智能·开源·aigc·ocr·deepseek
薛定谔的猫19823 小时前
二十一、基于 Hugging Face Transformers 实现中文情感分析情感分析
人工智能·自然语言处理·大模型 训练 调优
发哥来了3 小时前
《AI视频生成技术原理剖析及金管道·图生视频的应用实践》
人工智能
数智联AI团队3 小时前
AI搜索引领开源大模型新浪潮,技术创新重塑信息检索未来格局
人工智能·开源
不懒不懒4 小时前
【线性 VS 逻辑回归:一篇讲透两种核心回归模型】
人工智能·机器学习
冰西瓜6004 小时前
从项目入手机器学习——(四)特征工程(简单特征探索)
人工智能·机器学习
Ryan老房4 小时前
未来已来-AI标注工具的下一个10年
人工智能·yolo·目标检测·ai
丝斯20115 小时前
AI学习笔记整理(66)——多模态大模型MOE-LLAVA
人工智能·笔记·学习