使用说明
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.txt
2.配置环境变量
创建 .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=INFO
3.运行服务器
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", # <-- Model hardcoded in agent
"messages": [{"role": "user", "content": "Complex task..."}],
"temperature": 0.7,
"max_tokens": 2000
}
)
代理人B-使用克劳德3.5十四行诗
# This agent always uses claude-3-5-sonnet
response = await session.call_tool(
"generate",
{
"model": "claude-3-5-sonnet", # <-- Different model
"messages": [{"role": "user", "content": "Deep analysis..."}]
}
)
代理C-使用Llama 3.3 70B
# This agent always uses llama-3-3-70b
response = await session.call_tool(
"generate",
{
"model": "llama-3-3-70b", # <-- Another model
"messages": [{"role": "user", "content": "General task..."}]
}
)
来自代理的完整示例(Python)
from mcp import ClientSession
from mcp.client.stdio import stdio_client
async def use_llm_gateway():
# Connect to gateway
async with stdio_client("python", ["-m", "src.server"]) as (read, write):
async with ClientSession(read, write) as session:
# Initialize
await session.initialize()
# List available models
models = await session.call_tool("list_models", {})
print(f"Available: {len(models)} models")
# Generate completion with agent's specific model
response = await session.call_tool(
"generate",
{
"model": "nova-pro", # <-- Agent chooses its model
"messages": [
{"role": "user", "content": "What is AI?"}
],
"temperature": 0.7,
"max_tokens": 500
}
)
print(f"Response: {response['content']}")
print(f"Tokens: {response['usage']['total_tokens']}")
print(f"Cost: ${response['estimated_cost_usd']:.6f}")
print(f"Cached: {response['cached']}")
print(f"Latency: {response['latency_ms']:.2f}ms")
🛠️ 可用的MCP工具
1. generate
使用任何基岩模型生成完井。
参数:
model(str):短型号名称(例如,“nova pro”、“claude-3-5-sonnet”、“llama-3-3-70b”)messages(list):包含“角色”和“内容”的邮件列表temperature(浮子):取样温度(0.0-2.0)max_tokens(int):要生成的最大令牌数
退货:
{
"content": "Generated response...",
"model": "nova-pro",
"model_id": "us.amazon.nova-pro-v1:0",
"usage": {
"input_tokens": 10,
"output_tokens": 50,
"total_tokens": 60
},
"finish_reason": "stop",
"cached": false,
"latency_ms": 1234.56,
"estimated_cost_usd": 0.001234
}
2. list_models
列出所有可用的基岩型号及其定价。
退货:
[
{
"name": "nova-pro",
"model_id": "us.amazon.nova-pro-v1:0",
"description": "Advanced multimodal AI model with superior reasoning",
"context_window": 300000,
"input_cost_per_1k": 0.0008,
"output_cost_per_1k": 0.0032,
"supports_system": true,
"max_tokens": 5000
},
...
]
3. get_stats
检索网关统计信息(指标和缓存)。
退货:
{
"metrics": {
"total_requests": 100,
"total_tokens": 50000,
"total_cost_usd": 1.23,
"cache_hit_rate_percent": 45.5,
"average_latency_ms": 1234.5,
"requests_by_model": {
"nova-pro": 50,
"claude-3-5-sonnet": 30,
"llama-3-3-70b": 20
}
},
"cache": {
"current_size": 50,
"max_size": 1000,
"enabled": true
}
}
📊 特性
✅ 实现
- ✅ 具有标准协议的FastMCP服务器
- ✅ 15+基岩模型 (诺瓦,克劳德,火焰,米斯特拉尔)
- ✅ 通用基岩客户端 -所有型号的单一客户端
- ✅ 每个代理选择其模型 -在代理代码中硬编码
- ✅ 带TTL的缓存系统
- ✅ 每个模型的详细指标(请求、令牌、成本、延迟)
- ✅ 集中验证
- ✅ 结构化日志记录
- ✅ 具有实际定价的自动成本估算
🔮 未来
- 🔜 每个代理的费率限制
- 🔜 度量持久性(数据库)
- 🔜 Web监控仪表板
- 🔜 响应流
- 🔜 支持图像模型(多模式)
📝 环境变量
| 变量 | 描述 | 默认值 |
|---|---|---|
AWS_ACCESS_KEY_ID |
AWS访问密钥 | - |
AWS_SECRET_ACCESS_KEY |
AWS密钥 | - |
AWS_REGION |
AWS区域 | 美国东部-1 |
CACHE_ENABLED |
启用缓存 | true |
CACHE_TTL |
缓存TTL(秒) | 3600 |
CACHE_MAX_SIZE |
最大缓存大小 | 1000 |
METRICS_ENABLED |
启用指标 | true |
LOG_LEVEL |
日志记录级别 | 信息 |
❓ 常见问题解答
为什么只有Bedrock而不是其他供应商?
此网关针对以下方面进行了优化 企业环境 Bedrock提供:
- 单一基础设施下的15+个模型
- 企业安全和合规性
- 无每用户费率限制(每个AWS帐户的限额)
- 可预测的定价,没有隐藏费用
每个代理如何决定使用哪种模型?
型号已指定 在代理代码中,不在配置中:
# Agent A
response = await mcp.call_tool("generate", {"model": "nova-pro", ...})
# Agent B
response = await mcp.call_tool("generate", {"model": "claude-3-5-sonnet", ...})
# Agent C
response = await mcp.call_tool("generate", {"model": "llama-3-3-70b", ...})
我可以将多个代理连接到同一网关吗?
是,这是主要用例。所有代理都连接到同一个MCP网关,但每个代理都指定了其首选模型。网关:
- 缓存代理之间共享的响应
- 跟踪每个模型的指标
- 通过智能缓存优化成本
如何添加新的基岩模型?
编辑 src/models/bedrock_models.py 并将模型添加到 BEDROCK_MODELS 字典。例子:
"my-model": BedrockModel(
model_id="aws.my-model-v1:0",
name="My New Model",
description="Description",
context_window=128000,
input_cost_per_1k=0.001,
output_cost_per_1k=0.002,
supports_system=True,
max_tokens=4096
)
🐳 Docker部署
本地快速入门
# 1. Configure environment variables
cp .env.example .env
# Edit .env with your AWS credentials
# 2. Build and run with Docker Compose
docker-compose up -d
# 3. View logs
docker-compose logs -f
手动构建
# Build the image
docker build -t bedrock-gateway:latest .
# Run with environment variables
docker run -d \
-e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
-e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
-e AWS_REGION=us-east-1 \
-e CACHE_ENABLED=true \
bedrock-gateway:latest
Docker功能
- ✅ 多阶段构建(优化图像~150MB)
- ✅ 非root用户(安全)
- ✅ 日志的持久卷
- ✅ 可配置的健康检查
- ✅ 资源限制(CPU/内存)
- ✅ 兼容Docker Compose和Kubernetes
🎯 LangGraph代理集成
快速开始
这 ForAgents/ 文件夹包含所需的所有内容:
# 1. Install agent dependencies
cd ForAgents
pip install -r requirements.txt
# 2. Use the LLM node in your graph
from llm_node import AgentState, llm_consultation_node
from langgraph.graph import StateGraph, END
workflow = StateGraph(AgentState)
workflow.add_node("llm", llm_consultation_node)
workflow.set_entry_point("llm")
workflow.add_edge("llm", END)
app = workflow.compile()
# 3. Execute
result = await app.ainvoke({
"messages": [{"role": "user", "content": "Hello"}],
"model": "nova-pro"
})
print(result["response"])
📖 其他文件
连接示例
来自LangChain:
from langchain.llms.base import LLM
from mcp import ClientSession
class BedrockMCPLLM(LLM):
model: str = "nova-pro"
async def _acall(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 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 <account>.dkr.ecr.us-east-1.amazonaws.com
docker tag bedrock-gateway:latest <account>.dkr.ecr.us-east-1.amazonaws.com/bedrock-gateway:latest
docker push <account>.dkr.ecr.us-east-1.amazonaws.com/bedrock-gateway:latest
# 2. Create ECS task definition with IAM role
# 3. Deploy to ECS Fargate
Kubernetes
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上打开问题或联系开发团队。
