Spring AI 集成多个大语言模型
Spring AI 集成多个大语言模型
说明
本文档旨在指导开发者基于 Spring AI 框架,在 Spring Boot 2 环境下集成多种主流大语言模型(如 OpenAI ChatGPT、Deepseek、阿里云通义千问等),并提供从环境配置、模型调用、流式输出到提示模板与异常处理的完整使用示例。文中示例适配 Spring AI 进行开发。本教程适用于对 LLM 应用开发有一定基础的 Java 工程师,亦可作为企业多模型接入与管理的实现参考。
1. 环境准备
1.1 添加依赖
首先,在您的 pom.xml
中添加 Spring AI 和相关依赖:
<dependencies><!-- Spring Boot Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.7.x</version> <!-- 使用兼容Java 8的版本 --></dependency><!-- Spring AI Core --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-core</artifactId></dependency><!-- 阿里云通义千问 --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId><version>1.0.0-M2</version></dependency>
</dependencies>
1.2 配置API密钥(使用application.yml)
在 application.yml
中配置各模型的API密钥和参数:
spring:ai:openai:api-key: ${OPENAI_API_KEY}model: gpt-3.5-turbotemperature: 0.7base-url: https://api.openai.com/v1deepseek:api-key: ${DEEPSEEK_API_KEY}model: deepseek-chatbase-url: https://api.deepseek.com/v1alibaba:dashscope:api-key: ${ALIBABA_DASHSCOPE_API_KEY}model: qwen-maxtemperature: 0.8top-p: 0.9server:port: 8080
注意:在实际项目中,建议将API密钥存储在环境变量中,而不是直接写在配置文件中,以提高安全性。
2. 基础使用示例
2.1 使用OpenAI ChatGPT
import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class OpenAIDemo implements CommandLineRunner {@Autowiredprivate ChatClient chatClient;public static void main(String[] args) {SpringApplication.run(OpenAIDemo.class, args);}@Overridepublic void run(String... args) throws Exception {String response = chatClient.call("用中文解释一下量子计算的基本概念");System.out.println("OpenAI 响应: \n" + response);}
}
2.2 使用Deepseek
import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DeepseekDemo implements CommandLineRunner {@Autowired@Qualifier("deepseekChatClient")private ChatClient chatClient;public static void main(String[] args) {SpringApplication.run(DeepseekDemo.class, args);}@Overridepublic void run(String... args) throws Exception {String response = chatClient.call("用Python写一个快速排序算法");System.out.println("Deepseek 响应: \n" + response);}
}
2.3 使用阿里云通义千问
import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class AlibabaQianwenDemo implements CommandLineRunner {@Autowired@Qualifier("alibabaChatClient")private ChatClient chatClient;public static void main(String[] args) {SpringApplication.run(AlibabaQianwenDemo.class, args);}@Overridepublic void run(String... args) throws Exception {String response = chatClient.call("写一首关于春天的七言绝句");System.out.println("通义千问 响应: \n" + response);}
}
3. 高级功能
3.1 多模型切换服务
创建一个统一的服务类来管理不同模型的调用:
import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;import java.util.Map;@Service
public class MultiModelService {private final ChatClient openAIClient;private final ChatClient deepseekClient;private final ChatClient alibabaClient;@Autowiredpublic MultiModelService(@Qualifier("openAiChatClient") ChatClient openAIClient,@Qualifier("deepseekChatClient") ChatClient deepseekClient,@Qualifier("alibabaChatClient") ChatClient alibabaClient) {this.openAIClient = openAIClient;this.deepseekClient = deepseekClient;this.alibabaClient = alibabaClient;}public String askOpenAI(String prompt) {return openAIClient.call(prompt);}public String askDeepseek(String prompt) {return deepseekClient.call(prompt);}public String askAlibabaQianwen(String prompt) {return alibabaClient.call(prompt);}public Map<String, String> askAllModels(String prompt) {return Map.of("OpenAI", askOpenAI(prompt),"Deepseek", askDeepseek(prompt),"Alibaba_Qianwen", askAlibabaQianwen(prompt));}
}
3.2 使用提示模板
# 在application.yml中添加提示模板配置
spring:ai:prompt:templates:poem-template:text: |请以{style}风格写一首关于{topic}的诗。要求:1. 语言优美,意境深远2. 包含至少两个修辞手法3. 长度在8-12行之间input-variables: style, topic
对应的Java代码:
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class PoemService {private final ChatClient chatClient;@Autowiredpublic PoemService(ChatClient chatClient) {this.chatClient = chatClient;}public String generatePoem(String style, String topic) {PromptTemplate promptTemplate = new PromptTemplate("""请以{style}风格写一首关于{topic}的诗。要求:1. 语言优美,意境深远2. 包含至少两个修辞手法3. 长度在8-12行之间""");promptTemplate.add("style", style);promptTemplate.add("topic", topic);return chatClient.call(promptTemplate.create().getContents());}
}
3.3 流式响应
对于需要实时响应的场景,可以使用流式API:
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.stream.StreamingChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;@RestController
public class StreamingController {private final StreamingChatClient streamingChatClient;@Autowiredpublic StreamingController(StreamingChatClient streamingChatClient) {this.streamingChatClient = streamingChatClient;}@GetMapping("/ai/stream")public Flux<String> streamChatResponse(@RequestParam String message) {Prompt prompt = new Prompt(new UserMessage(message));return streamingChatClient.stream(prompt).map(response -> response.getResult().getOutput().getContent());}
}
4. 模型特性比较
特性 | OpenAI ChatGPT | Deepseek | 阿里云通义千问 |
---|---|---|---|
中文支持 | 良好 | 优秀 | 优秀 |
代码能力 | 优秀 | 优秀 | 良好 |
中文创作 | 良好 | 优秀 | 优秀 |
价格 | 较高 | 中等 | 中等 |
响应速度 | 快 | 很快 | 快 |
最大token数 | 4096 | 4096 | 2000 |
适合场景 | 通用 | 技术/代码 | 中文创作 |
5. 最佳实践建议
-
密钥管理:始终将API密钥存储在环境变量或安全的密钥管理系统中,不要直接硬编码在配置文件中。
-
模型选择:
- 对于通用场景和英文内容,优先考虑OpenAI ChatGPT
- 对于中文内容和本地化需求,通义千问表现更佳
- 对于技术问题和代码生成,Deepseek可能是更好的选择
-
错误处理:为每个模型调用添加适当的错误处理和重试机制:
import org.springframework.ai.chat.ChatClient;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;@Service
public class RobustAIService {private final ChatClient chatClient;public RobustAIService(ChatClient chatClient) {this.chatClient = chatClient;}@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))public String safeChat(String prompt) {try {return chatClient.call(prompt);} catch (Exception e) {// 记录日志并执行回退逻辑return "当前服务不可用,请稍后再试";}}
}
-
性能优化:
- 对于高频请求,考虑实现缓存机制
- 使用流式响应改善用户体验
- 合理设置超时参数
-
监控与日志:
- 记录每个模型的响应时间和成功率
- 监控API使用量和费用
- 设置告警机制应对服务中断
6. 扩展配置
6.1 高级YAML配置示例
spring:ai:openai:api-key: ${OPENAI_API_KEY}model: gpt-4-turbotemperature: 0.7max-tokens: 1000base-url: https://api.openai.com/v1embedding:model: text-embedding-3-largedimensions: 1536deepseek:api-key: ${DEEPSEEK_API_KEY}model: deepseek-codertemperature: 0.5max-tokens: 2048base-url: https://api.deepseek.com/v1alibaba:dashscope:api-key: ${ALIBABA_DASHSCOPE_API_KEY}model: qwen-max-longcontexttemperature: 0.8top-p: 0.9enable-search: trueretry:max-attempts: 3backoff:initial-interval: 1smultiplier: 2max-interval: 5sserver:port: 8080compression:enabled: true
6.2 动态配置更新
结合Nacos实现动态配置更新:
- 添加Nacos依赖
- 配置Nacos服务器地址
- 使用
@RefreshScope
注解使配置动态生效
spring:cloud:nacos:config:server-addr: ${NACOS_SERVER_ADDR:localhost:8848}namespace: ${NACOS_NAMESPACE:}group: DEFAULT_GROUPextension-configs:- data-id: spring-ai-configgroup: DEFAULT_GROUPrefresh: true
7. 总结
本教程详细介绍了如何使用Spring AI框架集成OpenAI ChatGPT、Deepseek和阿里云通义千问三大语言模型。通过统一的接口抽象,开发者可以轻松切换不同的AI服务提供商,而无需大幅修改业务代码。
关键要点:
- 使用
application.yml
集中管理各模型配置,保持整洁和可维护性 - 利用Spring AI提供的统一API简化多模型集成
- 根据业务需求选择合适的模型
- 实施最佳实践确保安全性、可靠性和性能
随着AI技术的快速发展,Spring AI为Java开发者提供了一个强大而灵活的工具,帮助构建下一代智能应用程序。无论是内容创作、技术支持还是数据分析,合理利用这些大语言模型都能显著提升应用价值和用户体验。