{
  "metadata": {
    "id": "ch32",
    "title": "第32章 多Agent编排模式",
    "volume": "vol9",
    "volume_title": "Agent设计模式",
    "word_count": 5062,
    "difficulty": "advanced",
    "prerequisites": [
      "ch08"
    ],
    "key_concepts": [
      "概述",
      "Orchestrator 模式（中心编排）",
      "意图",
      "动机",
      "结构",
      "参与者",
      "协作",
      "效果",
      "实现",
      "适用场景",
      "相关模式",
      "Blackboard 模式",
      "Pipeline 模式",
      "Swarm 模式",
      "Hierarchical 模式"
    ],
    "learning_objectives": [],
    "estimated_tokens": 3037,
    "source_file": "vol9/ch32_多Agent编排模式.md"
  },
  "overview": "",
  "sections": [
    {
      "id": "32.1",
      "title": "32.1 概述",
      "level": 2,
      "content": "当单个Agent的能力不足以处理复杂任务时，我们需要多个Agent协同工作。多Agent编排模式关注的是**如何组织和管理多个Agent之间的协作关系**，使它们作为一个整体发挥出超越个体的能力。\n\n本章探讨六种核心的多Agent编排模式：Orchestrator、Blackboard、Pipeline、Swarm、Hierarchical 和 Peer-to-Peer。这些模式从\"中心化→去中心化\"、\"静态→动态\"、\"顺序→并行\"等多个维度提供了不同的编排策略。\n\n选择合适的编排模式取决于以下关键因素：\n- **任务性质**：任务是否可分解、是否有依赖关系\n- **Agent同质性**：Agent是相同的还是各有所长\n- **实时性要求**：是否需要低延迟响应\n- **容错需求**：单个Agent失败时系统是否必须继续运行\n- **可扩展性**：是否需要动态增减Agent数量\n\n**模式选择决策树：**\n\n\n---",
      "subsections": []
    },
    {
      "id": "32.2",
      "title": "32.2 Orchestrator 模式（中心编排）",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "通过一个**中央编排器（Orchestrator）**来协调多个专业Agent的执行，由编排器负责任务分解、Agent选择、结果整合和流程控制。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "在面对复杂任务时，一个自然的方式是引入一个\"管理者\"角色——它不一定亲自执行具体工作，但知道\"谁最适合做什么\"以及\"应该按什么顺序做\"。这就是Orchestrator模式的核心思想。\n\nOrchestrator模式类似于软件架构中的\"Facade（外观）模式\"或\"Mediator（中介者）模式\"：它为外部调用者提供了一个简单的入口，但内部协调着多个专业组件的复杂交互。这种模式在企业级AI系统中最为常见——用户只需要和一个入口对话，背后由多个专业Agent协同完成。\n\nLangChain的 AgentExecutor、AutoGen的 GroupChatManager、CrewAI的 Manager 都在不同程度上实现了这种模式。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Orchestrator**：中央编排器，负责任务分解和Agent调度\n- **Agent Pool**：可用的专业Agent集合\n- **Task Queue**：任务队列，存储待执行和已完成的任务\n- **Context Store**：共享上下文存储，Agent之间通过它传递中间结果"
        },
        {
          "id": "协作",
          "title": "协作",
          "content": "1. Orchestrator接收用户请求，将其分解为子任务\n2. 根据每个子任务的性质选择最合适的Agent\n3. 按照依赖关系编排执行顺序（串行、并行或混合）\n4. 收集各Agent的执行结果，整合为最终答案\n5. 返回结果给用户"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：**\n- 流程可控——编排器完全掌控执行流程\n- 结果质量高——可以选择最佳Agent执行每个子任务\n- 易于调试——编排器记录完整的执行日志\n- 支持复杂的工作流（条件分支、循环、并行）\n\n**缺点：**\n- 编排器是单点故障\n- 编排器的能力瓶颈——编排器的\"规划能力\"限制了系统的上限\n- 灵活性受限——新Agent需要注册到编排器才能使用\n- 上下文传递开销大"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 需要多个专业Agent协同完成的复杂任务\n- 任务有明确的分解和依赖关系\n- 需要细粒度控制和审计的工作流"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Hierarchical**：Orchestrator是扁平编排，Hierarchical是层级编排\n- **Pipeline**：Orchestrator的并行能力可替代简单的Pipeline\n- **Blackboard**：Orchestrator主动调度，Blackboard被动通信\n\n---"
        }
      ]
    },
    {
      "id": "32.3",
      "title": "32.3 Blackboard 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "提供一个**共享的黑板（Blackboard）**作为Agent之间的通信媒介，各Agent独立监听黑板上的信息变化，自主决定是否参与处理。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "Blackboard模式起源于人工智能的早期研究（H.P. Nii, 1986），最初用于语音识别系统 Hearsay-II。其核心思想是：**不告诉Agent做什么，而是让Agent自己判断是否该做什么**。黑板上的内容变化就像是一个\"公告栏\"，所有Agent都可以看到，但只有认为自己能够做出贡献的Agent才会行动。\n\n这种模式特别适合问题求解路径不确定、需要\"机会主义\"求解的场景。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Blackboard**：共享数据结构，存储问题状态和中间结果\n- **Knowledge Sources（Agent）**：独立的Agent，各自擅长不同领域\n- **Controller**：监控黑板状态，判断终止条件"
        },
        {
          "id": "协作",
          "title": "协作",
          "content": "1. Controller将初始问题写入黑板\n2. 所有Agent监听黑板变化，满足条件的Agent被激活\n3. 被激活的Agent处理信息，将结果写回黑板\n4. 新信息可能触发其他Agent\n5. 重复直到达到终止条件"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 高度解耦、支持增量求解、新Agent可随时加入、天然支持并行\n**缺点：** 终止条件难确定、黑板可能成为性能瓶颈、行为不可预测"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 问题求解路径不确定（诊断系统、创意生成）\n- 需要增量式构建解决方案\n- 研究型AI系统（假设生成与验证）"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Orchestrator**：主动调度 vs 被动监听\n- **Swarm**：黑板间接通信 vs 直接通信\n\n---"
        }
      ]
    },
    {
      "id": "32.4",
      "title": "32.4 Pipeline 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "将多个Agent组织为**流水线**，数据按固定顺序流经每个处理阶段，每个Agent专注于处理数据的某个方面。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "许多数据处理任务具有天然的阶段性——先清洗、再转换、后分析。Pipeline模式借鉴了Unix管道的设计哲学：每个Agent做一件简单的事，通过串联组合完成复杂任务。核心优势在于**简单性和可预测性**。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Pipeline**：流水线管理器\n- **Stage**：处理阶段\n- **PipelineContext**：在Stage之间传递的上下文"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 简单直观、Stage可独立测试、便于添加/移除Stage\n**缺点：** 缺乏灵活性、整体延迟为各Stage之和、单Stage失败可能中断Pipeline"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 数据处理流水线（ETL）\n- 文档处理（翻译→摘要→格式化）\n- 内容审核（过滤→分类→标注）"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Orchestrator**：Pipeline固定流程 vs Orchestrator动态调度\n\n---"
        }
      ]
    },
    {
      "id": "32.5",
      "title": "32.5 Swarm 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "让多个**同质或半同质的Agent**以**群体智能（Swarm Intelligence）**的方式协作，通过简单的局部交互涌现出复杂的全局行为。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "Swarm模式借鉴自然界蜂群的集体智慧：没有中央控制，每个个体遵循简单规则，但整体能完成复杂任务。OpenAI的 Swarm 框架（2024）是这种模式的代表实现。\n\n核心机制是**Handoff（交接）**——Agent可以将任务移交给另一个更合适的Agent，形成灵活的协作链。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Swarm Agents**：轻量级、可互换的Agent节点\n- **Handoff Protocol**：任务交接协议"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 高度可扩展、鲁棒性强、无单点故障、负载自然均衡\n**缺点：** 行为难预测、调试困难、可能循环交接、全局一致性难保证"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 客服系统（多技能坐席协作）\n- 需要高可扩展性和容错的系统"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Peer-to-Peer**：Swarm通过Handoff协作，P2P通过直接消息协作\n- **Orchestrator**：Swarm去中心化，Orchestrator中心化\n\n---"
        }
      ]
    },
    {
      "id": "32.6",
      "title": "32.6 Hierarchical 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "将Agent组织为**层级结构**，上层Agent负责管理和协调下层Agent，形成类似组织架构的\"管理者-执行者\"关系。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "面对极其复杂的任务，单一的Orchestrator可能力不从心，需要多级管理来处理不同粒度的子任务。MetaGPT（2023）是典型实现：模拟软件公司组织架构（产品经理→架构师→工程师→QA），通过层级协作完成开发任务。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Manager Agent**：上层，任务分解和分配\n- **Team Lead**：中层，管理Worker\n- **Worker Agent**：底层，执行具体任务"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 支持复杂任务分解、职责明确、可扩展\n**缺点：** 层级过深增加延迟、信息传递可能丢失上下文、错误级联"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 大型复杂项目\n- 企业多部门协作\n- 需要多级审批的工作流"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Orchestrator**：Hierarchical是多层级版本\n- **Plan-and-Execute**：天然支持计划-执行范式\n\n---"
        }
      ]
    },
    {
      "id": "32.7",
      "title": "32.7 Peer-to-Peer 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "让Agent以**对等（Peer-to-Peer）**的方式直接通信和协作，没有中心控制器，所有Agent地位平等。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "Orchestrator和Hierarchical模式都依赖中心节点，这引入了单点故障和性能瓶颈。P2P模式借鉴分布式计算的P2P网络思想：每个Agent既是客户端也是服务端，可以主动发起请求也可以响应请求。\n\n这种模式特别适合分布式部署、边缘计算和需要强鲁棒性的场景。IPFS、BitTorrent等系统已经证明了P2P架构的可行性。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Peer Agent**：对等节点，既是请求发起者也是响应者\n- **Message Bus**：消息传递基础设施\n- **Discovery Service**：Agent发现服务（可选）"
        },
        {
          "id": "协作",
          "title": "协作",
          "content": "1. Peer A有任务需要协助\n2. Peer A通过消息总线广播请求或直接联系已知Peer\n3. 有能力的Peer响应并提供结果\n4. 结果通过消息总线返回给Peer A"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：**\n- 无单点故障——去中心化架构\n- 高可扩展性——Peer可以随时加入或离开\n- 强鲁棒性——部分节点故障不影响整体\n- 低延迟——直接通信无需经过中心节点\n\n**缺点：**\n- 全局协调困难——缺乏中心控制\n- 一致性保证复杂——分布式一致性问题\n- 安全性挑战——需要信任机制\n- 调试困难——分布式调试的天然复杂性"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 分布式AI系统（跨区域部署）\n- 边缘计算场景\n- 需要强鲁棒性和自愈能力的系统\n- 联邦学习、隐私计算"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Swarm**：P2P通过消息总线通信，Swarm通过Handoff交接\n- **Orchestrator**：P2P完全去中心化，Orchestrator完全中心化\n- **Blackboard**：P2P直接通信，Blackboard通过共享空间间接通信\n\n---"
        }
      ]
    },
    {
      "id": "32.8",
      "title": "32.8 模式对比与选择",
      "level": 2,
      "content": "本章介绍的六种多Agent编排模式各有优劣，适用于不同的场景。下表从多个维度进行了对比：\n\n| 维度 | Orchestrator | Blackboard | Pipeline | Swarm | Hierarchical | P2P |\n|------|:-----------:|:----------:|:--------:|:-----:|:------------:|:---:|\n| 中心化程度 | 高 | 低 | 中 | 低 | 高 | 无 |\n| 灵活性 | 中 | 高 | 低 | 高 | 中 | 高 |\n| 可预测性 | 高 | 低 | 高 | 低 | 中 | 低 |\n| 容错性 | 低 | 中 | 低 | 高 | 低 | 高 |\n| 可扩展性 | 中 | 高 | 中 | 高 | 中 | 高 |\n| 调试难度 | 低 | 高 | 低 | 高 | 中 | 高 |\n| 适用规模 | 小-中 | 中-大 | 小-中 | 大 | 大 | 大 |\n\n**实践建议：**\n\n1. **从小开始**：先用Orchestrator或Pipeline验证方案，再考虑更复杂的模式\n2. **混合使用**：不同层级可以使用不同的编排模式（如上层Orchestrator，下层Pipeline）\n3. **关注可观测性**：无论哪种模式，都需要完善的日志和监控\n4. **渐进式演进**：随着系统复杂度增长，逐步引入更复杂的编排模式\n\n---\n\n*\"如果我们把每个Agent看作一个神经元，那么多Agent系统就是一个神经网络。智能不在于单个神经元，而在于它们之间的连接方式。\"*",
      "subsections": []
    }
  ],
  "code_blocks": [
    {
      "id": "code-1",
      "language": "text",
      "description": "模式选择决策树：",
      "code": "任务能否预先分解？\n├── 是 → 有固定执行顺序？\n│   ├── 是 → Pipeline模式\n│   └── 否 → Orchestrator模式\n└── 否 → Agent之间地位是否平等？\n    ├── 是 → 通信机制？\n    │   ├── 直接通信 → Swarm / Peer-to-Peer\n    │   └── 间接通信 → Blackboard\n    └── 否 → 有明确层级关系？ → Hierarchical模式",
      "section_ref": "32.1",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-2",
      "language": "text",
      "description": "LangChain的 AgentExecutor、AutoGen的 GroupChatManager、CrewAI的 Manager 都在不同程度上实现了这种模式。",
      "code": "┌──────────────────────────────────────────────┐\n│            Orchestrator System                │\n│                                              │\n│  User ──▶ ┌──────────────┐                  │\n│           │ Orchestrator │                  │\n│           │  (编排器)      │                  │\n│           └──────┬───────┘                  │\n│                  │                           │\n│    ┌─────┬───────┼───────┬─────┐           │\n│    ▼     ▼       ▼       ▼     ▼           │\n│ ┌────┐┌────┐ ┌────┐ ┌────┐ ┌────┐          │\n│ │Agent││Agent│ │Agent│ │Agent│ │Agent│      │\n│ │ A  ││ B  │ │ C  │ │ D  │ │ E  │          │\n│ │(搜索)││(分析)│ │(写作)│ │(审核)│ │(翻译)│     │\n│ └────┘└────┘ └────┘ └────┘ └────┘          │\n│                                              │\n│  编排策略: 串行/并行/条件分支/循环            │\n└──────────────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-3",
      "language": "python",
      "description": "- 上下文传递开销大",
      "code": "\"\"\"\nOrchestrator 模式 - 中心编排实现\n\"\"\"\nfrom typing import List, Dict, Optional, Callable, Any\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport json\n\n\nclass TaskStatus(Enum):\n    PENDING = \"pending\"\n    RUNNING = \"running\"\n    COMPLETED = \"completed\"\n    FAILED = \"failed\"\n\n\n@dataclass\nclass SubTask:\n    task_id: str\n    description: str\n    assigned_agent: Optional[str] = None\n    depends_on: List[str] = field(default_factory=list)\n    status: TaskStatus = TaskStatus.PENDING\n    result: Any = None\n\n\n@dataclass\nclass AgentNode:\n    name: str\n    description: str\n    capabilities: List[str]\n    handler: Callable\n\n\nclass Orchestrator:\n    \"\"\"Orchestrator - 中心编排器，支持串行、并行和条件编排。\"\"\"\n    \n    def __init__(self, llm_client, max_parallel: int = 3, verbose: bool = False):\n        self.llm = llm_client\n        self.agents: Dict[str, AgentNode] = {}\n        self.max_parallel = max_parallel\n        self.verbose = verbose\n    \n    def register_agent(self, agent: AgentNode) -> None:\n        self.agents[agent.name] = agent\n    \n    def decompose_task(self, user_request: str) -> List[SubTask]:\n        agent_list = \"\\n\".join(\n            f\"- {n}: {a.description}\" for n, a in self.agents.items()\n        )\n        prompt = f\"\"\"将请求分解为子任务并分配Agent。\n请求: {user_request}\n可用Agent: {agent_list}\n返回JSON: {{\"tasks\": [{{\"task_id\":\"t1\",\"description\":\"...\",\n\"assigned_agent\":\"name\",\"depends_on\":[]}}]}}\"\"\"\n        \n        response = self.llm.chat([{\"role\": \"user\", \"content\": prompt}])\n        try:\n            import re\n            m = re.search(r'\\{.*\\}', response, re.DOTALL)\n            if m:\n                data = json.loads(m.group(0))\n                return [SubTask(t[\"task_id\"], t[\"description\"],\n                    t.get(\"assigned_agent\"), t.get(\"depends_on\", []))\n                    for t in data[\"tasks\"]]\n        except (json.JSONDecodeError, KeyError):\n            pass\n        return [SubTask(\"t1\", user_request)]\n    \n    def execute(self, user_request: str) -> Dict[str, Any]:\n        tasks = self.decompose_task(user_request)\n        context: Dict[str, Any] = {}\n        remaining = list(tasks)\n        \n        for _ in range(len(tasks) * 2):\n            ready = [t for t in remaining\n                     if all(context.get(d) is not None for d in t.depends_on)]\n            if not ready:\n                break\n            \n            with ThreadPoolExecutor(max_workers=min(self.max_parallel, len(ready))) as ex:\n                futures = {}\n                for t in ready:\n                    agent = self.agents.get(t.assigned_agent) or list(self.agents.values())[0]\n                    deps = {d: context[d] for d in t.depends_on if d in context}\n                    futures[ex.submit(agent.handler, t.description, deps)] = t\n                \n                for f in as_completed(futures):\n                    task = futures[f]\n                    try:\n                        context[task.task_id] = f.result()\n                        task.status = TaskStatus.COMPLETED\n                    except Exception:\n                        task.status = TaskStatus.FAILED\n                    if task in remaining:\n                        remaining.remove(task)\n        \n        return {\n            \"results\": context,\n            \"completed\": len([t for t in tasks if t.status == TaskStatus.COMPLETED])\n        }",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": [
        "concurrent"
      ]
    },
    {
      "id": "code-4",
      "language": "text",
      "description": "这种模式特别适合问题求解路径不确定、需要\"机会主义\"求解的场景。",
      "code": "┌──────────────────────────────────────────┐\n│           Blackboard System              │\n│        ┌─────────────────┐              │\n│        │   Blackboard     │              │\n│        │  hypothesis/数据  │              │\n│        │  partial_solution │              │\n│        └────────┬────────┘              │\n│    ┌────────────┼────────────┐         │\n│    ▼            ▼            ▼         │\n│ ┌──────┐   ┌──────┐    ┌──────┐       │\n│ │Agent │   │Agent │    │Agent │       │\n│ │(监听) │   │(监听) │    │(监听) │       │\n│ └──────┘   └──────┘    └──────┘       │\n└──────────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-5",
      "language": "python",
      "description": "缺点： 终止条件难确定、黑板可能成为性能瓶颈、行为不可预测",
      "code": "\"\"\"\nBlackboard 模式实现\n\"\"\"\nfrom typing import List, Dict, Optional, Callable, Any\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom threading import Lock\nimport time\n\n\nclass EntryType(Enum):\n    PROBLEM = \"problem\"\n    HYPOTHESIS = \"hypothesis\"\n    SOLUTION = \"solution\"\n\n\n@dataclass\nclass BlackboardEntry:\n    entry_id: str\n    entry_type: EntryType\n    content: Any\n    confidence: float = 0.0\n    source: str = \"\"\n    timestamp: float = field(default_factory=time.time)\n\n\nclass KnowledgeSource:\n    def __init__(self, name: str, can_contribute: Callable, process: Callable):\n        self.name = name\n        self.can_contribute = can_contribute\n        self.process = process\n\n\nclass Blackboard:\n    def __init__(self):\n        self._entries: Dict[str, BlackboardEntry] = {}\n        self._lock = Lock()\n    \n    def write(self, entry: BlackboardEntry) -> None:\n        with self._lock:\n            self._entries[entry.entry_id] = entry\n    \n    def read_all(self, entry_type: EntryType = None) -> List[BlackboardEntry]:\n        with self._lock:\n            entries = list(self._entries.values())\n        return [e for e in entries if entry_type is None or e.entry_type == entry_type]\n    \n    def has_solution(self, min_conf: float = 0.8) -> bool:\n        return any(e.entry_type == EntryType.SOLUTION and e.confidence >= min_conf\n                   for e in self._entries.values())\n\n\nclass BlackboardController:\n    def __init__(self, bb: Blackboard, max_rounds: int = 20):\n        self.bb = bb\n        self.sources: List[KnowledgeSource] = []\n        self.max_rounds = max_rounds\n    \n    def solve(self, problem: str) -> Dict:\n        self.bb.write(BlackboardEntry(\"p0\", EntryType.PROBLEM, problem, 1.0))\n        \n        for _ in range(self.max_rounds):\n            if self.bb.has_solution():\n                break\n            for src in self.sources:\n                entries = self.bb.read_all()\n                if src.can_contribute(entries):\n                    for e in (src.process(entries) or []):\n                        self.bb.write(e)\n        \n        sols = self.bb.read_all(EntryType.SOLUTION)\n        return {\"solutions\": [{\"content\": s.content, \"confidence\": s.confidence} for s in sols]}",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": [
        "threading"
      ]
    },
    {
      "id": "code-6",
      "language": "text",
      "description": "许多数据处理任务具有天然的阶段性——先清洗、再转换、后分析。Pipeline模式借鉴了Unix管道的设计哲学：每个Agent做一件简单的事，通过串联组合完成复杂任务。核心优势在于简单性和可预测性。",
      "code": "Input ──▶ [Stage 1: 清洗] ──▶ [Stage 2: 转换] ──▶ [Stage 3: 输出] ──▶ Output",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-7",
      "language": "python",
      "description": "缺点： 缺乏灵活性、整体延迟为各Stage之和、单Stage失败可能中断Pipeline",
      "code": "\"\"\"Pipeline 模式实现\"\"\"\nfrom typing import List, Optional, Callable, Any\nfrom dataclasses import dataclass, field\nimport time\n\n\n@dataclass\nclass PipelineContext:\n    data: Any\n    metadata: Dict[str, Any] = field(default_factory=dict)\n    errors: List[str] = field(default_factory=list)\n    stage_results: Dict[str, Any] = field(default_factory=dict)\n\n\n@dataclass\nclass PipelineStage:\n    name: str\n    process: Callable[[PipelineContext], PipelineContext]\n    condition: Optional[Callable[[PipelineContext], bool]] = None\n    on_error: str = \"stop\"\n\n\nclass Pipeline:\n    \"\"\"Pipeline - 流水线管理器\"\"\"\n    def __init__(self, name: str = \"default\", verbose: bool = False):\n        self.name = name\n        self.stages: List[PipelineStage] = []\n        self.verbose = verbose\n    \n    def add_stage(self, stage: PipelineStage) -> 'Pipeline':\n        self.stages.append(stage)\n        return self\n    \n    def execute(self, input_data: Any) -> PipelineContext:\n        ctx = PipelineContext(data=input_data)\n        for i, stage in enumerate(self.stages):\n            if stage.condition and not stage.condition(ctx):\n                continue\n            start = time.time()\n            try:\n                ctx = stage.process(ctx)\n                ctx.stage_results[stage.name] = {\"status\": \"ok\",\n                    \"ms\": (time.time() - start) * 1000}\n            except Exception as e:\n                ctx.errors.append(f\"{stage.name}: {e}\")\n                if stage.on_error == \"stop\":\n                    break\n        return ctx",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-8",
      "language": "text",
      "description": "核心机制是Handoff（交接）——Agent可以将任务移交给另一个更合适的Agent，形成灵活的协作链。",
      "code": "┌──────────────────────────────────────┐\n│          Swarm System                 │\n│  ┌──────┐  ┌──────┐  ┌──────┐      │\n│  │Agent │◀▶│Agent │◀▶│Agent │      │\n│  │ A    │  │ B    │  │ C    │      │\n│  └──────┘  └──────┘  └──────┘      │\n│       通过 Handoff 协议交接任务        │\n└──────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-9",
      "language": "python",
      "description": "缺点： 行为难预测、调试困难、可能循环交接、全局一致性难保证",
      "code": "\"\"\"Swarm 模式实现\"\"\"\nfrom typing import Dict, Optional, Callable\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass AgentConfig:\n    name: str\n    handler: Callable\n    can_handoff_to: list = field(default_factory=list)\n\n\n@dataclass\nclass Handoff:\n    target: str\n    reason: str = \"\"\n\n\nclass SwarmAgent:\n    def __init__(self, config: AgentConfig):\n        self.name = config.name\n        self.handler = config.handler\n        self.can_handoff_to = config.can_handoff_to\n\n\nclass Swarm:\n    \"\"\"Swarm - 群体智能管理器\"\"\"\n    def __init__(self, max_handoffs: int = 10, verbose: bool = False):\n        self.agents: Dict[str, SwarmAgent] = {}\n        self.max_handoffs = max_handoffs\n        self.verbose = verbose\n    \n    def add_agent(self, config: AgentConfig) -> 'Swarm':\n        self.agents[config.name] = SwarmAgent(config)\n        return self\n    \n    def run(self, message: str, entry: str = None) -> dict:\n        current = self.agents[entry or list(self.agents.keys())[0]]\n        handoffs = 0\n        visited = [current.name]\n        \n        while handoffs <= self.max_handoffs:\n            response, handoff = current.handler(current, message, self.agents)\n            if not handoff:\n                break\n            if handoff.target in visited or handoff.target not in self.agents:\n                break\n            visited.append(handoff.target)\n            current = self.agents[handoff.target]\n            message = response\n            handoffs += 1\n        \n        return {\"response\": response, \"chain\": visited, \"handoffs\": handoffs}",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-10",
      "language": "text",
      "description": "面对极其复杂的任务，单一的Orchestrator可能力不从心，需要多级管理来处理不同粒度的子任务。MetaGPT（2023）是典型实现：模拟软件公司组织架构（产品经理→架构师→工程师→QA），通过层",
      "code": "         ┌──────────┐\n         │ Manager  │\n         └────┬─────┘\n      ┌───────┼───────┐\n      ▼       ▼       ▼\n   [Lead A] [Lead B] [Lead C]\n    ┌─┴─┐    ┌─┴─┐\n   [W] [W]  [W] [W]",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-11",
      "language": "python",
      "description": "缺点： 层级过深增加延迟、信息传递可能丢失上下文、错误级联",
      "code": "\"\"\"Hierarchical 模式实现\"\"\"\nfrom typing import Dict, Any, Callable, List\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nimport json\n\n\nclass Level(Enum):\n    MANAGER = \"manager\"\n    LEAD = \"lead\"\n    WORKER = \"worker\"\n\n\n@dataclass\nclass HierarchyNode:\n    name: str\n    level: Level\n    handler: Callable = None\n    children: List['HierarchyNode'] = field(default_factory=list)\n    \n    def add_child(self, child: 'HierarchyNode'):\n        self.children.append(child)\n        return child\n\n\nclass HierarchicalSystem:\n    def __init__(self, root: HierarchyNode, verbose: bool = False):\n        self.root = root\n        self.verbose = verbose\n    \n    def _exec(self, node: HierarchyNode, task: str, ctx=None) -> Any:\n        ctx = ctx or {}\n        if not node.children:\n            return node.handler(task, ctx) if node.handler else task\n        if node.handler:\n            return node.handler(node, task, ctx)\n        return {c.name: self._exec(c, task, ctx) for c in node.children}\n    \n    def execute(self, task: str) -> Any:\n        return self._exec(self.root, task)\n\n\n# 示例：模拟软件公司\nroot = HierarchyNode(\"CEO\", Level.MANAGER,\n    lambda n, t, c: {ch.name: ch.handler(ch, t, c) if ch.handler else None\n                      for ch in n.children})\ntech = root.add_child(HierarchyNode(\"CTO\", Level.LEAD,\n    lambda n, t, c: {ch.name: ch.handler(t, c) for ch in n.children}))\ntech.add_child(HierarchyNode(\"前端\", Level.WORKER, lambda t, c: f\"[前端] {t}\"))\ntech.add_child(HierarchyNode(\"后端\", Level.WORKER, lambda t, c: f\"[后端] {t}\"))",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-12",
      "language": "text",
      "description": "这种模式特别适合分布式部署、边缘计算和需要强鲁棒性的场景。IPFS、BitTorrent等系统已经证明了P2P架构的可行性。",
      "code": "┌──────────────────────────────────────┐\n│       Peer-to-Peer Network            │\n│  ┌──────┐   ┌──────┐   ┌──────┐    │\n│  │Peer A│◀─▶│Peer B│◀─▶│Peer C│    │\n│  └──┬───┘   └──┬───┘   └──┬───┘    │\n│     │           │          │         │\n│     └───────────┼──────────┘         │\n│                 ▼                     │\n│         [Message Bus / Gossip]        │\n│                                       │\n│  ┌──────┐   ┌──────┐                 │\n│  │Peer D│◀─▶│Peer E│                 │\n│  └──────┘   └──────┘                 │\n└──────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-13",
      "language": "python",
      "description": "- 调试困难——分布式调试的天然复杂性",
      "code": "\"\"\"Peer-to-Peer 模式实现\"\"\"\nfrom typing import Dict, List, Callable, Any, Optional\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nimport uuid\nimport time\n\n\n@dataclass\nclass PeerMessage:\n    msg_id: str\n    sender: str\n    content: Any\n    msg_type: str = \"request\"  # request, response, broadcast\n    target: Optional[str] = None\n    timestamp: float = field(default_factory=time.time)\n\n\nclass PeerAgent:\n    \"\"\"P2P Agent节点\"\"\"\n    def __init__(self, name: str, capabilities: List[str],\n                 handler: Callable, verbose: bool = False):\n        self.name = name\n        self.capabilities = capabilities\n        self.handler = handler\n        self.verbose = verbose\n        self.peers: Dict[str, 'PeerAgent'] = {}\n        self.message_log: List[Dict] = []\n    \n    def connect(self, peer: 'PeerAgent') -> None:\n        \"\"\"连接到其他Peer\"\"\"\n        self.peers[peer.name] = peer\n        peer.peers[self.name] = self\n    \n    def send(self, target_name: str, content: Any) -> Optional[Any]:\n        \"\"\"直接发送消息给指定Peer\"\"\"\n        if target_name not in self.peers:\n            return None\n        \n        msg = PeerMessage(str(uuid.uuid4()), self.name, content, \"request\", target_name)\n        self.message_log.append({\"role\": \"sender\", \"msg_id\": msg.msg_id, \"target\": target_name})\n        \n        peer = self.peers[target_name]\n        response = peer.handler(msg)\n        \n        peer.message_log.append({\"role\": \"receiver\", \"msg_id\": msg.msg_id, \"from\": self.name})\n        return response\n    \n    def broadcast(self, content: Any) -> Dict[str, Any]:\n        \"\"\"广播消息给所有连接的Peer\"\"\"\n        msg = PeerMessage(str(uuid.uuid4()), self.name, content, \"broadcast\")\n        results = {}\n        for name, peer in self.peers.items():\n            response = peer.handler(msg)\n            results[name] = response\n        return results\n    \n    def handle_request(self, msg: PeerMessage) -> Any:\n        \"\"\"处理收到的请求\"\"\"\n        return self.handler(msg)\n\n\nclass PeerNetwork:\n    \"\"\"P2P 网络管理器\"\"\"\n    def __init__(self, verbose: bool = False):\n        self.peers: Dict[str, PeerAgent] = {}\n        self.verbose = verbose\n    \n    def add_peer(self, peer: PeerAgent) -> None:\n        self.peers[peer.name] = peer\n    \n    def connect_all(self) -> None:\n        \"\"\"全连接拓扑\"\"\"\n        names = list(self.peers.keys())\n        for i, n1 in enumerate(names):\n            for n2 in names[i+1:]:\n                self.peers[n1].connect(self.peers[n2])\n    \n    def find_peer(self, capability: str) -> Optional[PeerAgent]:\n        \"\"\"按能力查找Peer\"\"\"\n        for peer in self.peers.values():\n            if capability in peer.capabilities:\n                return peer\n        return None\n\n\ndef demo_p2p():\n    def search_handler(msg):\n        return f\"[搜索结果] {msg.content}\"\n    \n    def analyze_handler(msg):\n        return f\"[分析报告] {msg.content}\"\n    \n    network = PeerNetwork()\n    peer_a = PeerAgent\n    peer_a = PeerAgent(\"A\", [\"search\"], search_handler)\n    peer_b = PeerAgent(\"B\", [\"analyze\"], analyze_handler)\n    network.add_peer(peer_a)\n    network.add_peer(peer_b)\n    network.connect_all()\n    result = peer_a.send(\"B\", \"分析这段数据\")\n    print(f\"P2P结果: {result}\")",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    }
  ],
  "tables": [
    {
      "headers": [
        "维度",
        "Orchestrator",
        "Blackboard",
        "Pipeline",
        "Swarm",
        "Hierarchical",
        "P2P"
      ],
      "data": [
        [
          "中心化程度",
          "高",
          "低",
          "中",
          "低",
          "高",
          "无"
        ],
        [
          "灵活性",
          "中",
          "高",
          "低",
          "高",
          "中",
          "高"
        ],
        [
          "可预测性",
          "高",
          "低",
          "高",
          "低",
          "中",
          "低"
        ],
        [
          "容错性",
          "低",
          "中",
          "低",
          "高",
          "低",
          "高"
        ],
        [
          "可扩展性",
          "中",
          "高",
          "中",
          "高",
          "中",
          "高"
        ],
        [
          "调试难度",
          "低",
          "高",
          "低",
          "高",
          "中",
          "高"
        ],
        [
          "适用规模",
          "小-中",
          "中-大",
          "小-中",
          "大",
          "大",
          "大"
        ]
      ]
    }
  ],
  "key_takeaways": [],
  "common_pitfalls": [],
  "related_chapters": [
    "ch08",
    "ch30",
    "ch35"
  ]
}