用途
本技能用于在 Spring Boot 应用中集成大语言模型(LLM)、聊天客户端、向量嵌入(embeddings)、RAG(检索增强生成)流水线以及 AI 智能体。它覆盖 Spring AI 2.0 的核心用法与迁移要点,帮助开发者避开旧版本命名和配置带来的常见错误。
主要能力
依赖与版本管理
通过 spring-ai-bom 2.0.0 统一管理版本。Spring Boot 4 需要 Spring AI 2.0;1.x 系列仅面向 Boot 3。Starter 坐标遵循 spring-ai-starter-model-<provider>(如 -model-anthropic、-model-openai)与 spring-ai-starter-vector-store-<store> 规则。2.0 中已移除 spring-ai-starter-model-azure-openai,改用 OpenAI starter 配合 Azure base URL。
RAG / 向量检索相关依赖包括 spring-ai-starter-vector-store-pgvector;QuestionAnswerAdvisor 所在的依赖在 2.0 中已更名为 spring-ai-vector-store-advisor(原名为 spring-ai-advisors-vector-store)。
ChatClient 基础用法
支持通过 chatClient.prompt() 构建请求,使用 .user() 传入用户消息、.system() 设置系统提示,配合 .param() 注入模板变量,最后以 .call().content() 获取响应。
使用记忆顾问(memory advisor)的每次调用都必须提供用户级或会话级的 ChatMemory.CONVERSATION_ID,不能为所有用户共用同一个会话 ID。
ChatClient Bean 配置
通过 @Configuration 定义 ChatMemory 与 ChatClient Bean。2.0 中 InMemoryChatMemory 已移除,改用 MessageWindowChatMemory(滑动窗口限制历史消息,默认使用内存仓库)。默认顾问通过 builder 方式构建 MessageChatMemoryAdvisor 与 SimpleLoggerAdvisor。2.0 中 ChatMemory.DEFAULT_CONVERSATION_ID 已移除,缺少会话 ID 参数会抛出 IllegalArgumentException。
外置化提示词模板
提示词可放在 src/main/resources/prompts/ 下的 .st 文件中,通过 @Value("classpath:...") 注入 Resource 后在 .text(promptTemplate) 中使用 .param() 填充变量。
结构化输出
通过 .call().entity(OrderClassification.class) 直接将响应映射为 Java record,由 Spring AI 处理 JSON 解析。注意:对列表类型不能使用 .entity(List.class),因为泛型会被擦除,应传入 new ParameterizedTypeReference<List<X>>() {}。
RAG 流水线
向量库无需手动创建 Bean,spring-ai-starter-vector-store-pgvector 会自动配置,直接注入 VectorStore 即可(旧的 new PgVectorStore(...) 构造器已移除,如需构建请使用 PgVectorStore.builder(...))。通过 QuestionAnswerAdvisor.builder(vectorStore) 配合 SearchRequest.builder().topK(5).build() 配置检索顾问。文档摄取使用 vectorStore.add(docs),查询通过带有 RAG 顾问的 ChatClient 完成。
流式响应
在 @GetMapping 中设置 produces = MediaType.TEXT_EVENT_STREAM_VALUE,使用 .stream().content() 返回 Flux<String>。
配置(application.yml)
2.0 已将属性扁平化,避免旧的 chat.options.* 嵌套,例如使用 spring.ai.anthropic.chat.model 与 spring.ai.anthropic.chat.max-tokens。2.0 移除了 temperature 0.7 的默认值,如需依赖需显式设置。API 密钥应通过环境变量 ${...} 注入。
适用场景
- 在 Spring Boot 4 项目中集成 Anthropic、OpenAI 等 LLM 提供商
- 构建带对话记忆的聊天服务
- 实现基于向量库的 RAG 知识问答
- 需要结构化输出(分类、抽取)的业务场景
- 需要 SSE 流式返回的实时对话接口
- 从 Spring AI 1.x 或更早版本迁移到 2.0 的项目
限制与注意事项
- 版本配对必须正确:Spring Boot 4 需要 Spring AI 2.0,1.x 仅支持 Boot 3
- 旧版 starter 命名(如
spring-ai-anthropic-spring-boot-starter)在 Maven Central 中无法解析 MessageChatMemoryAdvisor需用 builder 构建,不能new(...)PromptChatMemoryAdvisor在 2.0 中已移除,应使用MessageChatMemoryAdvisor- 不应硬编码 API 密钥或模型 ID,应通过环境变量或外部配置注入
- 提示词应外置到资源文件,避免字符串拼接
- 应使用
.entity()结构化输出而非手动解析 - API 调用应包裹 try/catch,区分
NonTransientAiException(不重试)与TransientAiException(重试)