主流AI服务集成实战:OpenAI、Claude、Gemini与Grok接入指南

📅 2026/7/14 2:19:36
主流AI服务集成实战:OpenAI、Claude、Gemini与Grok接入指南
在技术项目开发中集成第三方 AI 服务已经成为提升应用智能能力的重要方式。无论是为产品添加对话交互、内容生成、代码辅助还是数据分析功能掌握主流 AI 工具的接入流程都是现代开发者必备的技能。本文将以工程实践的角度详细解析如何在项目中接入 OpenAI GPT、Claude、Grok 和 Gemini 这四类主流 AI 服务涵盖账号准备、API 密钥获取、SDK 集成、请求构造和异常处理等完整流程。适合有一定编程基础需要在 Web 应用、移动端或自动化脚本中集成 AI 能力的开发者和技术团队。通过本文的步骤你将能够在自己的开发环境中完成这些 AI 服务的配置和基础调用并了解生产环境中需要注意的关键事项。1. 理解不同 AI 服务的定位和接入方式在选择接入哪个 AI 服务前需要明确各服务的特性、适用场景和接入成本避免在项目中期才发现功能不匹配或预算超支。1.1 OpenAI GPT 系列通用对话和内容生成OpenAI 的 GPT 系列是目前最广泛使用的语言模型适用于聊天机器人、文本生成、翻译、摘要等通用场景。通过 OpenAI API 提供服务按使用量计费通常按 token 数量计算。最新模型如 GPT-4 在复杂推理和长文本处理上表现优秀GPT-3.5-turbo 则在成本与性能间取得较好平衡。技术接入特点RESTful API 接口规范支持流式响应有完善的官方 SDKPython、Node.js、Java 等文档详细且社区活跃。1.2 Claude长文本处理和安全性优先Anthropic 开发的 Claude 模型在长文档处理、逻辑推理和安全性方面有独特优势特别适合法律文档分析、技术规范解读、内容审核等需要处理大量文本且对输出安全性要求高的场景。Claude 3 系列模型支持 200K 上下文长度能一次性处理数百页文档。技术接入特点API 设计类似 OpenAI但有一些独特参数如 system 提示词角色同样提供官方 SDK 和流式响应支持。1.3 Grok实时信息访问和幽默风格xAI 开发的 Grok 模型最大特点是能访问 X平台的实时信息在需要结合最新时事、趋势话题的应用中具有优势。输出风格更加直接且带有幽默感适合社交媒体集成、新闻摘要、趋势分析等场景。技术接入特点目前主要通过 X平台开发者账号接入API 相对较新但遵循主流设计模式。1.4 Gemini多模态理解和谷歌生态集成Google 的 Gemini 模型在原生多模态能力上表现突出能同时处理文本、图像、音频和视频输入。适合需要视觉理解、跨模态生成的应用场景且与 Google 云服务深度集成便于已有 GCP 用户使用。技术接入特点通过 Google AI Studio 或 Vertex AI 提供服务支持 REST API 和 gRPC提供多种尺寸的模型选择。2. 环境准备和账号配置在开始编码前需要完成各平台的账号注册、认证和 API 密钥获取。不同平台的具体要求有所差异但整体流程相似。2.1 开发环境基础要求确保本地开发环境满足以下条件操作系统Windows 10/11、macOS 10.15 或主流 Linux 发行版Python 3.8或Node.js 16本文以 Python 示例为主网络能正常访问各 AI 服务 API 端点代码编辑器VS Code、PyCharm 等命令行工具终端# 检查 Python 环境 python --version pip --version # 或者检查 Node.js 环境 node --version npm --version2.2 OpenAI 账号和 API 密钥获取访问 OpenAI 平台 注册账号完成邮箱验证和手机号认证部分区域可能需要额外验证进入 API Keys 页面点击 Create new secret key妥善保存生成的密钥只显示一次注意新账号通常有免费试用额度但需要绑定支付方式后才能继续使用。生产环境要关注用量配额和费用控制。2.3 Claude 账号和 API 密钥获取访问 Anthropic 控制台 注册账号完成必要的身份验证在 API Keys 部分生成新的密钥记录密钥和可用的模型列表2.4 Grok 接入准备目前 Grok API 需要通过 X平台开发者账号申请访问 X开发者平台创建开发者账号和项目申请 API 访问权限可能需要等待审核获取 API 密钥和访问令牌2.5 Gemini 账号和 API 配置访问 Google AI Studio 或 Google Cloud Console使用 Google 账号登录创建新项目或选择现有项目启用 Generative Language API创建 API 密钥或配置服务账号3. 项目结构和依赖配置创建一个标准的 Python 项目来管理不同 AI 服务的集成代码这样便于维护和扩展。3.1 项目目录结构ai-integration-project/ ├── requirements.txt # Python 依赖列表 ├── config/ │ ├── __init__.py │ └── settings.py # 配置文件密钥等敏感信息 ├── services/ │ ├── __init__.py │ ├── openai_client.py # OpenAI 服务封装 │ ├── claude_client.py # Claude 服务封装 │ ├── grok_client.py # Grok 服务封装 │ └── gemini_client.py # Gemini 服务封装 ├── examples/ │ ├── basic_usage.py # 基础使用示例 │ └── advanced_features.py # 高级功能示例 └── tests/ ├── __init__.py └── test_services.py # 服务测试用例3.2 依赖管理配置创建requirements.txt文件包含所需依赖包openai1.0.0 anthropic0.25.0 google-generativeai0.3.0 requests2.31.0 python-dotenv1.0.0 pytest7.4.0安装依赖pip install -r requirements.txt3.3 环境变量和配置文件使用.env文件管理敏感信息避免将密钥硬编码在代码中# .env 文件示例 OPENAI_API_KEYsk-your-openai-key-here ANTHROPIC_API_KEYyour-claude-key-here X_API_KEYyour-x-api-key-here X_ACCESS_TOKENyour-x-access-token-here GOOGLE_API_KEYyour-google-api-key-here创建配置文件config/settings.pyimport os from dotenv import load_dotenv load_dotenv() class AIConfig: AI 服务配置类 # OpenAI 配置 OPENAI_API_KEY os.getenv(OPENAI_API_KEY) OPENAI_BASE_URL os.getenv(OPENAI_BASE_URL, https://api.openai.com/v1) # Claude 配置 ANTHROPIC_API_KEY os.getenv(ANTHROPIC_API_KEY) ANTHROPIC_BASE_URL os.getenv(ANTHROPIC_BASE_URL, https://api.anthropic.com) # Grok 配置通过 X API X_API_KEY os.getenv(X_API_KEY) X_ACCESS_TOKEN os.getenv(X_ACCESS_TOKEN) X_API_BASE_URL os.getenv(X_API_BASE_URL, https://api.x.com) # Gemini 配置 GOOGLE_API_KEY os.getenv(GOOGLE_API_KEY) GEMINI_MODEL os.getenv(GEMINI_MODEL, gemini-pro) # 通用配置 REQUEST_TIMEOUT int(os.getenv(REQUEST_TIMEOUT, 30)) MAX_RETRIES int(os.getenv(MAX_RETRIES, 3))4. 核心服务客户端实现为每个 AI 服务创建独立的客户端类封装 API 调用细节提供统一的接口风格。4.1 OpenAI 客户端实现# services/openai_client.py import openai from openai import OpenAI import json from typing import Dict, List, Optional, AsyncGenerator from config.settings import AIConfig class OpenAIClient: OpenAI 服务客户端 def __init__(self): self.client OpenAI( api_keyAIConfig.OPENAI_API_KEY, base_urlAIConfig.OPENAI_BASE_URL, timeoutAIConfig.REQUEST_TIMEOUT ) self.model gpt-3.5-turbo # 默认模型可根据需要调整 def chat_completion(self, messages: List[Dict[str, str]], model: Optional[str] None, temperature: float 0.7, max_tokens: Optional[int] None) - Dict: 聊天补全接口 try: response self.client.chat.completions.create( modelmodel or self.model, messagesmessages, temperaturetemperature, max_tokensmax_tokens, streamFalse ) return { content: response.choices[0].message.content, usage: { prompt_tokens: response.usage.prompt_tokens, completion_tokens: response.usage.completion_tokens, total_tokens: response.usage.total_tokens }, model: response.model } except openai.APIError as e: raise Exception(fOpenAI API 错误: {e}) except Exception as e: raise Exception(f请求失败: {e}) async def stream_chat_completion(self, messages: List[Dict[str, str]], model: Optional[str] None) - AsyncGenerator[str, None]: 流式聊天补全适用于实时对话场景 try: stream self.client.chat.completions.create( modelmodel or self.model, messagesmessages, streamTrue ) for chunk in stream: if chunk.choices[0].delta.content is not None: yield chunk.choices[0].delta.content except Exception as e: raise Exception(f流式请求失败: {e}) def get_models(self) - List[str]: 获取可用模型列表 try: models self.client.models.list() return [model.id for model in models.data] except Exception as e: raise Exception(f获取模型列表失败: {e}) # 使用示例 def openai_usage_example(): client OpenAIClient() messages [ {role: system, content: 你是一个有帮助的助手。}, {role: user, content: 请用 Python 写一个计算斐波那契数列的函数。} ] try: response client.chat_completion(messages) print(回答:, response[content]) print(Token 使用情况:, response[usage]) except Exception as e: print(f错误: {e})4.2 Claude 客户端实现# services/claude_client.py import anthropic from anthropic import Anthropic import json from typing import Dict, List, Optional from config.settings import AIConfig class ClaudeClient: Claude 服务客户端 def __init__(self): self.client Anthropic(api_keyAIConfig.ANTHROPIC_API_KEY) self.model claude-3-sonnet-20240229 # 可根据需要选择其他模型 def send_message(self, prompt: str, system: Optional[str] None, model: Optional[str] None, max_tokens: int 1024) - Dict: 发送消息到 Claude try: message self.client.messages.create( modelmodel or self.model, max_tokensmax_tokens, systemsystem, messages[{role: user, content: prompt}] ) return { content: message.content[0].text, usage: { input_tokens: message.usage.input_tokens, output_tokens: message.usage.output_tokens }, model: message.model } except anthropic.APIError as e: raise Exception(fClaude API 错误: {e}) except Exception as e: raise Exception(f请求失败: {e}) def process_long_document(self, document_text: str, instruction: str) - Dict: 处理长文档利用 Claude 的长上下文优势 system_prompt f 你是一个专业的文档分析助手。请根据以下指令处理用户提供的文档 {instruction} 请确保分析全面、准确并给出结构化的回答。 return self.send_message( promptdocument_text, systemsystem_prompt, max_tokens4000 # 长文档需要更多输出 token ) # 使用示例 def claude_usage_example(): client ClaudeClient() # 短对话示例 response client.send_message(请解释什么是机器学习) print(Claude 回答:, response[content]) # 长文档处理示例 long_text 这里是一篇很长的技术文档内容... # 实际使用时替换为真实文档 analysis client.process_long_document(long_text, 总结文档的主要观点) print(文档分析结果:, analysis[content])4.3 Grok 客户端实现# services/grok_client.py import requests import json from typing import Dict, Optional from config.settings import AIConfig class GrokClient: Grok 服务客户端通过 X API def __init__(self): self.api_key AIConfig.X_API_KEY self.access_token AIConfig.X_ACCESS_TOKEN self.base_url AIConfig.X_API_BASE_URL self.headers { Authorization: fBearer {self.access_token}, Content-Type: application/json } def send_message(self, message: str, context: Optional[str] None) - Dict: 发送消息到 Grok try: # 注意Grok API 端点可能随官方更新而变化 url f{self.base_url}/v1/grok/chat payload { message: message, context: context, stream: False } response requests.post( url, headersself.headers, jsonpayload, timeoutAIConfig.REQUEST_TIMEOUT ) if response.status_code 200: data response.json() return { content: data.get(response, ), usage: data.get(usage, {}), model: data.get(model, grok) } else: raise Exception(fAPI 请求失败: {response.status_code} - {response.text}) except requests.exceptions.RequestException as e: raise Exception(f网络请求错误: {e}) except Exception as e: raise Exception(f处理失败: {e}) def get_trending_topics(self) - Dict: 获取趋势话题Grok 特色功能 try: # 示例端点实际需要参考官方文档 url f{self.base_url}/v1/trends response requests.get(url, headersself.headers) if response.status_code 200: return response.json() else: raise Exception(f获取趋势失败: {response.status_code}) except Exception as e: raise Exception(f获取趋势话题错误: {e}) # 使用示例 def grok_usage_example(): client GrokClient() try: # 基础对话 response client.send_message(今天科技界有什么重要新闻) print(Grok 回答:, response[content]) # 趋势话题 trends client.get_trending_topics() print(当前趋势:, trends) except Exception as e: print(fGrok 请求错误: {e})4.4 Gemini 客户端实现# services/gemini_client.py import google.generativeai as genai from typing import Dict, List, Optional import PIL.Image import base64 from config.settings import AIConfig class GeminiClient: Gemini 服务客户端 def __init__(self): genai.configure(api_keyAIConfig.GOOGLE_API_KEY) self.model_name AIConfig.GEMINI_MODEL self.model genai.GenerativeModel(self.model_name) def text_generation(self, prompt: str) - Dict: 文本生成 try: response self.model.generate_content(prompt) return { content: response.text, usage: { prompt_token_count: response.usage_metadata.prompt_token_count, candidates_token_count: response.usage_metadata.candidates_token_count } if hasattr(response, usage_metadata) else {} } except Exception as e: raise Exception(fGemini 文本生成失败: {e}) def multimodal_generation(self, prompt: str, image_path: Optional[str] None, image_data: Optional[str] None) - Dict: 多模态生成文本图像 try: if image_path: # 从文件加载图像 img PIL.Image.open(image_path) response self.model.generate_content([prompt, img]) elif image_data: # 从 base64 数据加载图像 img_data base64.b64decode(image_data) img PIL.Image.open(io.BytesIO(img_data)) response self.model.generate_content([prompt, img]) else: raise ValueError(必须提供图像路径或图像数据) return { content: response.text, usage: getattr(response, usage_metadata, {}) } except Exception as e: raise Exception(f多模态生成失败: {e}) def chat_conversation(self, messages: List[Dict]) - Dict: 聊天对话 try: chat self.model.start_chat(history[]) # 构建历史记录 for msg in messages[:-1]: # 最后一条是当前消息 if msg[role] user: chat.send_message(msg[content]) else: # 这里需要根据实际 API 调整助手消息的处理方式 pass # 发送当前消息 response chat.send_message(messages[-1][content]) return { content: response.text, history: chat.history } except Exception as e: raise Exception(f聊天对话失败: {e}) # 使用示例 def gemini_usage_example(): client GeminiClient() # 文本生成 response client.text_generation(写一个关于人工智能的简短诗歌) print(Gemini 回答:, response[content]) # 多模态示例需要实际图像文件 # multimodal_response client.multimodal_generation( # 描述这张图片的内容, # image_pathpath/to/image.jpg # )5. 统一服务管理和高级功能创建统一的服务管理器方便在不同 AI 服务间切换和比较结果。5.1 统一服务管理器# services/ai_service_manager.py from typing import Dict, List, Optional from .openai_client import OpenAIClient from .claude_client import ClaudeClient from .grok_client import GrokClient from .gemini_client import GeminiClient class AIServiceManager: AI 服务统一管理器 def __init__(self): self.clients { openai: OpenAIClient(), claude: ClaudeClient(), grok: GrokClient(), gemini: GeminiClient() } def get_available_services(self) - List[str]: 获取可用的 AI 服务列表 return list(self.clients.keys()) def chat_with_service(self, service: str, message: str, **kwargs) - Dict: 使用指定服务进行聊天 if service not in self.clients: raise ValueError(f不支持的 AI 服务: {service}) client self.clients[service] if service openai: messages [{role: user, content: message}] return client.chat_completion(messages, **kwargs) elif service claude: return client.send_message(message, **kwargs) elif service grok: return client.send_message(message, **kwargs) elif service gemini: return client.text_generation(message, **kwargs) def compare_services(self, message: str, services: Optional[List[str]] None) - Dict: 比较不同服务的回答 if services is None: services self.get_available_services() results {} for service in services: try: results[service] self.chat_with_service(service, message) except Exception as e: results[service] {error: str(e)} return results # 使用示例 def manager_usage_example(): manager AIServiceManager() # 使用特定服务 response manager.chat_with_service(openai, 解释量子计算的基本概念) print(OpenAI 回答:, response[content]) # 比较不同服务 comparisons manager.compare_services(什么是深度学习, [openai, claude, gemini]) for service, result in comparisons.items(): print(f\n{service.upper()} 的回答:) if error in result: print(f错误: {result[error]}) else: print(result.get(content, 无内容))5.2 高级功能上下文管理和记忆在实际对话应用中维护对话上下文至关重要。以下是简单的上下文管理实现# services/context_manager.py from typing import Dict, List, Deque from collections import deque import json class ConversationContext: 对话上下文管理 def __init__(self, max_history: int 10): self.max_history max_history self.history: Deque[Dict] deque(maxlenmax_history) def add_message(self, role: str, content: str): 添加消息到历史 self.history.append({ role: role, content: content, timestamp: json.dumps(str(datetime.now())) }) def get_recent_history(self, num_messages: int 5) - List[Dict]: 获取最近的对话历史 return list(self.history)[-num_messages:] def clear_history(self): 清空对话历史 self.history.clear() def get_context_string(self, num_messages: int 5) - str: 将历史转换为上下文字符串 recent self.get_recent_history(num_messages) context_lines [] for msg in recent: role 用户 if msg[role] user else 助手 context_lines.append(f{role}: {msg[content]}) return \n.join(context_lines) # 集成到服务管理器 class AdvancedAIServiceManager(AIServiceManager): 带上下文管理的高级服务管理器 def __init__(self): super().__init__() self.conversations: Dict[str, ConversationContext] {} def chat_with_context(self, service: str, conversation_id: str, message: str) - Dict: 带上下文的对话 if conversation_id not in self.conversations: self.conversations[conversation_id] ConversationContext() context self.conversations[conversation_id] context.add_message(user, message) # 构建带上下文的提示词 recent_history context.get_context_string(3) full_prompt f之前的对话上下文 {recent_history} 当前用户消息{message} 请根据上下文提供连贯的回答 # 调用 AI 服务 response self.chat_with_service(service, full_prompt) # 添加助手回复到上下文 context.add_message(assistant, response[content]) return response6. 错误处理和重试机制在生产环境中稳定的错误处理和重试机制至关重要。以下是完善的异常处理方案6.1 自定义异常类# exceptions/ai_exceptions.py class AIServiceError(Exception): AI 服务基础异常 pass class AuthenticationError(AIServiceError): 认证失败异常 pass class RateLimitError(AIServiceError): 频率限制异常 pass class ServiceUnavailableError(AIServiceError): 服务不可用异常 pass class InvalidRequestError(AIServiceError): 无效请求异常 pass6.2 带重试的装饰器# utils/retry_utils.py import time import logging from functools import wraps from typing import Callable, Any logger logging.getLogger(__name__) def retry_with_backoff( max_retries: int 3, initial_delay: float 1.0, backoff_factor: float 2.0, exceptions: tuple (Exception,) ): 重试装饰器支持指数退避 def decorator(func: Callable) - Callable: wraps(func) def wrapper(*args, **kwargs) - Any: delay initial_delay last_exception None for attempt in range(max_retries 1): try: return func(*args, **kwargs) except exceptions as e: last_exception e if attempt max_retries: logger.error(f函数 {func.__name__} 重试 {max_retries} 次后失败) raise last_exception logger.warning(f函数 {func.__name__} 第 {attempt 1} 次尝试失败: {e}) time.sleep(delay) delay * backoff_factor raise last_exception return wrapper return decorator # 应用到客户端方法 class RobustOpenAIClient(OpenAIClient): 带重试机制的 OpenAI 客户端 retry_with_backoff( max_retries3, initial_delay1, backoff_factor2, exceptions(RateLimitError, ServiceUnavailableError) ) def robust_chat_completion(self, messages, **kwargs): 带重试的聊天补全 return self.chat_completion(messages, **kwargs)6.3 错误处理最佳实践表错误类型现象重试策略处理建议认证失败401 状态码不重试检查 API 密钥有效性重新生成密钥频率限制429 状态码指数退避重试降低请求频率申请提升配额服务不可用503 状态码有限次重试等待服务恢复检查服务状态页无效请求400 状态码不重试检查请求参数格式和内容网络超时请求超时异常立即重试检查网络连接增加超时时间7. 性能优化和监控在生产环境中使用 AI 服务时需要关注性能指标和成本控制。7.1 请求监控装饰器# utils/monitoring.py import time import functools from typing import Dict, Any import statistics class PerformanceMonitor: 性能监控器 def __init__(self): self.metrics: Dict[str, list] {} def track_performance(self, service_name: str): 性能跟踪装饰器 def decorator(func): functools.wraps(func) def wrapper(*args, **kwargs): start_time time.time() try: result func(*args, **kwargs) duration time.time() - start_time # 记录指标 if service_name not in self.metrics: self.metrics[service_name] [] self.metrics[service_name].append(duration) # 添加性能信息到结果 if isinstance(result, dict): result[performance] { duration_ms: round(duration * 1000, 2), service: service_name } return result except Exception as e: duration time.time() - start_time # 记录失败请求的持续时间 if f{service_name}_errors not in self.metrics: self.metrics[f{service_name}_errors] [] self.metrics[f{service_name}_errors].append(duration) raise e return wrapper return decorator def get_performance_stats(self) - Dict[str, Dict]: 获取性能统计 stats {} for service, durations in self.metrics.items(): if durations: stats[service] { request_count: len(durations), avg_duration_ms: round(statistics.mean(durations) * 1000, 2), p95_duration_ms: round(statistics.quantiles(durations, n20)[18] * 1000, 2), min_duration_ms: round(min(durations) * 1000, 2), max_duration_ms: round(max(durations) * 1000, 2) } return stats # 使用示例 monitor PerformanceMonitor() class MonitoredOpenAIClient(OpenAIClient): 带性能监控的 OpenAI 客户端 monitor.track_performance(openai) def chat_completion(self, messages, **kwargs): return super().chat_completion(messages, **kwargs)7.2 成本控制和用量统计# utils/cost_tracker.py class CostTracker: 成本跟踪器 # 示例价格实际价格以官方为准 PRICING { openai: { gpt-3.5-turbo: {input: 0.0015, output: 0.002}, # 每千 token 价格 gpt-4: {input: 0.03, output: 0.06} }, claude: { claude-3-sonnet: {input: 0.003, output: 0.015} } } def __init__(self): self.usage_stats: Dict[str, Dict] {} def track_usage(self, service: str, model: str, usage: Dict): 跟踪使用量 key f{service}_{model} if key not in self.usage_stats: self.usage_stats[key] { input_tokens: 0, output_tokens: 0, total_cost: 0.0 } stats self.usage_stats[key] input_tokens usage.get(prompt_tokens, usage.get(input_tokens, 0)) output_tokens usage.get(completion_tokens, usage.get(output_tokens, 0)) stats[input_tokens] input_tokens stats[output_tokens] output_tokens # 计算成本 if service in self.PRICING and model in self.PRICING[service]: pricing self.PRICING[service][model] cost (input_tokens / 1000 * pricing[input] output_tokens / 1000 * pricing[output]) stats[total_cost] cost def get_cost_report(self) - Dict: 生成成本报告 return self.usage_stats8. 生产环境部署建议将 AI 服务集成到生产环境时需要考虑以下关键因素。8.1 安全配置清单[ ] API 密钥通过环境变量或密钥管理服务传递不写入代码[ ] 实施请求频率限制防止滥用[ ] 验证用户输入防止提示词注入攻击[ ] 记录审计日志跟踪 AI 服务使用情况[ ] 定期轮换 API 密钥[ ] 使用网络策略限制出站连接8.2 性能优化清单[ ] 实现响应缓存减少重复请求[ ] 使用连接池管理 HTTP 连接[ ] 设置合理的超时时间通常 30-60 秒[ ] 监控 token 使用量优化提示词长度[ ] 考虑异步处理长时间运行的任务8.3 监控和告警配置需要监控的关键指标请求成功率4xx/5xx 错误率平均响应时间Token 使用量和成本并发请求数服务配额使用情况8.4 容灾和降级方案制定多服务降级策略主服务OpenAI GPT-4备用服务 1Claude 3备用服务 2Gemini Pro降级方案本地模型或规则引擎实现示例class FallbackAIManager: 带降级的 AI 服务管理器 def __init__(self, service_priority: List[str] None): if service_priority is None: service_priority [openai, claude, gemini, grok] self.service_priority service_priority self.manager AIServiceManager() def chat_with_fallback(self, message: str, **kwargs) - Dict: 带降级的聊天请求 last_error None for service in self.service_priority: try: result self.manager.chat_with_service(service, message, **kwargs) result[service_used] service return result except Exception as e: last_error e print(f服务 {service} 失败: {e}) continue # 所有服务都失败 raise Exception(f所有 AI 服务都不可用。最后错误: {last_error})通过本文的完整实现你可以在项目中稳健地集成主流 AI 服务具备生产环境所需的错误处理、性能监控和成本控制