Community程式設計與開發github.com

多智能體架構模式

此技能適用於設計需要上下文隔離、監督者或群體協調、明確交接、平行執行的多智能體系統,或協助判斷是否值得使用多個智能體。

多智能體架構模式 是什麼?

這個技能提供了一套完整的架構模式,用於設計和實作多智能體系統。它的核心觀點是,子智能體的主要目的是隔離上下文,而不是擬人化的角色分工。技能詳細說明了三種主要模式:監督者/協調者模式用於集中控制,點對點/群體模式用於靈活探索,以及階層式模式用於大規模專案。它還深入探討了上下文隔離的設計原則、共識與協調機制(如加權投票和辯論協議)、以及各種常見的失敗模式與緩解策略。此技能適用於 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 的新對話。

說明文件

多智能體架構模式 是做什麼的?

多智能體架構將工作分佈到多個語言模型實例上,每個實例都有自己的上下文視窗。如果設計得當,這種分佈能夠實現超越單一智能體限制的能力。如果設計不當,則會引入協調開銷,反而抵消好處。關鍵的見解是,子智能體主要用於隔離上下文,而不是擬人化的角色分工。

何時啟用

在以下情況啟用此技能:

  • 單一智能體的上下文限制限制了任務的複雜度
  • 任務自然分解為可並行的子任務
  • 不同的子任務需要不同的工具集或系統提示詞
  • 構建必須同時處理多個領域的系統
  • 將智能體能力擴展到單一上下文的限制之外
  • 設計具有多個專業化元件的生產級智能體系統

對於以下由其他技能負責的相關工作,請勿啟用此技能:

  • 決定任務-模型匹配、流程形狀或在拓撲結構確定前的專案級別成本:專案開發。
  • 設計託管沙盒、熱池、遠端會話或背景運行時基礎設施:託管智能體。
  • 透過受控運行時中的 KV 快取壓縮來共享協調器狀態:潛在簡報。
  • 設計每個智能體暴露的工具:工具設計。

核心概念

當單一智能體的上下文視窗無法容納所有任務相關資訊時,使用多智能體模式。上下文隔離是主要好處——每個智能體在乾淨的上下文中運行,不會積累來自其他子任務的雜訊,從而防止了資訊透過重複摘要而衰減的"傳話遊戲"問題。

根據協調需求(而非組織隱喻)在三種主要模式中選擇:

  • 監督者/協調者 — 當任務有清晰的分解且需要人類監督時,用於集中控制。單一協調者將任務委派給專家並合成結果。
  • 點對點/群體 — 當剛性規劃適得其反時,用於靈活探索。任何智能體都可以透過明確的交接機制將控制權轉移給任何其他智能體。
  • 階層式 — 用於具有分層抽象(策略、規劃、執行)的大型專案。每個層級在不同的細節層次上運作,並有自己的上下文結構。

圍繞明確的協調協定、能抵抗諂媚行為的共識機制以及防止錯誤傳播級聯的失敗處理來設計每個多智能體系統。

詳細主題

為什麼採用多智能體架構

上下文瓶頸 當單一智能體的上下文被累積的歷史記錄、檢索到的文件和工具輸出填滿,導致效能下降時,就該採用多智能體架構。識別三種效能下降訊號:中間丟失效應(注意力對中間內容減弱)、注意力稀缺(競爭項目太多)和上下文污染(不相關的內容取代了有用的內容)。

將工作分割到多個上下文視窗,以便每個智能體都能在專注於其子任務的乾淨上下文中運作。在協調層聚合結果,而不讓任何單一上下文承擔全部負擔。

Token 經濟學的現實 預算必須考慮到顯著更高的 Token 成本。生產數據顯示,多智能體系統的成本可能遠高於單一智能體聊天(聲明-多智能體-Token-乘數)。

架構Token 乘數使用案例
單一智能體聊天基準線簡單查詢
帶工具的單一智能體高於基準線使用工具的任務
多智能體系統遠高於基準線複雜研究/協調

瀏覽智能體評估研究表明,Token 使用量、工具呼叫和模型選擇主導了效能差異(聲明-評估-BrowseComp-變異數)。這支持將多智能體設定與單一智能體基準進行比較,而不是假設增加智能體就會有幫助。

在設計架構的同時優先考慮模型選擇——升級到更好的模型通常比加倍 Token 預算帶來更大的效能提升。BrowseComp 數據顯示,模型品質的提升通常勝過單純增加 Token。將模型選擇和多智能體架構視為互補策略。

平行化的論點 將可並行的子任務分配給具有全新上下文的專用智能體,而不是在單一智能體中順序處理。一個需要跨多個獨立來源進行搜尋、分析不同文件或比較競爭方法的研究任務,將受益於並行執行。實際總耗時接近最長子任務的持續時間,而不是所有子任務的總和。

專業化的論點 為每個智能體配置其特定子任務所需的系統提示詞、工具和上下文。通用智能體必須在上下文中攜帶所有可能的配置,從而稀釋了注意力。專業化智能體只攜帶所需的內容,在為其領域最佳化的精簡上下文中運作。從協調器路由到專業化智能體,可以在不導致組合爆炸的情況下實現專業化。

架構模式

模式 1:監督者/協調者 部署一個維護全域狀態和軌跡的中央智能體,將使用者目標分解為子任務,並路由到適當的工作者。

使用者查詢 -> 監督者 -> [專家, 專家, 專家] -> 聚合 -> 最終輸出

在以下情況選擇此模式:任務有清晰的分解、需要跨領域協調,或需要人工監督很重要。

預期這些取捨:嚴格的工作流程控制和更容易的人機互動干預,但監督者上下文成為瓶頸,監督者故障會級聯影響所有工作者,並且出現"傳話遊戲"問題,即監督者錯誤地轉述子智能體的回應。

傳話遊戲問題與解決方案 預期監督者架構最初由於傳話遊戲問題(LangGraph 基準測試),效能比最佳化版本差約 50%。監督者轉述子智能體的回應,每次傳遞都會損失保真度。

透過實施一個 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 使用基於角色的流程結構和階層式團隊結構。

實用指導

失敗模式與緩解措施

失敗:監督者瓶頸 監督者積累了所有工作者的上下文,容易飽和和效能下降。

透過約束工作者的輸出模式,使其只返回精煉的摘要來緩解。使用檢查點來持久化監督者狀態,而無需在上下文中攜帶完整的歷史記錄。

失敗:協調開銷 智能體通訊消耗 Token 並引入延遲。複雜的協調可能會抵消平行化的好處。

透過明確的交接協定最小化通訊來緩解。盡可能批次處理結果。使用非同步通訊模式。衡量多智能體協調是否比使用更長上下文的單一智能體真正節省了時間。

失敗:發散 追求不同目標且沒有中央協調的智能體會偏離預期目標。

透過為每個智能體定義明確的目標邊界來緩解。實施收斂檢查,驗證是否朝著共享目標前進。設定智能體執行的生存時間限制,以防止無限制的探索。

失敗:錯誤傳播 一個智能體輸出中的錯誤會傳播給消費該輸出的下游智能體,導致結果越來越錯。

在將輸出傳遞給消費者之前驗證智能體輸出。實施帶有斷路器的重試邏輯。盡可能使用冪等操作。考慮添加一個驗證智能體,在其進入流程之前交叉檢查關鍵輸出。

範例

範例 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. Token 預算衝擊 — 多智能體架構可以消耗比典型單一智能體對話多幾個數量級的 Token。始終從單一智能體基線開始。
  4. 框架鎖定 — 框架特定的抽象會將你鎖定在特定的協調模式中。在承諾框架之前,先設計架構並定義介面。
  5. 假設的平行化 — 多智能體設定不會自動實現平行執行。確保子任務是真正獨立的,且協調開銷不會超過並行化的收益。
  6. 狀態一致性的挑戰 — 使用檔案系統或外部儲存進行共享狀態會引入一致性問題,這些問題在訊息傳遞模式中不存在。做好處理競爭條件和過期狀態的準備。

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.

相關技能