Community编程与开发github.com

多智能体架构模式

此技能用于设计需要上下文隔离、监督或群组协调、显式移交、并行执行,或需要判断是否真正需要多个智能体的多智能体系统。

多智能体架构模式 是什么?

该技能提供了一套全面的多智能体架构设计原则和实用模式,帮助开发者在构建复杂AI系统时做出正确的技术决策。核心论点是,多智能体的主要价值在于上下文隔离——每个子智能体独立操作于自己的上下文窗口,避免信息在传递过程中退化(即“传话游戏”问题)。技能详细介绍了三种主导模式:监督者/编排器模式(适用于任务分解清晰且需要人工监督的场景)、点对点/群组模式(适合需要灵活探索的动态问题)、以及分层模式(适用于需要策略、规划和执行多层抽象的复杂项目)。此外,它还探讨了共识机制(如加权投票、辩论协议)、失败模式与缓解策略(如监督者瓶颈、错误传播)、以及具体的代码示例和框架对比(如LangGraph、AutoGen、CrewAI),指导开发者根据实际协调需求而非组织隐喻进行选择。技能支持Claude Code、Cursor、Codex等主流AI编程平台,强调在考虑多智能体架构前应先评估模型质量提升和单智能体基线表现。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/multi-agent-patterns

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

多智能体架构模式 是做什么的?

多智能体架构将工作分配到多个语言模型实例上,每个实例拥有自己的上下文窗口。设计得当时,这种分配能够实现超越单智能体限制的能力。设计得不好时,它引入的协调开销会抵消收益。关键洞察在于:子智能体存在的首要目的是隔离上下文,而非将角色分工拟人化。

何时激活

在以下情况下激活此技能:

  • 单智能体的上下文限制制约了任务复杂性
  • 任务可以自然地分解为并行的子任务
  • 不同的子任务需要不同的工具集或系统提示
  • 构建必须同时处理多个领域的系统
  • 将智能体能力扩展到单一上下文限制之外
  • 设计具有多个专业化组件的生产级智能体系统

对于其他技能负责的相关工作,不要激活此技能:

  • 在拓扑确定之前决定任务-模型匹配度、流程形状或项目级成本:project-development
  • 设计托管沙箱、预热池、远程会话或后台运行时基础设施:hosted-agents
  • 通过受控运行时中的 KV 缓存压缩共享编排器状态:latent-briefing
  • 设计每个智能体暴露的工具:tool-design

核心概念

当单个智能体的上下文窗口无法容纳所有任务相关信息时,使用多智能体模式。上下文隔离是主要优势——每个智能体在一个干净的上下文中操作,不会积累其他子任务带来的噪声,从而防止信息通过重复摘要而退化的“传话游戏”问题。

根据协调需求(而非组织隐喻)在三种主要模式中选择:

  • 监督者/编排器 — 用于当任务有清晰分解且人工监督很重要时的集中控制。单个协调者委托给专家并综合结果。
  • 点对点/群组 — 用于当刚性规划适得其反时的灵活探索。任何智能体都可以通过显式移交机制将控制权转移给任何其他智能体。
  • 分层 — 用于具有分层抽象(策略、规划、执行)的大型项目。每一层在不同的细节层级上操作,拥有自己的上下文结构。

围绕显式协调协议、能够抵抗谄媚的共识机制以及防止错误传播级联的故障处理来设计每个多智能体系统。

详细主题

为什么需要多智能体架构

上下文瓶颈 当单个智能体的上下文被累积的历史记录、检索到的文档和工具输出填满,导致性能下降时,采用多智能体架构。识别三种退化信号:中间迷失效应(注意力对中间内容减弱)、注意力稀缺(太多竞争项)和上下文污染(无关内容挤占有用内容)。

将工作划分到多个上下文窗口,使每个智能体在其干净的、专注于子任务的上下文中操作。在协调层聚合结果,而不让任何一个上下文承担全部负担。

代币经济现实 为显著更高的代币成本做好预算。生产数据显示,多智能体系统可能比单智能体聊天消耗多得多的代币(claim-multi-agent-token-multiplier):

架构代币倍数用例
单智能体聊天基准简单查询
带工具的单智能体高于基准使用工具的任务
多智能体系统远高于基准复杂研究/协调

浏览代理评估研究表明,代币使用量、工具调用和模型选择主导性能差异(claim-evaluation-browsecomp-variance)。这支持将多智能体设置与单智能体基线进行比较,而不是假设额外的智能体一定有帮助。

将模型选择与架构设计放在同等优先位置——升级到更好的模型通常比加倍代币预算带来更大的性能提升。BrowseComp 数据表明,模型质量改进通常优于原始代币增加。将模型选择和多智能体架构视为互补策略。

并行化论点 将可并行的子任务分配给具有全新上下文的专用智能体,而不是在单个智能体中顺序处理。需要跨多个独立来源搜索、分析不同文档或比较竞争方法的研究任务受益于并行执行。实际总时间接近于最长子任务的持续时间,而不是所有子任务的总和。

专业化论点 为每个智能体仅配置其特定子任务所需的系统提示、工具和上下文。通用智能体必须在其上下文中携带所有可能的配置,从而稀释注意力。专业化智能体只携带它们需要的东西,使用针对其领域优化的精简上下文进行操作。从协调者路由到专业化智能体,以实现专业化而无需组合爆炸。

架构模式

模式 1:监督者/编排器 部署一个中央智能体来维护全局状态和轨迹,将用户目标分解为子任务,并路由给适当的工人。

用户查询 -> 监督者 -> [专家, 专家, 专家] -> 聚合 -> 最终输出

在以下情况下选择此模式:任务有清晰分解,需要跨领域协调,或人工监督很重要。

预期这些权衡:严格的工作流控制和更容易的人工介入干预,但监督者上下文成为瓶颈,监督者故障会级联到所有工人,并且出现“传话游戏”问题,即监督者不正确地转述子智能体的响应。

传话游戏问题及解决方案 预期监督者架构初始性能比优化版本差约 50%,原因是传话游戏问题(LangGraph 基准测试)。监督者转述子智能体的响应,每次传递都会丢失保真度。

通过实现 forward_message 工具来修复此问题,该工具允许子智能体直接将响应传递给用户:

def forward_message(message: str, to_user: bool = True):
    """
    将子智能体的响应直接转发给用户,无需监督者合成。

    在以下情况下使用:
    - 子智能体响应是最终且完整的
    - 监督者合成会丢失重要细节
    - 必须精确保留响应格式
    """
    if to_user:
        return {"type": "direct_response", "content": message}
    return {"type": "supervisor_input", "content": message}

当子智能体可以直接响应用户时,优先选择群组架构而非监督者架构,因为这样可以完全消除翻译错误。

模式 2:点对点/群组 移除中央控制,允许智能体基于预定义协议直接通信。任何智能体通过显式移交机制将控制权转移给任何其他智能体。

def transfer_to_agent_b():
    return agent_b  # 通过函数返回进行移交

agent_a = Agent(
    name="智能体 A",
    functions=[transfer_to_agent_b]
)

在以下情况下选择此模式:任务需要灵活探索,刚性规划适得其反,或者需求动态涌现且无法预先分解。

预期这些权衡:没有单点故障和有效的广度优先扩展,但协调复杂性随着智能体数量增加而增加,没有中央状态保持者时发散风险上升,并且需要稳健的收敛约束。

定义带有状态传递的显式移交协议。确保智能体将其上下文需求告知接收智能体。

模式 3:分层 将智能体组织成抽象层:策略(目标定义)、规划(任务分解)和执行(原子任务)。

策略层(目标定义) -> 规划层(任务分解) -> 执行层(原子任务)

在以下情况下选择此模式:项目具有清晰的分层结构,工作流涉及管理层,或任务需要高层规划和详细执行。

预期这些权衡:关注点分离明确,支持不同层级的不同上下文结构,但各层之间存在协调开销,可能出现策略-执行不一致,以及复杂的错误传播路径。

上下文隔离作为设计原则

将上下文隔离视为多智能体架构的主要目的。每个子智能体应在一个干净的上下文窗口中操作,专注于其子任务,而不携带来自其他子任务的累积上下文。

隔离机制 为每个子任务选择正确的隔离机制:

  • 完整上下文委托 — 将规划器的完整上下文共享给子智能体。用于子智能体需要完全理解的复杂任务。子智能体拥有自己的工具和指令,但接收完整的上下文以供决策。注意:这在某种程度上违背了上下文隔离的目的。
  • 指令传递 — 通过函数调用创建指令;子智能体仅接收它需要的内容。用于简单、定义明确的子任务。保持隔离但限制子智能体的灵活性。
  • 文件系统内存 — 智能体读写持久化存储。用于需要共享状态的复杂任务。文件系统充当协调机制,避免因共享状态传递而导致的上下文膨胀。引入延迟和一致性挑战,但比消息传递具有更好的可扩展性。

根据任务复杂性、协调需求和可接受的延迟进行选择。默认使用指令传递,当需要共享状态时升级到文件系统内存。除非子任务确实需要,否则避免完整上下文委托。

共识与协调

投票问题 避免简单多数投票——它对待弱模型的幻觉与强模型的推理同等重要。如果不加干预,多智能体讨论会因固有的共识倾向而退化为对错误前提的一致同意。

加权投票 根据置信度或专业知识对智能体投票进行加权。置信度更高或领域专业知识更强的智能体应在最终决策中拥有更大的权重。

辩论协议 构建智能体,使其在多轮中相互批评对方的输出。对抗性批评在复杂推理上通常比协作共识产生更高的准确性。防范谄媚式趋同,即智能体为了友好而非正确而达成一致。

触发器式干预 监控多智能体交互的行为标记。当讨论没有进展时激活停滞触发器。当智能体没有独特推理而模仿彼此答案时检测谄媚触发器。

框架考虑

不同框架以不同的理念实现这些模式。LangGraph 使用基于图的状态机,具有显式节点和边。AutoGen 使用对话/事件驱动模式,带有 GroupChat。CrewAI 使用基于角色的流程,具有分层团队结构。

实用指南

失败模式及缓解措施

失败:监督者瓶颈 监督者累积所有工人的上下文,容易饱和和退化。

通过约束工人输出模式,使工人只返回精炼摘要来缓解。使用检查点来持久化监督者状态,而无需在上下文中携带完整历史记录。

失败:协调开销 智能体通信消耗代币并引入延迟。复杂的协调可能抵消并行化的好处。

通过清晰的移交协议最小化通信来缓解。尽可能批量处理结果。使用异步通信模式。衡量多智能体协调是否比使用更长上下文的单智能体实际节省时间。

失败:发散 智能体在没有中央协调的情况下追求不同的目标,偏离预期目标。

通过为每个智能体定义明确的目标边界来缓解。实施收敛检查,验证向共享目标的进展。设置智能体执行的生命周期限制,防止无边界探索。

失败:错误传播 一个智能体输出中的错误传播到消费该输出的下游智能体,复合为越来越错误的结果。

通过在将输出传递给消费者之前验证智能体输出来缓解。实施带有熔断器的重试逻辑。尽可能使用幂等操作。考虑添加一个验证智能体,在关键输出进入管道之前对其进行交叉检查。

示例

示例 1:研究团队架构

监督者
├── 研究员(网络搜索、文档检索)
├── 分析员(数据分析、统计)
├── 事实核查员(验证、确认)
└── 写手(报告生成、格式化)

示例 2:移交协议

def handle_customer_request(request):
    if request.type == "billing":
        return transfer_to(billing_agent)
    elif request.type == "technical":
        return transfer_to(technical_agent)
    elif request.type == "sales":
        return transfer_to(sales_agent)
    else:
        return handle_general(request)

准则

  1. 将上下文隔离设计为多智能体系统的主要好处
  2. 根据协调需求(而非组织隐喻)选择架构模式
  3. 实现带有状态传递的显式移交协议
  4. 使用加权投票或辩论协议达成共识
  5. 监控监督者瓶颈并实施检查点
  6. 在智能体之间传递输出之前进行验证
  7. 设置生命周期限制以防止无限循环
  8. 明确测试失败场景

注意事项

  1. 监督者瓶颈: 中央智能体随着工人数量增加而饱和。通过约束输出并使用检查点来缓解。
  2. 传话游戏: 转述会丢失细节。使用直接转发或群组模式进行最终输出。
  3. 代币成本: 预期总代币成本远高于中等单智能体任务。考虑模型质量升级作为替代。
  4. 协调开销: 如果通信比节省的时间更昂贵,并行化就会失去意义。测量实际收益。
  5. 发散: 没有中央监控的群组模式可能会失去目标。在适当的地方实施触发器——但每个触发器都需要自己的智能体来处理,从而增加成本。
  6. 错误传播: 错误会级联。在将输出传递给其他智能体之前验证每个输出。
  7. 不必要的复杂性: 不要因为听起来不错而使用多智能体。更长的上下文、更好的模型或更好的提示通常就足够了。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

advanced-evaluation

This skill should be used for advanced LLM evaluation: LLM-as-judge systems, direct scoring, pairwise comparison, rubric calibration, evaluator bias mitigation, confidence scoring, and automated quality assessment.

bdi-mental-states

This skill should be used when modeling agent mental states with BDI concepts: beliefs, desires, intentions, RDF-to-belief transformations, rational agency traces, cognitive agents, BDI ontologies, and neuro-symbolic AI integration.

book-sft-pipeline

This skill should be used for book-to-SFT pipelines: ePub extraction, literary segmentation, author-voice dataset construction, style-transfer training, LoRA workflows, and model evaluation for voice replication.

compaction-control-profiling

This skill should be used when deciding, for a specific model and workload, whether the harness or the model should control compaction, and when qualifying or calibrating that choice with measurements: context-budget sweeps that compare harness-driven and model-driven compaction on one harness, the context-pressure regime where delegation pays, a per-model compaction behavior profile (interface uptake, compression factor per call, reopen rate of archived content, context fill at first compaction, response to pressure warnings), context anxiety and timing-instruction calibration, reversible collapse-and-archive interfaces, and re-qualification after a model or prompt change. Route the editable-file protocol, harness invariants, and edit-position cache cost of self-editing agents to self-managed-context, summary content to context-compression, harness thresholds and cache layout to context-optimization, and general evaluation design to evaluation.

comprehensive-research-agent

Ensure thorough validation, error recovery, and transparent reasoning in research tasks with multiple tool calls

context-compression

This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions.

context-degradation

This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.

context-fundamentals

This skill should be used to explain or reason about the foundational concepts of context engineering: what context is, the anatomy of a context window, how attention mechanics work, the U-shaped attention curve, why context quality matters more than quantity, and the mental models needed to interpret every other context-engineering decision. Use this for conceptual explanation, onboarding, and background reading. Route operational work to the specialized skills: debugging attention failures goes to context-degradation, token-efficiency work goes to context-optimization, conversation summarization goes to context-compression, and project-shape decisions go to project-development.

context-optimization

This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.

evaluation

This skill should be used when building agent evaluation systems: deterministic checks, regression suites, multi-dimensional rubrics, quality gates, production monitoring, baseline comparison, and outcome measurement for agent pipelines.

filesystem-context

This skill should be used when agent work needs file-backed context: durable scratchpads, tool-output offloading, just-in-time discovery, cross-agent handoff files, filesystem memory, or cleanup policies for context stored outside the prompt.

harness-engineering

This skill should be used when designing autonomous agent harnesses: research loops, evaluation scaffolds, locked and editable surfaces, durable logs, novelty gates, pruning, rollback, PR preparation, and human approval boundaries.

hosted-agents

This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes.

instruction-surface-security

Hardens agent runtimes against persistent prompt injection or unauthorized changes to instructions and permissions. Use to audit what agents auto-load, design reviewed activation for project rules, skills, memory, or tool configuration, and test whether trust boundaries hold after reload, restart, or delegation.

latent-briefing

This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

long-horizon-prompting

This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

memory-systems

This skill should be used for persistent semantic memory in agent systems: cross-session knowledge retention, entity tracking, temporal validity, graph or vector retrieval, memory consolidation, and memory benchmark selection. Route file-backed scratchpads to filesystem-context, handoff summaries to context-compression, and token-efficiency tactics to context-optimization.

project-development

This skill should be used for project-level decisions about LLM-powered systems: whether an LLM is the right primitive for the task at hand, the shape of a multi-stage batch or agent pipeline, token and cost estimation, choosing between single-agent and multi-agent at the project level, structured output design for downstream parsing, and structuring agent-assisted iteration. Use this when the unit of work is a whole project or a multi-stage pipeline. Route individual tool design to tool-design and individual skill-loading or context-budget tactics to context-optimization.

self-improvement-loops

This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

self-managed-context

This skill should be used when a model gets read-write control over its own live context window instead of a harness-scheduled compaction policy: the context exposed as an editable file the model rewrites with code tools, model-driven eviction and in-place updates, the harness invariants that keep self-editing safe (pinned prefix, edit gate, edit receipts, budget readouts, rollback on overflow), the prefix-cache cost of mid-context edits, and steering or training the model's own context-editing strategy. Route note content and fixed-threshold summarization to context-compression, cache-stable layout under harness control to context-optimization, file offloading to filesystem-context, and loop governance to self-improvement-loops.

相关技能