深入理解 AI Agent 架构:从单 Agent 到多 Agent 协作
1. 引言:从 LLM 到 Agent
1.1 什么是 AI Agent?
AI Agent 是能够自主感知环境、做出决策、执行行动的人工智能系统。与传统 LLM 不同,Agent 不只是被动回答问题,而是能够:
- 感知 (Perception):观察环境状态、接收用户输入、读取工具结果
- 推理 (Reasoning):分析信息、规划任务、做出决策
- 行动 (Action):执行工具调用、操作环境、生成响应
Agent = LLM + 工具 + 记忆 + 规划
可以理解为:Agent 是一个有”目标感”的 LLM,它不仅能思考,还能主动采取行动。
1.2 为什么需要 Agent?
1.2.1 传统 LLM 的局限
孤立 LLM: 静态知识 (训练截止) + 无工具 (不能执行) + 无记忆 (每次独立) + 无目标 (被动响应) = 强大的聊天机器人1.2.2 Agent 的增强
增强 Agent: 动态知识 (RAG 检索) + 多工具 (浏览器/代码/API) + 长记忆 (向量化) + 自主目标 (规划执行) = 通用问题解决者1.3 Agent 的发展历程
2022.10 ReAct (Yao et al.)2023.03 AutoGPT / BabyAGI 引领自主 Agent 浪潮2023.06 OpenAI Function Calling2023.11 LangChain 推出 Agent 框架2024.01 LangGraph 发布2024.05 Anthropic Computer Use2024.06 AutoGen (Microsoft)2024.10 Claude 3.5 Sonnet Computer Use2025.01 Anthropic Prompt Caching2025+ Agent as a Service (Agent 服务化)1.4 应用场景
| 场景 | Agent 任务 |
|---|---|
| 软件开发 | 代码生成、Bug 修复、PR Review |
| 研究分析 | 信息检索、数据分析、报告撰写 |
| 客户支持 | 自动问答、工单处理、问题升级 |
| 数据分析 | 查询生成、可视化、洞察发现 |
| 工作流自动化 | 多步骤任务、跨系统协调 |
2. Agent 核心架构
2.1 Agent 三要素
经典的 Agent 架构包含三个核心组件:
┌─────────────────────────────────────┐ │ AI Agent │ │ │ │ ┌────────────┐ ┌────────────┐ │ │ │ Perception │ │ Memory │ │ │ └─────┬──────┘ └─────▲──────┘ │ │ │ │ │ │ ▼ │ │ │ ┌─────────────────────┴────────┐ │ │ │ Reasoning │ │ │ │ (LLM + Planning) │ │ │ └──────────────┬───────────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────┐ │ │ │ Action │ │ │ └──────┬───────┘ │ └────────────────┼──────────────────┘ ▼ [Environment]2.2 Perception 模块
Perception 是 Agent 的”感官”,负责接收和处理输入:
class Perception: """Agent 感知模块""" def __init__(self): self.input_processors = []
def add_processor(self, processor): """注册输入处理器""" self.input_processors.append(processor)
def perceive(self, raw_input): """处理输入""" processed = raw_input
for processor in self.input_processors: processed = processor(processed)
return processed
# 示例: 多模态感知perception = Perception()
# 文本输入perception.add_processor(lambda x: x.strip())
# 包含图像def image_processor(input): if "<image>" in input: # 调用视觉模型描述图像 return describe_image(input) return inputperception.add_processor(image_processor)感知来源包括:
- 用户输入:文本、语音、图像
- 环境状态:数据库内容、文件系统、API 返回值
- 工具结果:搜索响应、计算结果、API 响应
- 其他 Agent:多 Agent 系统中的消息
2.3 Memory 模块
Memory 是 Agent 的”大脑”,负责存储和检索信息:
class Memory: """Agent 记忆系统""" def __init__(self): self.short_term = [] # 短期记忆 (当前任务) self.long_term = {} # 长期记忆 (向量化) self.episodic = [] # 情节记忆 (历史行动) self.semantic = {} # 语义记忆 (事实知识)
def store(self, content, memory_type='short_term'): """存储记忆""" if memory_type == 'short_term': self.short_term.append(content) elif memory_type == 'long_term': vector = self.embed(content) self.long_term[vector] = content # ...
def retrieve(self, query, top_k=5): """检索相关记忆""" # 使用 embedding 相似度 query_vector = self.embed(query) relevant = self.similarity_search(query_vector, top_k) return relevantMemory 的分类参见第 5 节。
2.4 Reasoning 模块
Reasoning 是 Agent 的”思维”,负责规划和决策:
class Reasoning: """Agent 推理模块""" def __init__(self, llm): self.llm = llm self.planner = Planner(llm) self.reflector = Reflector(llm)
def reason(self, state, goal): """推理下一步行动""" # 1. 规划:分解目标 plan = self.planner.create_plan(state, goal)
# 2. 执行当前步骤 step = plan.current_step()
# 3. 反思:如果失败,调整 if self._is_stuck(state): plan = self.reflector.reflect(state, plan) step = plan.current_step()
return step
class Planner: """规划器""" def create_plan(self, state, goal): prompt = f""" 目标: {goal} 当前状态: {state}
请创建一个详细的执行计划: 1. [步骤1] 2. [步骤2] ... """ plan_text = self.llm.generate(prompt) return self._parse_plan(plan_text)2.5 Action 模块
Action 是 Agent 的”手脚”,负责执行决策:
class Action: """Agent 行动模块""" def __init__(self, tools): self.tools = tools # 可用工具集合
def execute(self, action): """执行行动""" tool_name = action.tool args = action.arguments
tool = self.tools.get(tool_name) if not tool: raise ToolNotFound(tool_name)
result = tool.execute(**args) return result
class Tool: """工具""" def __init__(self, name, func, schema): self.name = name self.func = func self.schema = schema
def execute(self, **kwargs): try: result = self.func(**kwargs) return ActionResult(success=True, data=result) except Exception as e: return ActionResult(success=False, error=str(e))3. Agent 设计模式
3.1 模式 1: ReAct
ReAct (Reasoning + Acting) 是最经典的 Agent 模式,由 Yao et al. (2022) 提出:
循环: Thought → Action → Observation → Thought → ...class ReActAgent: """ReAct Agent""" def __init__(self, llm, tools, max_steps=10): self.llm = llm self.tools = tools self.max_steps = max_steps
def run(self, question): history = []
for step in range(self.max_steps): # 1. Thought + Action prompt = self._build_prompt(question, history) response = self.llm.generate(prompt)
thought, action = self._parse_response(response)
# 2. 完成检测 if self._is_final_answer(response): return self._extract_answer(response)
# 3. 执行 Action observation = self._execute_tool(action)
# 4. 更新历史 history.append({ 'thought': thought, 'action': action, 'observation': observation })
return "达到最大步数"
# ReAct 循环示意:# Thought 1: 需要查询北京天气# Action 1: get_weather(city="北京")# Observation 1: 25°C, 晴## Thought 2: 现在查空气质量# Action 2: get_air_quality(city="北京")# Observation 2: AQI 85## Thought 3: 可以给出建议# Final Answer: 北京今天 25°C, 晴朗, 空气良好...3.2 模式 2: Plan-and-Execute
Plan-and-Execute 先完整规划,再逐步执行:
规划阶段: 一次生成完整计划执行阶段: 按计划逐步执行class PlanExecuteAgent: """Plan-and-Execute Agent"""
def run(self, question): # 1. 规划阶段 plan = self.create_plan(question)
# 2. 执行阶段 results = [] for step in plan: try: result = self.execute_step(step) results.append(result) except Exception as e: # 失败:重规划 plan = self.replan(question, plan, results, e) return self.run(question) # 重试
return self.synthesize(results)
def create_plan(self, question): """创建完整计划""" prompt = f""" 任务: {question}
请创建一个详细的执行计划。每个步骤应该明确指定: - 工具 - 参数 - 预期输出
计划: """ plan_text = self.llm.generate(prompt) return self._parse_plan(plan_text)
def replan(self, question, plan, results, error): """失败后重新规划""" prompt = f""" 原任务: {question} 原计划: {plan} 已执行: {results} 错误: {error}
请重新规划。跳过失败步骤或找到替代方案。
新计划: """ new_plan_text = self.llm.generate(prompt) return self._parse_plan(new_plan_text)优势:
- 全局可见的计划
- 执行阶段 LLM 调用少
- 适合复杂多步任务
3.3 模式 3: Reflexion
Reflexion 在 ReAct 基础上加入反思机制:
class ReflexionAgent(ReActAgent): """带反思的 Agent"""
def __init__(self, llm, tools, max_reflections=3): super().__init__(llm, tools) self.max_reflections = max_reflections self.reflections = []
def run(self, question): for attempt in range(self.max_reflections + 1): # 执行 ReAct result = super().run(question)
# 评估 if self.is_successful(result): return result
if attempt < self.max_reflections: # 反思 reflection = self.reflect(question, result) self.reflections.append(reflection)
return result
def reflect(self, question, result): """反思失败原因""" prompt = f""" 问题: {question} 尝试结果: {result}
反思以下: 1. 为什么失败? 2. 下次可以采取什么不同的策略? 3. 你学到了什么?
反思: """ return self.llm.generate(prompt)反思范式:
- 行动反思:行动后立即反思
- 失败反思:失败后反思
- 策略反思:更新整体策略
3.4 模式 4: ReWOO
ReWOO (Reasoning WithOut Observation) 通过预先生成所有任务减少冗余:
class ReWOOAgent: """ReWOO Agent - 减少观察次数"""
def run(self, question): # 1. 一次性生成所有步骤 plan = self.generate_full_plan(question)
# 2. 执行所有工具调用(无需中间反馈) evidence = {} for step in plan: result = self.execute_tool(step) evidence[step.id] = result
# 3. 综合所有证据 return self.synthesize(question, plan, evidence)
def generate_full_plan(self, question): """生成完整计划,包括变量替换""" # 计划结构: # Step 1: Search("Beijing weather") -> #E1 # Step 2: Search("Shanghai weather") -> #E2 # Step 3: LLM(#E1, #E2, "compare weathers") -> #E3 return self.llm.generate(prompt_for_plan(question))优势:
- 减少 LLM 调用次数
- 适合并行工具调用
- 降低成本
3.5 模式 5: Tree of Thoughts
Tree of Thoughts (ToT) 把推理组织成树搜索:
class ToTAgent: """Tree of Thoughts Agent"""
def __init__(self, llm, branching_factor=3, max_depth=5): self.llm = llm self.branching_factor = branching_factor self.max_depth = max_depth
def run(self, question): root = ThoughtNode(question) tree = ThoughtTree(root)
for depth in range(self.max_depth): # 1. 扩展当前层 current_nodes = tree.get_nodes_at_depth(depth) for node in current_nodes: # 生成多个候选 thoughts = self.generate_thoughts(node.state, n=self.branching_factor) for thought in thoughts: child = ThoughtNode(thought, parent=node)
# 评估 child.score = self.evaluate(thought)
tree.add(child)
# 2. 剪枝 tree.prune(keep_top_n=self.branching_factor)
return tree.get_best_path()
def generate_thoughts(self, state, n): """生成 n 个下一步思考""" prompt = f"当前: {state}\n生成 {n} 个可能的下一步思考:" response = self.llm.generate(prompt) return self._parse_thoughts(response, n)
def evaluate(self, thought): """评估思考的质量""" prompt = f"评估以下思考(1-10):{thought}" return int(self.llm.generate(prompt))3.6 模式对比
| 模式 | LLM 调用 | 适合场景 | 复杂度 |
|---|---|---|---|
| ReAct | 高 (每步) | 简单任务 | 低 |
| Plan-Execute | 低 | 复杂多步 | 中 |
| Reflexion | 中 | 反复尝试 | 中 |
| ReWOO | 很低 | 独立任务 | 低 |
| ToT | 极高 | 复杂搜索 | 高 |
4. Planning 模块深入
4.1 任务分解
class TaskDecomposer: """任务分解器"""
def decompose(self, task): """将复杂任务分解为子任务""" prompt = f""" 任务: {task}
请将这个任务分解为多个子任务。每个子任务应该: 1. 具体明确 2. 可独立执行 3. 有明确的成功标准
子任务列表(JSON 数组): """ response = self.llm.generate(prompt) return self._parse_tasks(response)
# 示例分解:# 原始任务: "研究某个 AI 主题"# 分解为:# 1. 搜索 arXiv 相关论文# 2. 阅读最重要的 3 篇# 3. 对比方法# 4. 总结发现4.2 计划表示
from dataclasses import dataclassfrom typing import List, Optional
@dataclassclass PlanStep: """计划步骤""" id: int description: str tool: Optional[str] = None # 可选的工具 args: dict = None # 工具参数 depends_on: List[int] = None # 依赖的前置步骤 status: str = "pending" # pending/running/done/failed result: any = None
@dataclassclass Plan: """完整计划""" goal: str steps: List[PlanStep]
def ready_steps(self): """获取所有可执行的步骤(依赖已满足)""" done_ids = {s.id for s in self.steps if s.status == 'done'} return [ s for s in self.steps if s.status == 'pending' and all(dep in done_ids for dep in (s.depends_on or [])) ]
def is_complete(self): return all(s.status == 'done' for s in self.steps)
def progress(self): done = sum(1 for s in self.steps if s.status == 'done') return done / len(self.steps)4.3 动态重规划
class DynamicPlanner: """动态规划器"""
def run_with_replanning(self, plan, executor): """带重规划的执行""" while not plan.is_complete(): ready = plan.ready_steps()
# 并行执行所有就绪步骤 futures = [] for step in ready: step.status = 'running' futures.append(executor.execute_async(step))
# 等待结果 for step, future in zip(ready, futures): try: result = future.result() step.status = 'done' step.result = result except Exception as e: step.status = 'failed' step.result = str(e)
# 检查是否需要重规划 failed = [s for s in plan.steps if s.status == 'failed'] if failed: plan = self.replan(plan, failed)
return plan4.4 分层规划
class HierarchicalPlanner: """分层规划器"""
def plan(self, goal): """分层规划""" # Level 1: 战略规划 strategy = self.strategic_plan(goal)
# Level 2: 战术规划 tactics = [self.tactical_plan(subgoal) for subgoal in strategy]
# Level 3: 操作规划 operations = [] for tactic in tactics: ops = self.operational_plan(tactic) operations.extend(ops)
return Plan(strategy, tactics, operations)
def strategic_plan(self, goal): """高层次规划""" prompt = f"目标: {goal}\n拆分为 3-5 个主要阶段:" return self.llm.generate(prompt)
def tactical_plan(self, subgoal): """子目标规划""" prompt = f"子目标: {subgoal}\n具体行动步骤:" return self.llm.generate(prompt)
def operational_plan(self, action): """操作级规划""" # 确定具体的工具调用 # ...5. Memory 系统设计
5.1 Memory 分类
┌─────────────────────────────────────────────────────┐│ Agent Memory │├─────────────────────────────────────────────────────┤│ ││ ┌──────────────────────────────────────────────┐ ││ │ Short-Term Memory │ ││ │ - 当前对话上下文 │ ││ │ - 最近 N 轮对话 │ ││ │ - 滑动窗口 │ ││ └──────────────────────────────────────────────┘ ││ ││ ┌──────────────────────────────────────────────┐ ││ │ Long-Term Memory (向量存储) │ ││ │ - 历史对话摘要 │ ││ │ - 用户偏好 │ ││ │ - 事实知识 │ ││ └──────────────────────────────────────────────┘ ││ ││ ┌──────────────────────────────────────────────┐ ││ │ Episodic Memory │ ││ │ - 具体的过去事件 │ ││ │ - "上次我尝试 X 然后..." │ ││ │ - 成功/失败模式 │ ││ └──────────────────────────────────────────────┘ ││ ││ ┌──────────────────────────────────────────────┐ ││ │ Semantic Memory │ ││ │ - 概念关系 │ ││ │ - 知识图谱 │ ││ │ - 领域知识 │ ││ └──────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────┘5.2 短期记忆实现
class ShortTermMemory: """短期记忆"""
def __init__(self, max_tokens=4000): self.messages = [] self.max_tokens = max_tokens
def add(self, role, content): """添加消息""" msg = {'role': role, 'content': content} self.messages.append(msg) self._truncate()
def get_messages(self): return self.messages
def _truncate(self): """超出 token 限制时截断""" while self._count_tokens() > self.max_tokens: # 保留 system prompt if len(self.messages) > 2: self.messages.pop(1) # 移除第二条 (最早用户消息)
def _count_tokens(self): return sum(len(m['content']) // 4 for m in self.messages)5.3 长期记忆实现
import numpy as npfrom typing import List, Tuple
class LongTermMemory: """长期记忆 - 向量存储"""
def __init__(self, embedder, vector_store): self.embedder = embedder # embedding 模型 self.vector_store = vector_store # 向量数据库
def store(self, content, metadata=None): """存储记忆""" embedding = self.embedder.embed(content) self.vector_store.add( vector=embedding, content=content, metadata=metadata or {} )
def retrieve(self, query, top_k=5): """检索相关记忆""" query_embedding = self.embedder.embed(query) results = self.vector_store.search( vector=query_embedding, top_k=top_k ) return results
def retrieve_relevant_for_context(self, query): """检索并格式化为上下文""" results = self.retrieve(query) context = "\n".join([ f"[{i}] {r['content']}" for i, r in enumerate(results) ]) return context5.4 记忆压缩
class MemoryCompressor: """记忆压缩器"""
def __init__(self, llm): self.llm = llm
def summarize_conversation(self, messages): """总结对话""" conversation = "\n".join([ f"{m['role']}: {m['content']}" for m in messages ])
prompt = f""" 请总结以下对话的关键信息: {conversation}
总结应包含: 1. 用户的主要需求 2. 已完成的工作 3. 重要的决定或发现 4. 待解决的问题
总结: """ return self.llm.generate(prompt)
def compress_old_memories(self, memories): """压缩旧记忆""" # 相似记忆去重 unique = self._deduplicate(memories)
# 过长记忆总结 compressed = [] for memory in unique: if len(memory) > 500: summarized = self.summarize_conversation([{'content': memory}]) compressed.append(summarized) else: compressed.append(memory)
return compressed5.5 Memory-Augmented Agent
class MemoryAugmentedAgent: """带记忆的 Agent"""
def __init__(self, llm, tools, memory): self.llm = llm self.tools = tools self.memory = memory
def run(self, user_input): # 1. 检索相关记忆 relevant_memories = self.memory.retrieve_relevant_for_context(user_input)
# 2. 增强 prompt augmented_prompt = f""" 相关历史: {relevant_memories}
当前请求: {user_input} """
# 3. 生成响应(可调用工具) response = self._generate(augmented_prompt)
# 4. 存储到记忆 self.memory.store( f"用户: {user_input}\n助手: {response}" )
return response6. Tool Use
6.1 Tool 抽象层
from typing import Callable, Dict, Any, Listfrom dataclasses import dataclassimport json
@dataclassclass Tool: """工具""" name: str description: str func: Callable schema: Dict[str, Any]
def execute(self, **kwargs) -> str: try: result = self.func(**kwargs) return json.dumps({"success": True, "data": result}) except Exception as e: return json.dumps({"success": False, "error": str(e)})
def to_openai_format(self) -> Dict: return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.schema } }
class ToolRegistry: """工具注册表"""
def __init__(self): self.tools: Dict[str, Tool] = {}
def register(self, name=None, description=None): def decorator(func): tool_name = name or func.__name__ tool_desc = description or (func.__doc__ or "") schema = self._infer_schema(func) tool = Tool(tool_name, tool_desc, func, schema) self.tools[tool_name] = tool return func return decorator
def _infer_schema(self, func): import inspect sig = inspect.signature(func) properties = {} required = []
for name, param in sig.parameters.items(): properties[name] = {"type": "string"} if param.default is param.empty: required.append(name)
return { "type": "object", "properties": properties, "required": required }
def get(self, name: str) -> Tool: return self.tools.get(name)
def to_openai_tools(self) -> List[Dict]: return [t.to_openai_format() for t in self.tools.values()]6.2 Tool Selection
class ToolSelector: """智能工具选择器"""
def __init__(self, all_tools, embedding_model): self.all_tools = all_tools self.embedding_model = embedding_model self.tool_embeddings = self._embed_tools()
def _embed_tools(self): embeddings = {} for tool in self.all_tools: tool_text = f"{tool.name}: {tool.description}" embeddings[tool.name] = self.embedding_model.embed(tool_text) return embeddings
def select(self, query, top_k=5): """根据查询选择相关工具""" query_emb = self.embedding_model.embed(query)
similarities = {} for name, tool_emb in self.tool_embeddings.items(): sim = self._cosine_similarity(query_emb, tool_emb) similarities[name] = sim
# 返回 top-k sorted_tools = sorted( similarities.items(), key=lambda x: x[1], reverse=True )
return [name for name, _ in sorted_tools[:top_k]]
def _cosine_similarity(self, a, b): return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))6.3 Tool 错误处理
class RobustToolExecutor: """健壮的工具执行器"""
def __init__(self, tools, max_retries=3): self.tools = tools self.max_retries = max_retries
async def execute(self, name, args): """异步执行,带重试""" last_error = None
for attempt in range(self.max_retries): try: tool = self.tools.get(name) if not tool: return {"error": f"未知工具: {name}"}
result = tool.execute(**args)
if isinstance(result, dict) and result.get('success'): return result else: raise Exception(result.get('error', 'Unknown error'))
except Exception as e: last_error = e
# 重试延迟 if attempt < self.max_retries - 1: delay = 2 ** attempt # 指数退避 await asyncio.sleep(delay)
return {"error": f"执行失败 (尝试 {self.max_retries} 次): {last_error}"}7. Multi-Agent 系统
7.1 为什么需要 Multi-Agent?
单 Agent 在复杂任务中存在局限:
- 上下文限制:难以处理庞大信息
- 能力单一:一个 Agent 不可能精通所有
- 协作困难:单 Agent 缺乏不同视角
- 专业不足:通用模型在专业领域不够精准
Multi-Agent 通过分工协作解决这些问题:
- 专业分工:每个 Agent 专注于特定领域
- 并行处理:多个 Agent 同时工作
- 交叉验证:不同 Agent 可以相互校验
- 可扩展性:根据需要增加新 Agent
7.2 Multi-Agent 架构
7.2.1 Supervisor 架构
一个中心 Supervisor 协调多个 Worker Agents:
Supervisor Agent │ ┌──────────────┼──────────────┐ ▼ ▼ ▼ Researcher Coder Reviewer Agent Agent Agentclass SupervisorAgent: """监督者 Agent"""
def __init__(self, llm, worker_agents): self.llm = llm self.worker_agents = worker_agents
def run(self, task): while not self._is_complete(task): # 决定下一步分配给谁 decision = self._decide_next_agent(task) agent_name = decision['agent'] sub_task = decision['sub_task']
# 调用 Worker Agent if agent_name == "FINISH": break
worker = self.worker_agents[agent_name] result = worker.run(sub_task)
# 更新任务状态 task.add_result(agent_name, result)
return task.synthesize()
# 定义 Worker Agentsclass ResearchAgent: def run(self, task): # 研究任务 return search_and_summarize(task)
class CoderAgent: def run(self, task): # 编程任务 return write_code(task)
class ReviewerAgent: def run(self, task): # 评审任务 return review(task)
# 创建系统supervisor = SupervisorAgent( llm=llm, worker_agents={ 'researcher': ResearchAgent(llm), 'coder': CoderAgent(llm), 'reviewer': ReviewerAgent(llm) })7.2.2 对等架构
各 Agent 完全对等,点对点通信:
class PeerToPeerAgent: """点对点 Agent"""
def __init__(self, name, llm, tools, peers=None): self.name = name self.llm = llm self.tools = tools self.peers = peers or {} # 其他 Agent self.mailbox = [] # 消息队列
def send_message(self, peer_name, message): """发送消息给其他 Agent""" peer = self.peers.get(peer_name) if peer: peer.receive_message(self.name, message)
def receive_message(self, sender, message): """接收消息""" self.mailbox.append({'from': sender, 'content': message})
def run(self, task): # 可以询问其他 Agent context = self._format_context() prompt = f"{context}\n\n任务: {task}\n\n响应:" response = self.llm.generate(prompt)
# 决定是否需要其他人协助 if self._needs_help(response): helper = self._choose_helper() self.send_message(helper, "需要帮助")
return response7.2.3 层级架构
按层级组织 Agent:
顶层: Planner Agent (战略规划) │ ├─ 中层: 多个 Specialist Agent (领域专家) │ └─ 底层: 多个 Executor Agent (执行单元)7.3 Agent 通信协议
class AgentMessage: """Agent 间消息""" def __init__(self, sender, receiver, content, msg_type='text', metadata=None): self.sender = sender self.receiver = receiver self.content = content self.msg_type = msg_type # text/request/response/error self.metadata = metadata or {} self.timestamp = time.time()
class AgentCommunicationBus: """Agent 通信总线"""
def __init__(self): self.agents = {} self.message_log = []
def register(self, agent): self.agents[agent.name] = agent
def send(self, message): """发送消息""" # 记录 self.message_log.append(message)
# 路由 receiver = self.agents.get(message.receiver) if receiver: receiver.receive_message(message)
def broadcast(self, sender, content): """广播""" for name, agent in self.agents.items(): if name != sender: self.send(AgentMessage(sender, name, content))7.4 协作模式
7.4.1 投票 (Voting)
class VotingAgent: """投票 Agent"""
def __init__(self, agents): self.agents = agents
def run(self, task): # 每个 Agent 独立给出答案 answers = [] for agent in self.agents: answer = agent.run(task) answers.append(answer)
# 投票 from collections import Counter votes = Counter(answers) most_common = votes.most_common(1)[0][0]
return most_common, votes7.4.2 辩论 (Debate)
class DebateAgent: """辩论 Agent"""
def __init__(self, agents, rounds=3): self.agents = agents self.rounds = rounds
def run(self, task): opinions = [agent.run(task) for agent in self.agents]
for round in range(self.rounds): new_opinions = [] for i, agent in enumerate(self.agents): # 让每个 Agent 看到其他 Agent 的意见 others = [op for j, op in enumerate(opinions) if j != i] context = "\n".join([f"Agent {j}: {op}" for j, op in enumerate(others)])
prompt = f""" 任务: {task}
其他 Agent 的意见: {context}
你的新意见: """ new_opinion = agent.llm.generate(prompt) new_opinions.append(new_opinion)
opinions = new_opinions
# 综合最终答案 final = self.synthesize(opinions) return final7.4.3 流水线 (Pipeline)
class PipelineAgent: """流水线 Agent"""
def __init__(self, agents): self.agents = agents
def run(self, task): result = task for agent in self.agents: result = agent.run(result) return result
# 使用:研究 -> 写作 -> 审查 -> 发布pipeline = PipelineAgent([ ResearchAgent(llm), WriterAgent(llm), ReviewerAgent(llm), PublisherAgent(llm)])7.5 AutoGen 框架示例
# AutoGen 风格的多 Agent 协作from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager
# 定义 Agentresearcher = AssistantAgent( name="researcher", llm_config={"model": "gpt-4"}, system_message="你是一个研究员。负责查找和分析信息。")
coder = AssistantAgent( name="coder", llm_config={"model": "gpt-4"}, system_message="你是一个程序员。负责编写代码。")
user_proxy = UserProxyAgent( name="user_proxy", human_input_mode="TERMINATE")
# 创建群聊groupchat = GroupChat( agents=[user_proxy, researcher, coder], messages=[], max_round=10)
manager = GroupChatManager(groupchat=groupchat, llm_config={"model": "gpt-4"})
# 启动user_proxy.initiate_chat( manager, message="开发一个计算斐波那契数列的 Python 程序")8. LangGraph 框架
8.1 LangGraph 概述
LangGraph 是 LangChain 推出的图状 Agent 框架:
# LangGraph 用 StateGraph 定义 Agentfrom langgraph.graph import StateGraph, END
# 定义 Stateclass AgentState(TypedDict): messages: list next_step: str
# 定义节点def research_step(state): # 研究节点 return {"messages": state["messages"] + ["research done"]}
def code_step(state): # 编码节点 return {"messages": state["messages"] + ["code done"]}
def review_step(state): # 审查节点 return {"messages": state["messages"] + ["review done"]}
# 定义图workflow = StateGraph(AgentState)
workflow.add_node("research", research_step)workflow.add_node("code", code_step)workflow.add_node("review", review_step)
# 定义边workflow.add_edge("research", "code")workflow.add_edge("code", "review")workflow.add_edge("review", END)
# 入口点workflow.set_entry_point("research")
# 编译app = workflow.compile()
# 执行result = app.invoke({"messages": []})8.2 条件分支
def should_continue(state): """决定下一步""" last_message = state["messages"][-1]
if "需要更多信息" in last_message: return "research" elif "需要修复" in last_message: return "code" elif "完成" in last_message: return END else: return "review"
# 添加条件边workflow.add_conditional_edges( "review", should_continue, { "research": "research", "code": "code", END: END })8.3 循环工作流
class IterativeState(TypedDict): code: str tests: str iteration: int passed: bool
def generate_code(state): if state["iteration"] == 0: code = generate_initial(state["tests"]) else: code = fix_code(state["code"], state["test_results"]) return {"code": code, "iteration": state["iteration"] + 1}
def run_tests(state): passed = execute_tests(state["code"], state["tests"]) return {"passed": passed}
def should_continue(state): if state["passed"] or state["iteration"] >= 5: return "end" return "retry"
workflow = StateGraph(IterativeState)workflow.add_node("code", generate_code)workflow.add_node("test", run_tests)
workflow.add_edge("code", "test")workflow.add_conditional_edges( "test", should_continue, {"end": END, "retry": "code"})workflow.set_entry_point("code")
app = workflow.compile()9. Agent 评估
9.1 评估维度
class AgentEvaluator: """Agent 评估器"""
METRICS = { 'success_rate': '任务完成率', 'efficiency': '效率(步数/时间)', 'tool_accuracy': '工具调用准确率', 'response_quality': '响应质量', 'robustness': '鲁棒性', 'cost': '成本(token/金钱)' }
def evaluate(self, agent, test_cases): results = { 'success': 0, 'total': 0, 'steps': [], 'tokens': 0, 'time': 0, }
for case in test_cases: start_time = time.time()
result = agent.run(case['input'])
results['time'] += time.time() - start_time results['total'] += 1
# 成功评估 if self._check_success(result, case['expected']): results['success'] += 1
return { 'success_rate': results['success'] / results['total'], 'avg_time': results['time'] / results['total'], 'avg_steps': sum(results['steps']) / results['total'], 'total_cost': results['tokens'] }9.2 评估基准
AGENT_BENCHMARKS = { 'HotpotQA': '多跳问答', 'FEVER': '事实核查', 'SWE-bench': '软件工程', 'HumanEval': '代码生成', 'WebShop': '网页购物', 'AlfWorld': '文本游戏', 'Mind2Web': '网页操作', 'GAIA': '通用助手', 'AgentBench': '综合 Agent 评测',}
class BenchmarkRunner: """基准测试运行器"""
def run_benchmark(self, agent, benchmark_name): cases = self.load_benchmark(benchmark_name) return self.evaluate(agent, cases)9.3 失败分析
class FailureAnalyzer: """失败分析器"""
FAILURE_TYPES = [ 'planning_failure', # 规划失败 'tool_selection', # 工具选错 'tool_execution', # 工具执行失败 'reasoning_loop', # 推理循环 'context_overflow', # 上下文溢出 'hallucination', # 幻觉 'timeout', # 超时 ]
def analyze(self, run_history): """分析失败原因""" for step in run_history: step['failure_type'] = self._classify_failure(step)
distribution = Counter( s['failure_type'] for s in run_history if s.get('failure_type') )
return { 'distribution': distribution, 'recommendations': self._generate_recommendations(distribution) }
def _generate_recommendations(self, distribution): """生成改进建议""" recs = []
if distribution.get('planning_failure', 0) > 0.2: recs.append("改进规划策略:使用 Plan-and-Execute")
if distribution.get('tool_selection', 0) > 0.2: recs.append("改进工具描述:使 description 更清晰")
if distribution.get('reasoning_loop', 0) > 0.1: recs.append("加入循环检测机制")
return recs10. 生产实践
10.1 性能优化
10.1.1 Token 优化
class TokenOptimizedAgent: """Token 优化的 Agent"""
def __init__(self, llm, tools): self.llm = llm self.tools = tools
def compress_prompt(self, prompt, max_tokens=4000): """压缩 prompt""" if self._count_tokens(prompt) > max_tokens: # 策略 1: 删除旧的工具结果 prompt = self._remove_old_observations(prompt)
# 策略 2: 总结长对话 if self._count_tokens(prompt) > max_tokens: prompt = self._summarize_old_messages(prompt)
return prompt
def cache_system_prompt(self): """缓存 system prompt (如果模型支持)""" # Claude: cache_control # OpenAI: 自动部分优化 ...
def parallel_tool_calls(self): """并行工具调用""" # 多个独立工具同时执行 ...10.1.2 模型路由
class ModelRouter: """模型路由器"""
def __init__(self): self.cheap_model = "gpt-3.5-turbo" self.expensive_model = "gpt-4"
def choose_model(self, task_complexity): """根据复杂度选择模型""" if task_complexity < 0.3: return self.cheap_model else: return self.expensive_model
# 在 Agent 中使用class CostOptimizedAgent: def __init__(self): self.router = ModelRouter()
def run(self, task): # 简单任务用便宜模型 if self._is_simple(task): model = self.router.cheap_model else: model = self.router.expensive_model
return self._generate(model, task)10.2 可靠性
class ReliableAgent: """可靠的 Agent"""
def __init__(self, llm, tools, max_retries=3): self.llm = llm self.tools = tools self.max_retries = max_retries
def run(self, task): for attempt in range(self.max_retries): try: return self._try_run(task) except Exception as e: if attempt < self.max_retries - 1: # 记录错误,调整策略 self._handle_error(e) else: raise
def _handle_error(self, error): """错误处理""" if isinstance(error, ToolExecutionError): # 工具错误:重试或换工具 self._fallback_strategy(error) elif isinstance(error, RateLimitError): # 限流:等待 time.sleep(60) # ...10.3 监控
class AgentMonitor: """Agent 监控器"""
def __init__(self): self.metrics = []
def record_step(self, step_data): """记录每步""" self.metrics.append({ 'timestamp': time.time(), 'step_type': step_data['type'], 'duration': step_data['duration'], 'tokens': step_data['tokens'], 'success': step_data['success'] })
def get_dashboard(self): """获取仪表盘数据""" return { 'total_runs': len(self.metrics), 'success_rate': self._calc_success_rate(), 'avg_duration': self._avg('duration'), 'p95_duration': self._percentile('duration', 95), 'avg_tokens': self._avg('tokens'), 'cost_estimate': self._estimate_cost() }10.4 安全性
class SecureAgent: """安全的 Agent"""
SENSITIVE_TOOLS = {'make_payment', 'delete_data', 'send_email'}
def execute_tool(self, name, args): tool = self.tools.get(name)
# 敏感操作需要确认 if name in self.SENSITIVE_TOOLS: if not self._user_confirmation(name, args): return "用户拒绝"
# 输入消毒 sanitized_args = self._sanitize(name, args)
# 执行 return tool.execute(**sanitized_args)
def _user_confirmation(self, action, args): """用户确认""" print(f"\n⚠️ 确认执行: {action}({args})") return input("(yes/no): ").lower() == 'yes'
def _sanitize(self, name, args): """输入消毒""" # SQL 注入检测 # 路径遍历检测 # 命令注入检测 # ... return args11. 实战案例
11.1 研究助手 Agent
class ResearchAssistantAgent: """研究助手 Agent"""
def __init__(self): self.tools = ToolRegistry() self._register_tools() self.memory = LongTermMemory(embedder, vector_store)
def _register_tools(self): @self.tools.register(description="搜索 arXiv 论文") def search_arxiv(query, max_results=5): # ... return results
@self.tools.register(description="阅读论文内容") def read_paper(paper_id): # ... return content
@self.tools.register(description="总结段落") def summarize(text): return self.llm.summarize(text)
@self.tools.register(description="生成引用") def cite(paper_id): return format_citation(paper_id)
def research(self, question): plan = self._create_research_plan(question)
report = [] for step in plan: if step.tool == "search_arxiv": papers = self.tools.get("search_arxiv").execute(**step.args) # 选最相关的几篇 for paper in papers[:3]: content = self.tools.get("read_paper").execute(paper.id) summary = self.tools.get("summarize").execute(content) report.append({ 'paper': paper, 'summary': summary, 'citation': self.tools.get("cite").execute(paper.id) })
return self._write_report(question, report)11.2 编码 Agent
class CodingAgent: """编码 Agent - 类似 SWE-Agent"""
def __init__(self, repo_path): self.tools = ToolRegistry() self._register_coding_tools() self.repo_path = repo_path
def _register_coding_tools(self): @self.tools.register(description="读取文件") def read_file(path): with open(f"{self.repo_path}/{path}", 'r') as f: return f.read()
@self.tools.register(description="编辑文件") def edit_file(path, old_string, new_string): # 应用编辑 ...
@self.tools.register(description="运行命令") def run_command(cmd): return subprocess.run(cmd, shell=True, capture_output=True)
@self.tools.register(description="搜索代码") def search_code(pattern): return grep(self.repo_path, pattern)
def solve_issue(self, issue_text): # 1. 理解问题 # 2. 查看相关文件 # 3. 设计修复 # 4. 应用修改 # 5. 运行测试 # 6. 迭代到通过 ...11.3 数据分析 Agent
class DataAnalysisAgent: """数据分析 Agent"""
def analyze(self, dataset_path, question): # 1. 理解数据集 schema = self._read_schema(dataset_path)
# 2. 规划分析步骤 plan = self._plan_analysis(question, schema)
# 3. 执行 results = {} for step in plan: if step.tool == "execute_sql": results[step.id] = self.execute_sql(step.sql) elif step.tool == "create_chart": results[step.id] = self.create_chart(results[step.deps]) elif step.tool == "interpret": results[step.id] = self.interpret(results[step.deps])
# 4. 生成报告 return self.generate_report(question, results)12. 框架对比
12.1 主流 Agent 框架
| 框架 | 特点 | 适合场景 |
|---|---|---|
| LangChain | 通用 LLM 框架 | 多用途 |
| LangGraph | 图状 Agent | 复杂工作流 |
| AutoGen | 多 Agent 协作 | 对话式 |
| CrewAI | 角色扮演多 Agent | 协作任务 |
| LangSmith | 可观测性 | 调试优化 |
| Semantic Kernel | 企业级 | .NET 生态 |
| SmolAgents | 轻量级 | 简单应用 |
12.2 选型建议
FRAMEWORK_SELECTION = """选择 LangChain / LangGraph 当: - 需要 RAG、链式调用等 - 工作流是图/树结构 - 需要细粒度控制
选择 AutoGen 当: - 主要需求是多 Agent 对话 - 人类在环 (human-in-the-loop) - 灵活的对话管理
选择 CrewAI 当: - 角色清晰的多 Agent 协作 - 任务流程标准化 - 希望快速搭建
选择 SmolAgents 当: - 简单任务 - 学习 Agent 原理 - 快速原型
自研 当: - 完全定制需求 - 学习/教育目的 - 已有基础设施"""13. 未来发展方向
13.1 当前挑战
┌─────────────────────────────────────────────────────┐│ Agent 的核心挑战 │├─────────────────────────────────────────────────────┤│ ││ 1. 可靠性 ││ - 长链任务容易出错 ││ - 需要自我纠错 ││ ││ 2. 效率 ││ - Token 消耗巨大 ││ - 需要优化策略 ││ ││ 3. 评估 ││ - 难以量化性能 ││ - 需要更好基准 ││ ││ 4. 安全 ││ - 自主行动的边界 ││ - 防止滥用 ││ ││ 5. 协同 ││ - 多 Agent 协调复杂 ││ - 通信协议尚未成熟 ││ │└─────────────────────────────────────────────────────┘13.2 未来方向
- 更智能的规划:从被动响应到主动规划
- 更强记忆:跨会话、跨任务的长期记忆
- 更好的工具学习:自动发现和使用新工具
- 多模态融合:视觉、听觉、触觉的统一
- 自演化 Agent:根据使用自动改进
13.3 Agent OS 愿景
未来的 Agent OS:┌────────────────────────────────────┐│ Agent Operating System │├────────────────────────────────────┤│ - 标准化工具调用 ││ - 统一的记忆接口 ││ - 跨平台 Agent 运行时 ││ - Agent 网络通信 ││ - 安全沙箱 │└────────────────────────────────────┘ │ │ ▼ ▼ ┌─────────┐ ┌─────────┐ │ Agent A │ │ Agent B │ └─────────┘ └─────────┘14. 核心概念总结
14.1 Agent 的核心定义
AGENT_EQUATION = """Agent = Perception + Memory + Reasoning + Action + Tools
其中:- Perception: 感知环境- Memory: 记忆系统- Reasoning: 推理决策- Action: 行动执行- Tools: 工具集
Agent 的核心特征:1. 自主性 (Autonomy)2. 反应性 (Reactivity)3. 主动性 (Proactivity)4. 社交性 (Social Ability)"""14.2 关键架构模式
ARCHITECTURE_PATTERNS = """1. 单 Agent - ReAct - Plan-Execute - Reflexion - ReWOO
2. Multi-Agent - Supervisor - Hierarchical - Peer-to-Peer - Collaborative
3. 设计原则 - 模块化 - 可观测 - 容错 - 可扩展"""14.3 数学化表达
- Agent 决策过程:
其中 是行动, 是状态, 是记忆, 是工具集。
- Plan-Execute 计划评估:
- 记忆检索相似度:
15. 实战建议
15.1 设计 Agent 的最佳实践
BEST_PRACTICES = """1. 从简单开始 - 先实现 ReAct - 逐步添加复杂功能 - 测试每个组件
2. 工具设计 - 单一职责 - 清晰描述 - 错误处理
3. 记忆策略 - 短期+长期结合 - 定期压缩 - 重要信息优先
4. 规划策略 - 简单任务不需要复杂规划 - 复杂任务使用 Plan-Execute - 加入容错
5. 评估驱动 - 先定义评估标准 - 持续监控 - 数据驱动改进"""15.2 常见反模式
ANTI_PATTERNS = """1. 过度复杂 - 一开始就设计 10 个 Agent - 应该从单 Agent 开始
2. 缺乏测试 - 没有评估标准 - 难以改进
3. 忽视成本 - 不监控 Token 使用 - 应该控制成本
4. 没有 fallback - 单点失败 - 应该设计降级方案
5. 模糊目标 - Agent 不知道目标 - 应该明确任务分解"""15.3 学习路径
LEARNING_ROADMAP = """1. 基础 (1-2 周) - 理解 LLM 调用 - 学会 Function Calling - 实现 ReAct Agent
2. 进阶 (2-4 周) - 加入 Memory 系统 - 学习 Plan-Execute - 实现复杂 Agent
3. 多 Agent (4-8 周) - 学习 Multi-Agent 概念 - 掌握 1-2 个框架(LangGraph/AutoGen) - 实现协作系统
4. 专家 (3 个月+) - 深入研究 - 性能优化 - 生产部署 - 安全考虑"""16. 总结
Agent 架构的核心
AI Agent 不只是”会调用工具的 LLM”,而是一个完整的智能系统:
- 感知:理解环境
- 记忆:积累知识
- 推理:规划决策
- 行动:执行任务
Agent 的发展趋势
| 阶段 | 时间 | 特征 |
|---|---|---|
| LLM | 2020-2022 | 文本生成 |
| Tool-LLM | 2023 | 工具调用 |
| ReAct Agent | 2022-2023 | 思考+行动 |
| Multi-Agent | 2023-2024 | 多代理协作 |
| Agent OS | 2025+ | 平台化 |
推荐资源
- 论文:ReAct, Reflexion, ReWOO, AutoGen
- 框架:LangChain, LangGraph, AutoGen, CrewAI
- 课程:DeepLearning.AI Agent 课程
- 实践:从简单 ReAct 开始,逐步构建复杂系统
结语
AI Agent 是 LLM 走向通用人工智能的关键一步。掌握 Agent 架构设计,理解不同模式、Memory 系统、Multi-Agent 协作,将为你打开 AI 应用开发的新天地。
无论技术如何演进,Perception → Reasoning → Action 的循环思想始终是 Agent 系统设计的核心范式。
参考资料
- Yao, S., et al. (2022). “ReAct: Synergizing Reasoning and Acting in Language Models.” ICLR.
- Shinn, N., et al. (2023). “Reflexion: Language Agents with Verbal Reinforcement Learning.” NeurIPS.
- Wei, J., et al. (2022). “Chain-of-Thought Prompting Elicits Reasoning in Large Language Models.” NeurIPS.
- Liu, J., et al. (2023). “ReWOO: Decoupling Reasoning from Observations for Efficient Augmented Language Models.” arXiv.
- Schick, T., et al. (2023). “Toolformer: Language Models Can Teach Yourself to Use Tools.” NeurIPS.
- Wang, L., et al. (2024). “A Survey on Large Language Model based Autonomous Agents.” arXiv.
- Xi, Z., et al. (2023). “The Rise and Potential of Large Language Model Based Agents.” arXiv.
- Wu, Q., et al. (2023). “AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation.” arXiv.
- LangChain. (2024). “LangGraph: Multi-Agent Workflows.” Documentation.
- Anthropic. (2024). “Building Effective Agents with Claude.” Engineering Blog.
- Microsoft. (2024). “AutoGen: Enabling Next-Gen LLM Applications.” arXiv.
- Patil, S., et al. (2024). “Function Calling Best Practices.” OpenAI Cookbook.
- Liu, F., et al. (2024). “AgentBench: Evaluating LLMs as Agents.” ICLR.
文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!

