大模型开发 - 如何在Spring AI中配置多个LLM
Spring AI多模型集成实战指南 本文系统介绍了如何在Spring Boot应用中集成多个大语言模型(LLM)。主要内容包括: 多厂商模型配置:详细演示了OpenAI和Anthropic等不同厂商LLM的集成方法,包括依赖引入、API配置和客户端创建。 同厂商多模型管理:展示了如何配置同一厂商下的多个模型实例,并利用Spring AI的模型注册机制进行统一管理。 智能模型路由:构建了可根据对话
文章目录

Pre
大模型开发 - 03 QuickStart_借助DeepSeekChatModel实现Spring AI 集成 DeepSeek
大模型开发 - 04 QuickStart_DeepSeek 模型调用流程源码解析:从 Prompt 到远程请求
大模型开发 - 05 QuickStart_接入阿里百炼平台:Spring AI Alibaba 与 DashScope SDK
大模型开发 - 06 QuickStart_本地大模型私有化部署实战:Ollama + Spring AI 全栈指南
大模型开发 - 07 ChatClient:构建统一、优雅的大模型交互接口
大模型开发 - 08 ChatClient:构建智能对话应用的流畅 API
大模型开发 - 09 ChatClient:基于 Spring AI 的多平台多模型动态切换实战
大模型开发 - 10 ChatClient:Advisors API 构建可插拔、可组合的智能对话增强体系
大模型开发 - 11 ChatClient:Advisor 机制详解:拦截、增强与自定义 AI 对话流程
大模型开发 - 12 Prompt:Spring AI 中的提示(Prompt)系统详解_从基础概念到高级工程实践
大模型开发 - 13 Prompt:提示词工程实战指南_Spring AI 中的提示设计、模板化与最佳实践
大模型开发 - 14 Chat Memory:实现跨轮次对话上下文管理
大模型开发 - 15 Tool Calling :从入门到实战,一步步构建智能Agent系统
大模型开发 - 16 Chat Memory:借助 ChatMemory + PromptChatMemoryAdvisor轻松实现大模型多轮对话记忆
大模型开发 - 17 Structured Output Converter:结构化输出转换器_从文本到结构化数据的可靠桥梁
大模型开发 - 18 Chat Memory:集成 JdbcChatMemoryRepository 实现大模型多轮对话记忆
大模型开发 - 19 Chat Memory:集成 BaseRedisChatMemoryRepository实现大模型多轮对话记忆
大模型开发 - 20 Chat Memory:多层次记忆架构_突破大模型对话中的 Token 上限瓶颈
大模型开发 - 21 Structured Output Converter:结构化输出功能实战指南
大模型开发 - 22 Multimodality API:多模态大模型与 Spring AI 的融合
大模型开发 - 23 Chat Model API:深入解析 Spring AI Chat Model API_构建统一、灵活、可扩展的 AI 对话系统
大模型开发 - 24 Embeddings Model API:深入解析 Spring AI Embeddings Model API_构建语义理解的基石
大模型开发 - 25 Image Model API:深入解析 Spring AI Image Model API_构建统一、灵活的 AI 图像生成系统
大模型开发 - 26 Origin Tools: Spring AI 结构化多聊天客户端实战
大模型开发 - 27 Tool Calling:Spring AI 中的工具调用指南
大模型开发 - 28 Tool Calling:Spring AI 工具调用执行外部操作实战
大模型开发 - 29 Tool Calling:大模型与业务系统集成的利器 _Tool Calling 实战指南
大模型开发 - 30 Tool Calling:Spring AI Tool Calling 工作原理及源码详解
大模型开发 - 31 Tool Calling:解决大模型“工具选择困难症”_基于 RAG 的动态工具加载方案解读
大模型开发 - 32 Tool Calling:Spring AI 工具调用最佳实践完整指南
大模型开发 - 33 MCP:深入理解 Model Context Protocol(MCP)及其在 Spring AI 中的实践指南
大模型开发 - 34 MCP:Spring AI MCP 客户端启动器(MCP Client Boot Starter)深度指南
大模型开发 - 35 MCP:Spring AI MCP 服务端启动器(MCP Server Boot Starter)完全指南
大模型开发 - 36 MCP:深入理解 MCP Utilities :同步与异步工具回调
大模型开发 - 37 RAG:Retrieval Augmented Generation(RAG)详解与实战指南
概述
现代应用越来越多地集成大语言模型,以构建智能化解决方案。虽然单个LLM可以处理多类任务,但仅依赖一种模型并非最优方案。不同模型在技术分析、创意写作等领域各有专长,此外我们也可能希望用轻量且低成本的模型处理由简单任务,将高性能模型用于复杂场景。
本文将讲解如何在Spring Boot应用中利用Spring AI集成多个LLM。涵盖如何配置不同厂商的模型,以及同一厂商下的多个模型,在此基础上构建弹性聊天机器人,实现模型自动切换与故障转移。
一、配置不同厂商的LLM
以OpenAI和Anthropic为例,分别配置它们的LLM。
1.1 配置主模型(OpenAI)
首先在pom.xml引入OpenAI依赖:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
<version>1.0.2</version>
</dependency>
在application.yaml中配置API Key和模型:
spring:
ai:
open-ai:
api-key: ${OPENAI_API_KEY}
chat:
options:
model: ${PRIMARY_LLM}
temperature: 1
配置后,Spring AI会自动创建OpenAiChatModel bean。可用来定义ChatClient,即与LLM交互的入口:
@Configuration
class ChatbotConfiguration {
@Bean
@Primary
ChatClient primaryChatClient(OpenAiChatModel chatModel) {
return ChatClient.create(chatModel);
}
}
通过@Primary注解,Spring Boot会优先注入该ChatClient。
1.2 配置第二模型(Anthropic)
添加Anthropic依赖(即你选中的 <artifactId>spring-ai-starter-model-anthropic</artifactId>):
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-anthropic</artifactId>
<version>1.0.2</version>
</dependency>
在application.yaml配置Anthropic API key和模型:
spring:
ai:
anthropic:
api-key: ${ANTHROPIC_API_KEY}
chat:
options:
model: ${SECONDARY_LLM}
定义Anthropic模型对应的ChatClient Bean:
@Bean
ChatClient secondaryChatClient(AnthropicChatModel chatModel) {
return ChatClient.create(chatModel);
}
二、配置同一厂商的多个LLM
Spring AI默认每个厂商只自动创建一个ChatModel,如需同厂商多个模型需手动定义:
-
先在
application.yaml中为第三模型留自定义字段:spring: ai: anthropic: chat: options: tertiary-model: ${TERTIARY_LLM} -
配置第三模型对应Bean,复用AnthropicApi与默认AnthropicChatModel,设置模型名:
@Bean ChatModel tertiaryChatModel( AnthropicApi anthropicApi, AnthropicChatModel anthropicChatModel, @Value("${spring.ai.anthropic.chat.options.tertiary-model}") String tertiaryModelName) { AnthropicChatOptions chatOptions = anthropicChatModel.getDefaultOptions().copy(); chatOptions.setModel(tertiaryModelName); return AnthropicChatModel.builder() .anthropicApi(anthropicApi) .defaultOptions(chatOptions) .build(); } @Bean ChatClient tertiaryChatClient( @Qualifier("tertiaryChatModel") ChatModel tertiaryChatModel) { return ChatClient.create(tertiaryChatModel); }
如果需要不同API Key或配置,可进一步定制AnthropicChatOptions。
三、实际案例:弹性聊天机器人
实现一个聊天机器人,主模型失败时,自动切换备用模型,再失败还可切换至第三模型,使用Spring Retry实现故障转移。
3.1 服务层实现
创建服务类,自动注入三个ChatClient:
@Retryable(retryFor = Exception.class, maxAttempts = 3)
String chat(String prompt) {
logger.debug("用主模型处理: '{}', 尝试#{}", prompt, RetrySynchronizationManager.getContext().getRetryCount() + 1);
return primaryChatClient.prompt(prompt).call().content();
}
@Recover
String chat(Exception exception, String prompt) {
logger.warn("主模型失败: {}", exception.getMessage());
logger.debug("尝试备用模型处理: '{}'", prompt);
try {
return secondaryChatClient.prompt(prompt).call().content();
} catch (Exception e) {
logger.warn("备用模型失败: {}", e.getMessage());
logger.debug("尝试第三模型处理: '{}'", prompt);
return tertiaryChatClient.prompt(prompt).call().content();
}
}
3.2 REST API暴露
@PostMapping("/api/chatbot/chat")
ChatResponse chat(@RequestBody ChatRequest request) {
String response = chatbotService.chat(request.prompt);
return new ChatResponse(response);
}
record ChatRequest(String prompt) {}
record ChatResponse(String response) {}
四、测试与验证
启动应用时,主模型和副模型可故意用无效名称,第三模型使用有效名称。例如:
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
PRIMARY_LLM=gpt-100
SECONDARY_LLM=claude-opus-200
TERTIARY_LLM=claude-3-haiku-20240307
mvn spring-boot:run
用HTTPie命令行调用API:
http POST :8080/api/chatbot/chat prompt="法国的首都是哪里?"
返回:
{
"response": "法国的首都是巴黎。"
}
日志可见主模型尝试三次失败,备用模型失败,第三模型成功响应,验证故障转移链路。
五、总结
本文演示了如何在Spring AI应用中集成多个LLM实现弹性伸缩,既可用不同厂商模型,也可配置同厂商多个模型,进而构建高可用的聊天机器人服务,并详细阐述实现步骤和代码细节,便于开发者落地。1

更多推荐



所有评论(0)