MCP智能任务分配网关
一个原生支持MCP的服务器,能够实现从Claude等高级AI代理到更具成本效益的LLM的任务智能委派,从而在保持输出质量的同时优化成本。
服务介绍
LLM Gateway MCP 服务器
一个模型上下文协议 (MCP) 服务器,使高能力的 AI 代理能够智能地将任务委派给成本效益更高的 LLM

什么是 LLM Gateway?
LLM Gateway 是一个原生支持 MCP 的服务器,它使像 Claude 3.7 Sonnet 这样的高级 AI 代理能够智能地将任务委派给 Gemini Flash 2.0 Lite 等更具成本效益的模型。它提供了一个统一的接口来访问多个大型语言模型(LLM)提供商,同时优化了成本、性能和质量。
愿景:AI 驱动的资源优化
从根本上讲,LLM Gateway 代表了我们与 AI 系统交互方式的根本转变。与其使用单一昂贵的模型处理所有任务,它启用了一个智能层级结构,其中:
- 像 Claude 3.7 这样的高级模型专注于高层次推理、协调和复杂任务
- 具有成本效益的模型处理常规处理、提取和机械任务
- 整个系统以极低的成本实现了接近顶级的性能
这种方法类似于人类组织的工作方式——专家处理复杂的决策,而将常规任务委托给具有特定技能的人。
原生 MCP 架构
该服务器基于 模型上下文协议 (MCP) 构建,使其专门设计用于与 Claude 等 AI 代理一起工作。所有功能都通过 MCP 工具暴露出来,这些工具可以直接被这些代理调用,从而为 AI 到 AI 的委派创建无缝的工作流程。
主要用例:AI 代理任务委派
LLM Gateway 的主要设计目标是允许像 Claude 3.7 Sonnet 这样的高级 AI 代理智能地将任务委派给更便宜的模型:
delegates to
┌─────────────┐ ────────────────────────► ┌───────────────────┐ ┌──────────────┐
│ Claude 3.7 │ │ LLM Gateway │ ───────►│ Gemini Flash │
│ (Agent) │ ◄──────────────────────── │ MCP Server │ ◄───────│ DeepSeek │
└─────────────┘ returns results └───────────────────┘ │ GPT-4o-mini │
└──────────────┘
示例工作流程:
- Claude 识别出需要对文档进行摘要(对于 Claude 来说这是一个昂贵的操作)
- Claude 通过 MCP 工具将此任务委派给 LLM Gateway
- LLM Gateway 将摘要任务路由到 Gemini Flash(比 Claude 便宜 10-20 倍)
- 摘要返回给 Claude 以便进行更高层次的推理和决策
- Claude 可以将其能力集中在真正需要其智能的任务上
这种委派模式可以在保持输出质量的同时节省 70-90% 的 API 成本。
为什么使用 LLM Gateway?
🔄 AI 到 AI 任务委派
最强大的用例是使高级 AI 代理能够将常规任务委派给更便宜的模型:
- 让 Claude 3.7 使用 GPT-4o-mini 进行初始文档摘要
- 让 Claude 使用 Gemini 2.0 Flash light 进行数据提取和转换
- 允许 Claude 在不同提供商之间协调多阶段工作流程
- 使 Claude 能够为每个特定子任务选择合适的模型
💰 成本优化
高级模型的 API 成本可能相当高。LLM Gateway 通过以下方式帮助降低成本:
- 将适当的任务路由到更便宜的模型(例如,每 1K tokens $0.01 对比每 1K tokens $0.15)
- 实施高级缓存以避免冗余的 API 调用
- 跨提供商跟踪和优化成本
- 支持基于成本的任务路由决策
🔄 提供商抽象
通过统一接口避免供应商锁定:
- 为 OpenAI、Anthropic (Claude)、Google (Gemini) 和 DeepSeek 提供标准 API
- 一致的参数处理和响应格式
- 可以在不更改应用程序代码的情况下更换提供商
- 防止因特定提供商的问题或限制导致的服务中断
📄 大规模文档处理
高效处理大型文档:
- 将文档分解成语义上有意义的片段
- 并行处理多个模型中的片段
- 从非结构化文本中提取结构化数据
- 从大段文本生成摘要和见解
主要功能
MCP 协议集成
- 原生 MCP 服务器:基于 Model Context Protocol 构建,用于 AI 代理集成
- MCP 工具框架:所有功能通过标准化的 MCP 工具暴露
- 工具组合:可以将工具组合起来以实现复杂的工作流
- 工具发现:支持工具列表和能力发现
智能任务委派
- 任务路由:分析任务并将其路由到适当的模型
- 提供商选择:根据任务需求选择提供商
- 成本-性能平衡:针对成本、质量或速度进行优化
- 委派跟踪:监控委派模式和结果
高级缓存
- 多级缓存:多种缓存策略:
- 精确匹配缓存
- 语义相似性缓存
- 任务感知缓存
- 持久缓存:基于磁盘的持久化存储,并具有快速内存访问
- 缓存分析:跟踪节省情况和命中率
文档工具
- 智能分块:多种分块策略:
- 基于令牌的分块
- 语义边界检测
- 结构分析
- 文档操作:
- 摘要
- 实体提取
- 问题生成
- 批量处理
结构化数据提取
- JSON 提取:带模式验证的结构化 JSON 提取
- 表格提取:提取多种格式的表格
- 键值对提取:从文本中提取键值对
- 语义模式推断:从文本生成模式
锦标赛模式
- 代码和文本竞赛:支持举办锦标赛风格的竞赛
- 多模型:同时比较不同模型的输出
- 性能指标:评估和跟踪模型性能
- 结果存储:持久化竞赛结果以便进一步分析
高级向量操作
- 语义搜索:跨文档查找语义相似的内容
- 向量存储:高效存储和检索向量嵌入
- 混合搜索:结合关键词和语义搜索功能
- 批量处理:高效处理大型数据集
使用示例
Claude 使用 LLM Gateway 进行文档分析
此示例展示了 Claude 如何通过 LLM Gateway 将任务委托给更便宜的模型来处理文档:
import asyncio
from mcp.client import Client
async def main():
# Claude would use this client to connect to the LLM Gateway
client = Client("http://localhost:8013")
# Claude can identify a document that needs processing
document = "... large document content ..."
# Step 1: Claude delegates document chunking
chunks_response = await client.tools.chunk_document(
document=document,
chunk_size=1000,
method="semantic"
)
print(f"Document divided into {chunks_response['chunk_count']} chunks")
# Step 2: Claude delegates summarization to a cheaper model
summaries = []
total_cost = 0
for i, chunk in enumerate(chunks_response["chunks"]):
# Use Gemini Flash (much cheaper than Claude)
summary = await client.tools.summarize_document(
document=chunk,
provider="gemini",
model="gemini-2.0-flash-lite",
format="paragraph"
)
summaries.append(summary["summary"])
total_cost += summary["cost"]
print(f"Processed chunk {i+1} with cost ${summary['cost']:.6f}")
# Step 3: Claude delegates entity extraction to another cheap model
entities = await client.tools.extract_entities(
document=document,
entity_types=["person", "organization", "location", "date"],
provider="openai",
model="gpt-4o-mini"
)
total_cost += entities["cost"]
print(f"Total delegation cost: ${total_cost:.6f}")
# Claude would now process these summaries and entities using its advanced capabilities
# Close the client when done
await client.close()
if __name__ == "__main__":
asyncio.run(main())
多提供商比较以辅助决策
# Claude can compare outputs from different providers for critical tasks
responses = await client.tools.multi_completion(
prompt="Explain the implications of quantum computing for cryptography.",
providers=[
{"provider": "openai", "model": "gpt-4o-mini", "temperature": 0.3},
{"provider": "anthropic", "model": "claude-3-haiku-20240307", "temperature": 0.3},
{"provider": "gemini", "model": "gemini-2.0-pro", "temperature": 0.3}
]
)
# Claude could analyze these responses and decide which is most accurate
for provider_key, result in responses["results"].items():
if result["success"]:
print(f"{provider_key} Cost: ${result['cost']}")
成本优化工作流
# Claude can define and execute complex multi-stage workflows
workflow = [
{
"name": "Initial Analysis",
"operation": "summarize",
"provider": "gemini",
"model": "gemini-2.0-flash-lite",
"input_from": "original",
"output_as": "summary"
},
{
"name": "Entity Extraction",
"operation": "extract_entities",
"provider": "openai",
"model": "gpt-4o-mini",
"input_from": "original",
"output_as": "entities"
},
{
"name": "Question Generation",
"operation": "generate_qa",
"provider": "deepseek",
"model": "deepseek-chat",
"input_from": "summary",
"output_as": "questions"
}
]
# Execute the workflow
results = await client.tools.execute_optimized_workflow(
documents=[document],
workflow=workflow
)
print(f"Workflow completed in {results['processing_time']:.2f}s")
print(f"Total cost: ${results['total_cost']:.6f}")
文档分块
将大文档拆分为较小、可管理的块:
large_document = "... your very large document content ..."
chunking_response = await client.tools.chunk_document(
document=large_document,
chunk_size=500, # Target size in tokens
overlap=50, # Token overlap between chunks
method="semantic" # Or "token", "structural"
)
if chunking_response["success"]:
print(f"Document divided into {chunking_response['chunk_count']} chunks.")
# chunking_response['chunks'] contains the list of text chunks
else:
print(f"Error: {chunking_response['error']}")
多提供商补全
同时从多个提供商/模型获取相同提示的补全,以便进行比较:
multi_response = await client.tools.multi_completion(
prompt="What are the main benefits of using the MCP protocol?",
providers=[
{"provider": "openai", "model": "gpt-4o-mini"},
{"provider": "anthropic", "model": "claude-3-haiku-20240307"},
{"provider": "gemini", "model": "gemini-2.0-flash-lite"}
],
temperature=0.5
)
if multi_response["success"]:
print("Multi-completion results:")
for provider_key, result in multi_response["results"].items():
if result["success"]:
print(f"--- {provider_key} ---")
print(f"Completion: {result['completion']}")
print(f"Cost: ${result['cost']:.6f}")
else:
print(f"--- {provider_key} Error: {result['error']} ---")
else:
print(f"Multi-completion failed: {multi_response['error']}")
结构化数据提取(JSON)
将信息从文本中提取到特定的 JSON 模式中:
text_with_data = "User John Doe (john.doe@example.com) created an account on 2024-07-15. His user ID is 12345."
desired_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string", "format": "email"},
"creation_date": {"type": "string", "format": "date"},
"user_id": {"type": "integer"}
},
"required": ["name", "email", "creation_date", "user_id"]
}
json_response = await client.tools.extract_json(
document=text_with_data,
json_schema=desired_schema,
provider="openai", # Choose a provider capable of structured extraction
model="gpt-4o-mini"
)
if json_response["success"]:
print(f"Extracted JSON: {json_response['json_data']}")
print(f"Cost: ${json_response['cost']:.6f}")
else:
print(f"Error: {json_response['error']}")
增强生成检索(RAG)查询
使用 RAG 提问,系统在生成答案之前检索相关上下文(假设相关文档已被索引):
rag_response = await client.tools.rag_query( # Assuming a tool name like rag_query
query="What were the key findings in the latest financial report?",
# Parameters to control retrieval, e.g.:
# index_name="financial_reports",
# top_k=3,
provider="anthropic",
model="claude-3-haiku-20240307" # Model to generate the answer based on context
)
if rag_response["success"]:
print(f"RAG Answer:\n{rag_response['answer']}")
# Potentially include retrieved sources: rag_response['sources']
print(f"Cost: ${rag_response['cost']:.6f}")
else:
print(f"Error: {rag_response['error']}")
融合搜索(关键词 + 语义)
使用 Marqo 执行结合关键词相关性和语义相似性的混合搜索:
fused_search_response = await client.tools.fused_search( # Assuming a tool name like fused_search
query="impact of AI on software development productivity",
# Parameters for Marqo index and tuning:
# index_name="tech_articles",
# keyword_weight=0.3, # Weight for keyword score (0.0 to 1.0)
# semantic_weight=0.7, # Weight for semantic score (0.0 to 1.0)
# top_n=5,
# filter_string="year > 2023"
)
if fused_search_response["success"]:
print(f"Fused Search Results ({len(fused_search_response['results'])} hits):")
for hit in fused_search_response["results"]:
print(f" - Score: {hit['_score']:.4f}, ID: {hit['_id']}, Content: {hit.get('text', '')[:100]}...")
else:
print(f"Error: {fused_search_response['error']}")
本地文本处理
执行本地离线文本操作而不调用 LLM API:
# Assuming a tool that bundles local text functions
local_process_response = await client.tools.process_local_text(
text=" Extra spaces and\nnewlines\t here. ",
operations=[
{"action": "trim_whitespace"},
{"action": "normalize_newlines"},
{"action": "lowercase"}
]
)
if local_process_response["success"]:
print(f"Processed Text: '{local_process_response['processed_text']}'")
else:
print(f"Error: {local_process_response['error']}")
运行模型竞赛
比较多个模型在特定任务(如代码生成)上的输出:
# Assuming a tournament tool
tournament_response = await client.tools.run_model_tournament(
task_type="code_generation",
prompt="Write a Python function to calculate the factorial of a number.",
competitors=[
{"provider": "openai", "model": "gpt-4o-mini"},
{"provider": "anthropic", "model": "claude-3-opus-20240229"}, # Higher-end model for comparison
{"provider": "deepseek", "model": "deepseek-coder"}
],
evaluation_criteria=["correctness", "efficiency", "readability"],
# Optional: ground_truth="def factorial(n): ..."
)
if tournament_response["success"]:
print("Tournament Results:")
# tournament_response['results'] would contain rankings, scores, outputs
for rank, result in enumerate(tournament_response.get("ranking", [])):
print(f" {rank+1}. {result['provider']}/{result['model']} - Score: {result['score']:.2f}")
print(f"Total Cost: ${tournament_response['total_cost']:.6f}")
else:
print(f"Error: {tournament_response['error']}")
(此处可以添加更多工具示例...)
开始使用
安装
# Install uv if you don't already have it:
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone the repository
git clone https://github.com/yourusername/llm_gateway_mcp_server.git
cd llm_gateway_mcp_server
# Install in venv using uv:
uv venv --python 3.13
source .venv/bin/activate
uv pip install -e ".[all]"
环境设置
创建一个包含您的 API 密钥的 .env 文件:
# API Keys (at least one provider required)
OPENAI_API_KEY=your_openai_key
ANTHROPIC_API_KEY=your_anthropic_key
GEMINI_API_KEY=your_gemini_key
DEEPSEEK_API_KEY=your_deepseek_key
# Server Configuration
SERVER_PORT=8013
SERVER_HOST=127.0.0.1
# Logging Configuration
LOG_LEVEL=INFO
USE_RICH_LOGGING=true
# Cache Configuration
CACHE_ENABLED=true
CACHE_TTL=86400
运行服务器
# Start the MCP server
python -m llm_gateway.cli.main run
# Or with Docker
docker compose up
一旦运行,服务器将在 http://localhost:8013 上可用。
高级配置
虽然 .env 文件对于基本设置很方便,但 LLM Gateway 提供了更多详细的配置选项,主要通过环境变量进行管理。
服务器配置
SERVER_HOST:(默认值:127.0.0.1)服务器监听的网络接口。使用0.0.0.0监听所有接口(对于 Docker 或外部访问是必要的)。SERVER_PORT:(默认值:8013)服务器监听的端口。API_PREFIX:(默认值:/)API 端点的 URL 前缀。
日志配置
LOG_LEVEL: (默认:INFO) 控制日志的详细程度。选项:DEBUG,INFO,WARNING,ERROR,CRITICAL。USE_RICH_LOGGING: (默认:true) 使用 Rich 库进行彩色、格式化的控制台日志输出。设置为false以使用纯文本日志(更适合文件重定向或某些日志聚合系统)。LOG_FORMAT: (可选) 指定自定义的日志格式字符串。LOG_TO_FILE: (可选,例如:gateway.log) 日志应写入的文件路径。
缓存配置
CACHE_ENABLED: (默认:true) 全局启用或禁用缓存。CACHE_TTL: (默认:86400秒,即 24 小时) 缓存项的默认生存时间。特定工具可能会覆盖此设置。CACHE_TYPE: (默认:memory) 缓存后端的类型。选项可能包括memory,redis,diskcache。(注意:请检查当前实现支持的类型)。CACHE_MAX_SIZE: (可选) 缓存的最大项目数或内存大小。REDIS_URL: (如果CACHE_TYPE=redis则必需) Redis 缓存服务器的连接 URL(例如:redis://localhost:6379/0)。
提供者超时与重试
PROVIDER_TIMEOUT: (默认:120秒) 请求 LLM 提供者 API 的默认超时时间。PROVIDER_MAX_RETRIES: (默认:3) 失败提供者请求的默认重试次数(例如,由于临时网络问题或速率限制)。- 特定提供者的超时和重试可能通过专用变量如
OPENAI_TIMEOUT,ANTHROPIC_MAX_RETRIES等进行配置。(注意:请检查当前实现)。
工具特定配置
- 某些工具可能有自己特定的环境变量用于配置(例如,
MARQO_URL用于融合搜索,默认分块参数)。请参考个别工具的文档或源代码。
在启动服务器之前,请始终确保您的环境变量设置正确。更改通常需要重启服务器。
部署注意事项
虽然直接使用 python 或 docker compose up 运行服务器适合开发和测试,但在更健壮或生产部署中,请考虑以下几点:
1. 作为后台服务运行
为了确保网关持续运行并在失败或服务器重启时自动重启,请使用进程管理器:
systemd(Linux): 创建一个服务单元文件(例如/etc/systemd/system/llm-gateway.service)来管理进程。这样可以使用命令如sudo systemctl start|stop|restart|status llm-gateway。supervisor: 一个流行的 Python 编写的进程控制系统。配置supervisord来监控和控制网关进程。- Docker 重启策略: 如果使用 Docker(单独或 Compose),在
docker run命令或docker-compose.yml文件中配置适当的重启策略(例如,unless-stopped或always)。
2. 使用反向代理 (Nginx/Caddy/Apache)
强烈建议在 LLM Gateway 前放置一个反向代理:
- HTTPS/SSL 终止: 代理可以处理 SSL 证书(例如,使用 Caddy 和 Let's Encrypt 或 Nginx/Apache 和 Certbot),加密客户端和代理之间的流量。
- 负载均衡: 如果你需要运行多个网关实例以实现高可用性或性能提升,代理可以将流量分发到这些实例上。
- 路径路由: 将外部路径(例如,
https://api.yourdomain.com/llm-gateway/)映射到内部网关服务器(http://localhost:8013)。 - 安全头: 添加重要的安全头(如 CSP、HSTS)。
- 缓冲/缓存: 一些代理提供额外的请求/响应缓冲或缓存功能。
示例 Nginx location 块(简化版):
location /llm-gateway/ {
proxy_pass http://127.0.0.1:8013/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Add configurations for timeouts, buffering, etc.
}
3. 容器编排 (Kubernetes/Swarm)
如果在容器化环境中部署:
- 健康检查: 在你的部署清单中实现并配置健康检查端点(例如前面提到的
/healthz),以便编排器可以监控服务的健康状况。 - 配置管理: 使用 ConfigMaps 和 Secrets(Kubernetes)或等效机制来安全地管理环境变量和 API 密钥,而不是将它们硬编码在镜像中或仅依赖于
.env文件。 - 资源限制: 为网关容器定义适当的 CPU 和内存请求/限制,以确保稳定的性能并防止资源饥饿。
- 服务发现: 利用编排器的服务发现机制,而不是硬编码 IP 地址或主机名。
4. 资源分配
- 确保主机或容器具有足够的 RAM,特别是当使用内存缓存或处理大文档/请求时。
- 监控 CPU 使用率,特别是在高负载下或同时运行多个复杂操作时。
通过委托节省成本
使用 LLM Gateway 进行委托可以显著降低成本:
| 任务 | Claude 3.7 直接 | 委托给更便宜的 LLM | 节省 |
|---|---|---|---|
| 概述 100 页文档 | $4.50 | $0.45 (Gemini Flash) | 90% |
| 从 50 条记录中提取数据 | $2.25 | $0.35 (GPT-4o-mini) | 84% |
| 生成 20 个内容创意 | $0.90 | $0.12 (DeepSeek) | 87% |
| 处理 1,000 个客户查询 | $45.00 | $7.50 (混合委托) | 83% |
通过让 Claude 专注于高级推理和协调,而将机械任务委托给成本效益更高的模型,可以在保持高质量输出的同时实现这些节省。
为什么 AI 对 AI 的委托很重要
AI 对 AI 的委托的战略重要性不仅限于简单的成本节约:
普及高级 AI 功能
通过使强大的模型如 Claude 3.7、GPT-4o 等能够有效委托,我们:
- 以极低的成本使高级 AI 功能变得可访问
- 允许预算有限的组织利用顶级 AI 功能
- 促进行业内更高效地使用 AI 资源
经济资源优化
AI-to-AI 委托代表了一种基本的经济优化:
- 复杂推理、创造力和理解能力保留给顶级模型
- 日常数据处理、提取和更简单的任务交给成本效益高的模型
- 整个系统以一小部分成本实现接近顶级性能
- API 成本成为可控支出,而不是不可预测的负担
可持续的 AI 架构
这种方法促进了更可持续的 AI 使用:
- 减少对高端计算资源的不必要消耗
- 创建分层的 AI 方法,使能力与需求相匹配
- 使得仅使用顶级模型会成本过高的实验性工作变得可行
- 创建可扩展的 AI 集成方法,可以随着业务需求增长
技术演进路径
LLM Gateway 代表了 AI 应用架构的重要演进:
- 从单一的 AI 调用转向分布式多模型工作流
- 启用由 AI 驱动的复杂处理管道编排
- 为能够对其自身资源使用进行推理的 AI 系统奠定基础
- 构建能够做出智能委托决策的自优化 AI 系统
AI 效率的未来
LLM Gateway 指向了一个未来,在那里:
- AI 系统主动管理和优化其自身的资源使用
- 更高能力的模型作为整个 AI 生态系统的智能编排者
- AI 工作流变得越来越复杂和自我组织
- 组织能够以成本效益的方式利用全范围的 AI 能力
这种高效、自我组织的 AI 系统愿景代表了实际 AI 部署的下一个前沿,超越了目前对每个任务都使用单一模型的模式。
架构
MCP 集成的工作原理
LLM Gateway 基于 Model Context Protocol(模型上下文协议)构建:
- MCP 服务器核心:网关实现了一个完整的 MCP 服务器
- 工具注册:所有功能都作为 MCP 工具暴露
- 工具调用:Claude 和其他 AI 代理可以直接调用这些工具
- 上下文传递:结果以 MCP 的标准格式返回
这确保了与 Claude 和其他兼容 MCP 的代理无缝集成。
组件图
┌─────────────┐ ┌───────────────────┐ ┌──────────────┐
│ Claude 3.7 │ ────────► LLM Gateway MCP │ ────────► LLM Providers│
│ (Agent) │ ◄──────── Server & Tools │ ◄──────── (Multiple) │
└─────────────┘ └───────┬───────────┘ └──────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ Completion │ │ Document │ │ Extraction │ │
│ │ Tools │ │ Tools │ │ Tools │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
│ │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ Optimization │ │ Core MCP │ │ Analytics │ │
│ │ Tools │ │ Server │ │ Tools │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
│ │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ Cache │ │ Vector │ │ Prompt │ │
│ │ Service │ │ Service │ │ Service │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
│ │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ Tournament │ │ Code │ │ Multi-Agent │ │
│ │ Tools │ │ Extraction │ │ Coordination │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
│ │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ RAG Tools │ │ Local Text │ │ Meta Tools │ │
│ │ │ │ Tools │ │ │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
委托请求流程
当 Claude 将任务委托给 LLM Gateway 时:
- Claude 发送一个 MCP 工具调用请求
- Gateway 通过 MCP 协议接收请求
- 适当的工具处理该请求
- 缓存服务检查结果是否已缓存
- 如果未缓存,优化服务选择适当的提供者/模型
- 提供者层将请求发送到选定的 LLM API
- 响应被标准化、缓存,并记录指标
- MCP 服务器将结果返回给 Claude
详细功能文档
提供者集成
-
多提供商支持:
- 一流的支持包括:
- OpenAI (GPT-4o-mini, GPT-4o, GPT-4o mini)
- Anthropic (Claude 3.7 系列)
- Google (Gemini Pro, Gemini Flash, Gemini Flash Light)
- DeepSeek (DeepSeek-Chat, DeepSeek-Reasoner)
- 可扩展架构,便于添加新的提供商
- 一流的支持包括:
-
模型管理:
- 根据任务需求自动选择模型
- 模型性能跟踪
- 提供商故障时的回退机制
成本优化
-
智能路由:
- 根据以下因素自动选择模型:
- 任务复杂度要求
- 预算限制
- 性能优先级
- 历史性能数据
- 根据以下因素自动选择模型:
-
高级缓存系统:
- 多种缓存策略(精确、语义、基于任务)
- 每种任务类型的可配置 TTL
- 持久化缓存与快速内存查找
- 缓存统计和成本节省跟踪
文档处理
-
智能文档分块:
- 多种分块策略(基于令牌、语义、结构)
- 重叠配置以保留上下文
- 高效处理非常大的文档
-
文档操作:
- 摘要生成(支持可配置格式)
- 实体抽取
- 问答对生成
- 批量处理并控制并发
数据提取
- 结构化数据提取:
- 带模式验证的 JSON 提取
- 表格提取(JSON、CSV、Markdown 格式)
- 键值对提取
- 语义模式推断
竞赛和基准测试
-
模型竞赛:
- 在不同模型和配置之间运行竞赛
- 比较跨提供商的代码生成功能
- 生成统计性能报告
- 存储竞赛结果以进行历史分析
-
代码提取:
- 从模型响应中提取干净的代码
- 分析和验证提取的代码
- 支持多种编程语言
向量操作
-
嵌入服务:
- 高效生成文本嵌入
- 通过嵌入缓存减少 API 成本
- 批量处理以提高性能
-
语义搜索:
- 查找语义相似的内容
- 可配置的相似度阈值
- 快速向量操作
-
高级融合搜索 (Marqo):
- 利用 Marqo 进行关键词和语义搜索的结合
- 可调节关键词和向量相关性的权重
- 支持复杂的过滤和面分类
检索增强生成 (RAG)
-
上下文生成:
- 通过相关检索信息增强 LLM 提示
- 提高事实准确性并减少幻觉
- 与向量搜索和文档存储集成
-
工作流集成:
- 无缝结合文档检索与生成任务
- 可定制的检索和生成策略
本地文本处理
- 离线操作:
- 提供本地运行的文本处理工具,无需调用 API
- 包括函数