> 技术文档 > Spring AI 集成多个大语言模型_spring ai ailibaba集成多个大模型配置

Spring AI 集成多个大语言模型_spring ai ailibaba集成多个大模型配置


Spring AI 集成多个大语言模型

说明

本文档旨在指导开发者基于 Spring AI 框架,在 Spring Boot 2 环境下集成多种主流大语言模型(如 OpenAI ChatGPT、Deepseek、阿里云通义千问等),并提供从环境配置、模型调用、流式输出到提示模板与异常处理的完整使用示例。文中示例适配 Spring AI 进行开发。本教程适用于对 LLM 应用开发有一定基础的 Java 工程师,亦可作为企业多模型接入与管理的实现参考。

1. 环境准备

1.1 添加依赖

首先,在您的 pom.xml 中添加 Spring AI 和相关依赖:

<dependencies>  <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.7.x</version>  </dependency>  <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-turbo temperature: 0.7 base-url: https://api.openai.com/v1 deepseek: api-key: ${DEEPSEEK_API_KEY} model: deepseek-chat base-url: https://api.deepseek.com/v1 alibaba: dashscope: api-key: ${ALIBABA_DASHSCOPE_API_KEY} model: qwen-max temperature: 0.8 top-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;@SpringBootApplicationpublic class OpenAIDemo implements CommandLineRunner { @Autowired private ChatClient chatClient; public static void main(String[] args) { SpringApplication.run(OpenAIDemo.class, args); } @Override public 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;@SpringBootApplicationpublic class DeepseekDemo implements CommandLineRunner { @Autowired @Qualifier(\"deepseekChatClient\") private ChatClient chatClient; public static void main(String[] args) { SpringApplication.run(DeepseekDemo.class, args); } @Override public 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;@SpringBootApplicationpublic class AlibabaQianwenDemo implements CommandLineRunner { @Autowired @Qualifier(\"alibabaChatClient\") private ChatClient chatClient; public static void main(String[] args) { SpringApplication.run(AlibabaQianwenDemo.class, args); } @Override public 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;@Servicepublic class MultiModelService { private final ChatClient openAIClient; private final ChatClient deepseekClient; private final ChatClient alibabaClient; @Autowired public 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;@Servicepublic class PoemService { private final ChatClient chatClient; @Autowired public 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;@RestControllerpublic class StreamingController { private final StreamingChatClient streamingChatClient; @Autowired public 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. 最佳实践建议

  1. 密钥管理:始终将API密钥存储在环境变量或安全的密钥管理系统中,不要直接硬编码在配置文件中。

  2. 模型选择

    • 对于通用场景和英文内容,优先考虑OpenAI ChatGPT
    • 对于中文内容和本地化需求,通义千问表现更佳
    • 对于技术问题和代码生成,Deepseek可能是更好的选择
  3. 错误处理:为每个模型调用添加适当的错误处理和重试机制:

import org.springframework.ai.chat.ChatClient;import org.springframework.retry.annotation.Retryable;import org.springframework.stereotype.Service;@Servicepublic 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 \"当前服务不可用,请稍后再试\"; } }}
  1. 性能优化

    • 对于高频请求,考虑实现缓存机制
    • 使用流式响应改善用户体验
    • 合理设置超时参数
  2. 监控与日志

    • 记录每个模型的响应时间和成功率
    • 监控API使用量和费用
    • 设置告警机制应对服务中断

6. 扩展配置

6.1 高级YAML配置示例

spring: ai: openai: api-key: ${OPENAI_API_KEY} model: gpt-4-turbo temperature: 0.7 max-tokens: 1000 base-url: https://api.openai.com/v1 embedding: model: text-embedding-3-large dimensions: 1536 deepseek: api-key: ${DEEPSEEK_API_KEY} model: deepseek-coder temperature: 0.5 max-tokens: 2048 base-url: https://api.deepseek.com/v1 alibaba: dashscope: api-key: ${ALIBABA_DASHSCOPE_API_KEY} model: qwen-max-longcontext temperature: 0.8 top-p: 0.9 enable-search: true retry: max-attempts: 3 backoff: initial-interval: 1s multiplier: 2 max-interval: 5sserver: port: 8080 compression: enabled: true

6.2 动态配置更新

结合Nacos实现动态配置更新:

  1. 添加Nacos依赖
  2. 配置Nacos服务器地址
  3. 使用@RefreshScope注解使配置动态生效
spring: cloud: nacos: config: server-addr: ${NACOS_SERVER_ADDR:localhost:8848} namespace: ${NACOS_NAMESPACE:} group: DEFAULT_GROUP extension-configs: - data-id: spring-ai-config group: DEFAULT_GROUP refresh: true

7. 总结

本教程详细介绍了如何使用Spring AI框架集成OpenAI ChatGPT、Deepseek和阿里云通义千问三大语言模型。通过统一的接口抽象,开发者可以轻松切换不同的AI服务提供商,而无需大幅修改业务代码。

关键要点:

  1. 使用application.yml集中管理各模型配置,保持整洁和可维护性
  2. 利用Spring AI提供的统一API简化多模型集成
  3. 根据业务需求选择合适的模型
  4. 实施最佳实践确保安全性、可靠性和性能

随着AI技术的快速发展,Spring AI为Java开发者提供了一个强大而灵活的工具,帮助构建下一代智能应用程序。无论是内容创作、技术支持还是数据分析,合理利用这些大语言模型都能显著提升应用价值和用户体验。