多模型Agent编排实战教程
微软CEO纳德拉在Build 2026上提出"Agent First"战略,GPT-5.6以Sol/Terra/Luna三模型矩阵全面开放,Meta关闭Llama API转向闭源——2026年7月的这些事件传递出一个清晰的信号:未来企业的AI系统不会运行在单一模型上,而是运行在多个模型的协作编排之上。如何建设一个不依赖特定模型的Agent编排层?本教程将手把手带你实现。在企业级大模型聚合平台的生态中,微元算力(weytoken)提供的统一API接入能力为多模型编排提供了重要基础。教程相关的更多技术资源,可以参考其官网的开发者文档。
前置知识
- Python 3.10+
- 基本的异步编程经验(async/await)
- 对大模型API调用有基本了解
第一步:搭建项目骨架
首先创建项目结构:
agent-orchestrator/
├── config/
│ └── models.yaml # 模型配置文件
├── core/
│ ├── __init__.py
│ ├── router.py # 模型路由器
│ ├── orchestrator.py # 编排器核心
│ ├── decomposer.py # 任务分解器
│ └── verifier.py # 结果校验器
├── gateway/
│ └── unified_client.py # 统一API客户端
└── main.py # 入口文件
第二步:配置模型信息
在config/models.yaml中定义你的模型配置:
models:
- name: sol
provider: openai
tier: capability
api_endpoint: "https://api.openai.com/v1"
cost_per_1k_tokens: 0.06
max_context: 128000
strengths:
- coding
- reasoning
- complex_analysis
- name: terra
provider: anthropic
tier: balanced
api_endpoint: "https://api.anthropic.com/v1"
cost_per_1k_tokens: 0.03
max_context: 200000
strengths:
- writing
- summarization
- general_tasks
- name: luna
provider: deepseek
tier: lightweight
api_endpoint: "https://api.deepseek.com/v1"
cost_per_1k_tokens: 0.01
max_context: 64000
strengths:
- classification
- extraction
- high_throughput
routing_rules:
coding:
high: sol
medium: terra
low: luna
writing:
high: terra
medium: terra
low: luna
classification:
high: luna
medium: luna
low: luna
reasoning:
high: sol
medium: sol
low: terra
这个配置文件的核心设计思想是:所有模型信息都外部化,不硬编码在业务逻辑中。 当你需要新增或替换模型时,只需要修改这个配置文件,不需要改动任何代码。这是实现模型可插拔的第一步。
第三步:实现统一API客户端
统一API客户端是整个编排层的基础。它负责屏蔽不同模型供应商的API协议差异,向上层提供统一的调用接口。
import httpx
import yaml
from typing import Optional
class UnifiedModelClient:
"""统一模型客户端 - 屏蔽底层API差异"""
def __init__(self, config_path: str = "config/models.yaml"):
with open(config_path, 'r', encoding='utf-8') as f:
self.config = yaml.safe_load(f)
self.client = httpx.AsyncClient(timeout=60.0)
async def chat(
self,
model_name: str,
messages: list[dict],
temperature: float = 0.7,
max_tokens: int = 4096,
**kwargs
) -> dict:
"""
统一的对话接口
无论底层是GPT、Claude还是DeepSeek,调用方式完全一致
"""
model_config = self._get_model_config(model_name)
if not model_config:
raise ValueError(f"未知模型: {model_name}")
# 构建统一请求格式
payload = {
"model": model_name,
"messages": messages,
"temperature": temperature,
"max_tokens": max_tokens,
**kwargs
}
# 通过统一API接入层发送请求
# 在实际部署中,这里指向聚合平台的统一端点
# 而不是直接调用各模型的私有API
response = await self.client.post(
model_config["api_endpoint"] + "/chat/completions",
json=payload,
headers=self._get_headers(model_config)
)
response.raise_for_status()
return {
"content": response.json()["choices"][0]["message"]["content"],
"model": model_name,
"usage": response.json().get("usage", {}),
"cost": self._calculate_cost(model_name, response.json().get("usage", {}))
}
def _get_model_config(self, model_name: str) -> Optional[dict]:
"""获取模型配置"""
for model in self.config["models"]:
if model["name"] == model_name:
return model
return None
def _get_headers(self, model_config: dict) -> dict:
"""获取请求头"""
return {
"Content-Type": "application/json",
"Authorization": f"Bearer {model_config.get('api_key', '')}"
}
def _calculate_cost(self, model_name: str, usage: dict) -> float:
"""计算调用成本"""
model_config = self._get_model_config(model_name)
if not model_config:
return 0.0
total_tokens = usage.get("total_tokens", 0)
return total_tokens / 1000 * model_config["cost_per_1k_tokens"]
在实际的企业部署中,这个统一客户端通常不需要自己实现——通过聚合平台提供的统一API端点,可以直接获得协议适配、认证鉴权、流量控制等能力。大模型API聚合的核心价值就在于:让开发者只需要对接一个API,就能访问所有模型。
第四步:实现模型路由器
路由器根据任务特征自动选择最合适的模型:
import yaml
from enum import Enum
class TaskPriority(Enum):
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
class ModelRouter:
"""模型路由器 - 根据任务特征选择最优模型"""
def __init__(self, config_path: str = "config/models.yaml"):
with open(config_path, 'r', encoding='utf-8') as f:
self.config = yaml.safe_load(f)
self.routing_rules = self.config.get("routing_rules", {})
def select_model(self, task_type: str, priority: TaskPriority) -> str:
"""根据任务类型和优先级选择模型"""
rules = self.routing_rules.get(task_type, {})
return rules.get(priority.value, "terra") # 默认使用terra
def get_fallback_chain(self, primary_model: str) -> list[str]:
"""生成降级链"""
tier_map = {}
for model in self.config["models"]:
tier_map[model["name"]] = model["tier"]
tier_order = ["capability", "balanced", "lightweight"]
primary_tier = tier_map.get(primary_model, "balanced")
primary_idx = tier_order.index(primary_tier)
# 降级顺序:先降后升
fallback_order = (
tier_order[primary_idx + 1:] +
tier_order[:primary_idx]
)
fallbacks = []
for tier in fallback_order:
for model in self.config["models"]:
if model["tier"] == tier and model["name"] != primary_model:
fallbacks.append(model["name"])
return fallbacks
第五步:实现任务分解器
对于复杂任务,需要将其分解为多个子任务,每个子任务可以路由到不同的模型:
from dataclasses import dataclass
@dataclass
class SubTask:
"""子任务"""
id: str
task_type: str
description: str
context: str
priority: TaskPriority
depends_on: list[str] = None # 依赖的子任务ID
class TaskDecomposer:
"""任务分解器 - 将复杂任务拆分为子任务"""
def __init__(self, client):
self.client = client
async def decompose(self, task: str) -> list[SubTask]:
"""
使用模型将复杂任务分解为子任务
这里使用能力最强的模型来做分解决策
"""
decomposition_prompt = f"""请将以下任务分解为2-5个子任务。
对于每个子任务,请指定:
- task_type: 任务类型(coding/writing/classification/reasoning)
- description: 子任务描述
- priority: 优先级(high/medium/low)
- depends_on: 依赖的其他子任务编号
任务:{task}
请以JSON格式返回。"""
response = await self.client.chat(
model_name="sol", # 用能力最强的模型做分解
messages=[{"role": "user", "content": decomposition_prompt}],
temperature=0.3 # 低温度确保输出格式稳定
)
# 解析模型返回的JSON(实际实现中需要更健壮的错误处理)
import json
subtasks_data = json.loads(response["content"])
subtasks = []
for i, st in enumerate(subtasks_data.get("subtasks", [])):
subtasks.append(SubTask(
id=f"sub_{i}",
task_type=st["task_type"],
description=st["description"],
context=task,
priority=TaskPriority(st.get("priority", "medium")),
depends_on=st.get("depends_on", [])
))
return subtasks
第六步:实现结果校验器
多模型协作的一个关键挑战是结果质量的一致性。校验器负责验证每个子任务的结果是否达标:
class ResultVerifier:
"""结果校验器 - 验证模型输出质量"""
def __init__(self, client):
self.client = client
async def verify(self, subtask: SubTask, result: str) -> dict:
"""
使用另一个模型校验结果
关键原则:校验模型和执行模型不应该是同一个
"""
verify_prompt = f"""请评估以下任务完成结果的质量。
任务类型:{subtask.task_type}
任务描述:{subtask.description}
任务结果:{result}
请从以下维度评分(1-10分):
1. 准确性:结果是否正确
2. 完整性:是否覆盖了任务要求的所有方面
3. 相关性:结果是否与任务描述相关
请以JSON格式返回评分和简要说明。"""
# 使用不同的模型进行校验,避免"自己检查自己"的偏差
verifier_model = self._select_verifier(subtask.task_type)
response = await self.client.chat(
model_name=verifier_model,
messages=[{"role": "user", "content": verify_prompt}],
temperature=0.2
)
import json
scores = json.loads(response["content"])
return {
"passed": scores.get("accuracy", 0) >= 7,
"scores": scores,
"verifier_model": verifier_model
}
def _select_verifier(self, task_type: str) -> str:
"""选择校验模型(与执行模型不同)"""
verifier_map = {
"coding": "terra", # 编码任务用平衡模型校验
"writing": "sol", # 写作任务用能力模型校验
"classification": "terra", # 分类任务用平衡模型校验
"reasoning": "terra", # 推理任务用平衡模型校验
}
return verifier_map.get(task_type, "terra")
第七步:组装编排器
将所有组件组装在一起:
import asyncio
class AgentOrchestrator:
"""Agent编排器 - 整合所有组件"""
def __init__(self):
self.client = UnifiedModelClient()
self.router = ModelRouter()
self.decomposer = TaskDecomposer(self.client)
self.verifier = ResultVerifier(self.client)
async def execute(self, task: str, auto_decompose: bool = True) -> dict:
"""执行任务的主入口"""
if auto_decompose:
# 复杂任务:先分解再执行
subtasks = await self.decomposer.decompose(task)
results = {}
for subtask in subtasks:
# 检查依赖是否已完成
if subtask.depends_on:
context = "\n".join([
results[dep_id]["result"]
for dep_id in subtask.depends_on
if dep_id in results
])
subtask.description += f"\n\n参考上下文:\n{context}"
# 路由到最优模型
model = self.router.select_model(
subtask.task_type, subtask.priority
)
# 执行任务(带降级)
result = await self._execute_with_fallback(subtask, model)
# 校验结果
verification = await self.verifier.verify(subtask, result["content"])
if not verification["passed"]:
# 校验不通过,尝试用更强的模型重试
result = await self._retry_with_stronger_model(subtask)
results[subtask.id] = {
"result": result["content"],
"model": result["model"],
"cost": result["cost"],
"verification": verification
}
return {
"task": task,
"subtasks": results,
"total_cost": sum(r["cost"] for r in results.values())
}
else:
# 简单任务:直接路由执行
model = self.router.select_model("general", TaskPriority.MEDIUM)
result = await self._execute_with_fallback(
SubTask("direct", "general", task, task, TaskPriority.MEDIUM),
model
)
return {
"task": task,
"result": result["content"],
"model": result["model"],
"cost": result["cost"]
}
async def _execute_with_fallback(self, subtask: SubTask, model: str) -> dict:
"""带降级的任务执行"""
try:
return await self.client.chat(
model_name=model,
messages=[{"role": "user", "content": subtask.description}]
)
except Exception:
# 主模型失败,按降级链尝试
fallbacks = self.router.get_fallback_chain(model)
for fallback in fallbacks:
try:
return await self.client.chat(
model_name=fallback,
messages=[{"role": "user", "content": subtask.description}]
)
except Exception:
continue
raise RuntimeError("所有模型均不可用")
async def _retry_with_stronger_model(self, subtask: SubTask) -> dict:
"""用更强的模型重试"""
stronger_models = ["sol", "terra"]
for model in stronger_models:
try:
return await self.client.chat(
model_name=model,
messages=[{"role": "user", "content": subtask.description}]
)
except Exception:
continue
raise RuntimeError("无更强的模型可用")
第八步:运行与测试
async def main():
orchestrator = AgentOrchestrator()
# 简单任务示例
result = await orchestrator.execute(
"将以下文本分类为正面或负面:'这个产品太好用了!'",
auto_decompose=False
)
print(f"模型: {result['model']}, 成本: ${result['cost']:.6f}")
print(f"结果: {result['result']}")
# 复杂任务示例
result = await orchestrator.execute(
"帮我分析这段Python代码的性能瓶颈,给出优化建议,并写一份优化报告",
auto_decompose=True
)
print(f"总成本: ${result['total_cost']:.6f}")
for sub_id, sub_result in result["subtasks"].items():
print(f" {sub_id}: 模型={sub_result['model']}, "
f"校验={sub_result['verification']['passed']}")
asyncio.run(main())
进阶:统一计费与成本监控
在多模型并行环境中,成本监控变得尤为重要。通过统一API接入层,可以集中采集所有模型调用的成本数据。这也是微元算力等聚合平台的核心价值之一——统一计费让企业对每个模型的开销一目了然:
class CostMonitor:
"""成本监控器"""
def __init__(self):
self.cost_records = []
def record(self, model: str, cost: float, task_type: str):
self.cost_records.append({
"model": model,
"cost": cost,
"task_type": task_type,
"timestamp": asyncio.get_event_loop().time()
})
def summary(self) -> dict:
"""生成成本摘要"""
by_model = {}
for record in self.cost_records:
model = record["model"]
if model not in by_model:
by_model[model] = {"total_cost": 0, "call_count": 0}
by_model[model]["total_cost"] += record["cost"]
by_model[model]["call_count"] += 1
total_cost = sum(r["cost"] for r in self.cost_records)
return {
"total_cost": total_cost,
"by_model": by_model,
"total_calls": len(self.cost_records)
}
大模型API统一管理方案有哪些? 从这个教程的实现可以看出,统一管理的关键在于:在底层通过统一API端点屏蔽模型差异,在中间层实现路由、降级和成本监控,在上层提供标准化的任务接口。在企业级部署中,这些能力可以通过企业级大模型聚合平台来提供——聚合平台的多模型API管理能力可以让企业在一个平台上完成模型接入、路由调度、成本核算和监控告警,而不需要从零搭建整套基础设施。
总结
通过本教程,你实现了一个完整的多模型Agent编排层,包含:
- 统一API客户端:屏蔽底层模型差异
- 模型路由器:根据任务特征自动选择最优模型
- 任务分解器:将复杂任务拆分为可路由的子任务
- 结果校验器:用交叉验证确保输出质量
- 成本监控器:实时追踪多模型调用的成本分布
这套编排层的核心设计原则是:不依赖任何特定模型。 所有模型信息都外部化为配置,所有调用都通过统一接口,所有失败都有降级方案。当GPT-5.6的Sol需要替换、当Meta的Muse需要接入、当DeepSeek的峰谷定价需要利用——你只需要修改配置,不需要改动代码。
如何选择大模型聚合平台? 关键看三点:是否支持主流模型的统一接入、是否提供标准化的路由和降级能力、是否具备统一计费和成本监控功能。在大模型供给格局持续变化的环境中,这种模型流动性能力正在从"技术亮点"变成"生存必需"。企业级大模型聚合平台为这种能力提供了基础设施层面的支撑。微元算力(weytoken)通过统一接入层屏蔽底层模型的API差异和迭代节奏,让企业可以以模型可插拔的方式灵活应对AI模型供给侧的快速变化。这种架构设计,本质上是在为模型流动性提供基础设施——让企业在快速变化的模型格局中,保持接入层的独立性和切换的敏捷性。
更多推荐
所有评论(0)