LLM网关(MCP服务器)
通过模型上下文协议(MCP)为多个AWS基岩模型提供集中式网关
该项目实现了一个MCP服务器,允许AI代理和工作流与 15+AWS基岩基础模型 (Nova、Claude、Llama、Mistral等)通过标准化的MCP接口。
🎯 目的
LLM网关充当 通用桥接 在外部AI工作流程和基岩基础模型之间,提供:
- 统一访问 15+基岩模型(Nova、Claude、Llama、Mistral)
- 每个代理选择其模型 基于其需求(在代理中硬编码)
- 智能缓存 降低成本和延迟的响应
- 详细指标 关于使用、成本和性能
- 标准MCP接口 用于通用代理连接
🏗️ 建筑
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Agent A │ │ Agent B │ │ Agent C │
│ (nova-pro) │ │ (claude) │ │ (llama) │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
▲ ▲ ▲
│ │ │
│ MCP Protocol (stdio/SSE) │
└──────────────────────┼──────────────────────┘
▼
┌────────────────────┐
│ LLM Gateway │
│ (MCP Server) │
│ │
│ ┌──────────────┐ │
│ │ Router │ │
│ ├──────────────┤ │
│ │ Cache │ │
│ ├──────────────┤ │
│ │ Metrics │ │
│ └──────────────┘ │
└─────────┬──────────┘
▲
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌──────────┐
│ Nova │ │ Claude │ │ Llama │
│ Models │ │ Models │ │ Models │
└─────────┘ └─────────┘ └──────────┘
AWS Bedrock Foundation Models📁 项目结构
llm-gateway/
├── src/
│ ├── server.py # Main FastMCP server
│ ├── config.py # Configuration (AWS Bedrock only)
│ │
│ ├── models/ # 🆕 Bedrock models catalog
│ │ ├── bedrock_models.py # 15+ FMs with pricing
│ │ └── __init__.py
│ │
│ ├── bedrock/ # 🆕 Universal Bedrock client
│ │ ├── bedrock_client.py # Single client for all models
│ │ └── __init__.py
│ │
│ ├── mcp/ # MCP Tools
│ │ ├── tools.py # generate, list_models, get_stats
│ │ └── __init__.py
│ │
│ ├── core/ # Business logic
│ │ ├── router.py # Model routing
│ │ ├── cache.py # Cache system
│ │ ├── metrics.py # Metrics tracking
│ │ └── __init__.py
│ │
│ └── utils/ # Utilities
│ ├── logger.py # Centralized logging
│ ├── validators.py # Validations
│ └── __init__.py
│
├── ForAgents/ # 🎯 LangGraph agent integration
│ ├── bedrock_client.py # MCP client (stdio)
│ ├── llm_node.py # Reusable LangGraph node
│ ├── example_agent.py # 5 complete examples
│ ├── requirements.txt # Agent dependencies
│ └── README.md # Integration guide
│
├── Dockerfile # 🐳 Docker image for production
├── docker-compose.yml # Easy deployment with Docker Compose
├── .dockerignore # Build exclusions
│
├── requirements.txt # Gateway dependencies
├── .env.example # Environment variables template
└── README.md # This file🚀 安装
1.克隆并安装依赖项
cd llm-gateway
pip install -r requirements.txt2.配置环境变量
创建 .env 使用您的AWS凭据创建文件:
# AWS Bedrock (only required configuration)
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
# Cache and metrics
CACHE_ENABLED=true
CACHE_TTL=3600
CACHE_MAX_SIZE=1000
METRICS_ENABLED=true
# Logging
LOG_LEVEL=INFO3.运行服务器
python -m src.server📋 可用模型
网关支持 15+基岩模型:
亚马逊新星
nova-pro-高级、卓越的推理能力(每1K 0.0008美元/0.0032美元)nova-lite-快速经济(每1K 0.00006美元/0.00024美元)nova-micro-超快、基本(0.000035美元/1K 0.00014美元)
人物克劳德
claude-3-5-sonnet-最智能(每1K 0.003美元/0.015美元)claude-3-5-haiku-最快(每1K 0.001美元/0.005美元)claude-3-opus-最强大(每1K 0.015美元/0.075美元)claude-3-sonnet-平衡(每1K 0.003美元/0.015美元)claude-3-haiku-高效(每1K 0.00025美元/0.00125美元)
梅塔·拉玛
llama-3-3-70b-最新70B型号(0.00065美元/1K 0.00065美元)llama-3-2-90b-有远见的多式联运(0.0008美元/1K 0.0008美元)llama-3-2-11b-小型多式联运(0.00016美元/1K 0.00016美元)llama-3-1-70b-70B参数(0.00099美元/1K 0.00099美元)llama-3-1-8b-小巧高效(0.00022美元/1K 0.00022美元)
米斯特拉尔
mistral-large-2-旗舰级高级推理(每1K 0.003美元/0.009美元)mistral-small-快速经济(每1K 0.001美元/0.003美元)
查看完整列表: await mcp.call_tool("list_models", {})
🔌 从代理连接
关键概念
每个代理在代码中指定其模型,不在配置中。网关是所有基岩模型的单一入口点。
MCP配置(适用于所有代理)
{
"mcpServers": {
"llm-gateway": {
"command": "python",
"args": ["-m", "src.server"],
"env": {
"AWS_REGION": "us-east-1",
"AWS_ACCESS_KEY_ID": "your-key",
"AWS_SECRET_ACCESS_KEY": "your-secret"
}
}
}
}代理A-使用Nova Pro
# This agent always uses nova-pro
response = await session.call_tool(
"generate",
{
"model": "nova-pro", # str:
async with stdio_client("python", ["-m", "src.server"]) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
response = await session.call_tool(
"generate",
{
"model": self.model,
"messages": [{"role": "user", "content": prompt}]
}
)
return response["content"]
# Use in chain
llm = BedrockMCPLLM(model="claude-3-5-sonnet")
result = await llm.ainvoke("Explain quantum computing")来自LlamaIndex:
from llama_index.llms.base import LLM
from mcp import ClientSession
class BedrockMCPLLM(LLM):
def __init__(self, model: str = "nova-pro"):
self.model = model
async def acomplete(self, prompt: str) -> str:
async with stdio_client("python", ["-m", "src.server"]) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
response = await session.call_tool(
"generate",
{
"model": self.model,
"messages": [{"role": "user", "content": prompt}]
}
)
return response["content"]
# Use in index
llm = BedrockMCPLLM(model="llama-3-3-70b")
response = await llm.acomplete("Summarize this document")监控与调试
启用详细日志记录:
export LOG_LEVEL=DEBUG
python -m src.server检查网关运行状况:
stats = await session.call_tool("get_stats", {})
print(f"Total requests: {stats['metrics']['total_requests']}")
print(f"Cache hit rate: {stats['metrics']['cache_hit_rate_percent']}%")
print(f"Total cost: ${stats['metrics']['total_cost_usd']:.2f}")监控特定型号的使用情况:
stats = await session.call_tool("get_stats", {})
for model, count in stats['metrics']['requests_by_model'].items():
print(f"{model}: {count} requests")🔒 安全最佳实践
- 从不提交AWS凭据 -使用环境变量或AWS IAM角色
- 使用IAM角色 部署到AWS(EC2、ECS、Lambda)时
- 轮换凭据 定期
- 限制基岩许可 仅适用于所需型号
- 使用VPC端点 用于生产中的基岩
- 启用CloudTrail 用于审计日志记录
IAM策略示例(最小权限)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel"
],
"Resource": [
"arn:aws:bedrock:*::foundation-model/amazon.nova-*",
"arn:aws:bedrock:*::foundation-model/anthropic.claude-*",
"arn:aws:bedrock:*::foundation-model/meta.llama-*",
"arn:aws:bedrock:*::foundation-model/mistral.*"
]
}
]
}🚀 生产部署
AWS ECS(推荐)
# 1. Push image to ECR
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin .dkr.ecr.us-east-1.amazonaws.com
docker tag bedrock-gateway:latest .dkr.ecr.us-east-1.amazonaws.com/bedrock-gateway:latest
docker push .dkr.ecr.us-east-1.amazonaws.com/bedrock-gateway:latest
# 2. Create ECS task definition with IAM role
# 3. Deploy to ECS FargateKubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
name: bedrock-gateway
spec:
replicas: 3
selector:
matchLabels:
app: bedrock-gateway
template:
metadata:
labels:
app: bedrock-gateway
spec:
containers:
- name: gateway
image: bedrock-gateway:latest
env:
- name: AWS_REGION
value: "us-east-1"
- name: CACHE_ENABLED
value: "true"
resources:
requests:
memory: "256Mi"
cpu: "500m"
limits:
memory: "512Mi"
cpu: "1000m"📊 性能基准
上的典型延迟 t3.medium 例子
| 模型 | 第一个请求 | 缓存请求 | 平均令牌/秒 |
|---|---|---|---|
| 新星微 | 800ms | 5ms | 120 |
| 新星光 | 1200毫秒 | 5毫秒 | 100 |
| 新星专业 | 2000ms | 5ms | 80 |
| claude-3-5-haiku | 900毫秒 | 5毫秒 | 110 |
| claude-3-5连接器 | 1500毫秒 | 5毫秒 | 90 |
| 美洲驼3-1-8b | 700毫秒 | 5毫秒 | 130 |
| 骆驼-3-3-70b | 1800毫秒 | 5毫秒 | 85 |
*注意:延迟因网络、地区和提示复杂性而异*
🤝 贡献
欢迎投稿!拜托:
- 分叉存储库
- 创建要素分支(
git checkout -b feature/amazing-feature) - 提交您的更改(
git commit -m 'Add amazing feature') - 推到分支(
git push origin feature/amazing-feature) - 打开拉取请求
📄 许可证
该项目是为PUCP的仪器课程开发的。
👥 作者
由Leon Achata开发,作为IoT Holter项目的一部分-PUCP 2025
🔗 参考文献
______________________________________________________________________
需要帮助? 在GitHub上打开问题或联系开发团队。
