{
  "metadata": {
    "id": "ch33",
    "title": "第33章 人机协作模式",
    "volume": "vol9",
    "volume_title": "Agent设计模式",
    "word_count": 4272,
    "difficulty": "advanced",
    "prerequisites": [
      "ch08"
    ],
    "key_concepts": [
      "概述",
      "Human-in-the-Loop 模式",
      "意图",
      "动机",
      "结构",
      "参与者",
      "协作",
      "效果",
      "实现",
      "适用场景",
      "相关模式",
      "Human-on-the-Loop 模式",
      "Human-over-the-Loop 模式",
      "Approval Gate 模式",
      "Delegation 模式"
    ],
    "learning_objectives": [],
    "estimated_tokens": 2563,
    "source_file": "vol9/ch33_人机协作模式.md"
  },
  "overview": "",
  "sections": [
    {
      "id": "33.1",
      "title": "33.1 概述",
      "level": 2,
      "content": "Agent系统的最终目标不是完全自主运行，而是与人类高效协作。在大多数实际应用中，完全自主的Agent要么不可靠（安全风险），要么不必要（人类参与能提升结果质量）。人机协作模式解决的核心问题是：**在什么时机、以什么方式让人类参与Agent的工作流程**。\n\n本章探讨六种人机协作模式，它们按照人类参与的深度分为三个层次：\n\n- **Human-in-the-Loop**：人类深度参与，每次关键决策都需要人类确认\n- **Human-on-the-Loop**：人类监督运行，异常时介入\n- **Human-over-the-Loop**：人类高层控制，Agent自主执行\n\n此外还有三种补充模式：**Approval Gate**（审批关卡）、**Delegation**（任务委派）和**Escalation**（问题升级），它们分别从不同角度丰富了人机协作的工具箱。\n\n**选择协作模式的关键考量：**\n\n| 考量维度 | Human-in-the-Loop | Human-on-the-Loop | Human-over-the-Loop |\n|---------|:-:|:-:|:-:|\n| 人类参与频率 | 每次关键决策 | 异常时介入 | 仅设定目标 |\n| 适用风险等级 | 高 | 中 | 低 |\n| 人类时间成本 | 高 | 中 | 低 |\n| Agent自主性 | 低 | 中 | 高 |\n| 典型场景 | 医疗诊断 | 内容审核 | 数据报表 |\n\n---",
      "subsections": []
    },
    {
      "id": "33.2",
      "title": "33.2 Human-in-the-Loop 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "在Agent执行的**每个关键决策点**引入人类审查和确认，确保Agent的行为始终处于人类的直接控制之下。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "在高风险场景中——医疗诊断、法律建议、金融交易、军事决策——Agent的任何错误都可能导致严重后果。Human-in-the-Loop模式确保Agent不是\"自作主张\"，而是\"请示后行动\"。\n\n这种模式的本质是**信任但验证**：Agent负责生成建议或方案，人类负责审核和决策。Agent是\"参谋\"，人类是\"指挥官\"。\n\nMicrosoft的 Human-in-the-Loop AI 框架和IBM的 AI OpenScale 都将这种模式作为企业级AI部署的必备组件。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Agent**：生成建议或执行方案\n- **Human Reviewer**：审核Agent的建议并做出决策\n- **Approval Interface**：人类与Agent交互的界面\n- **Decision Log**：记录人类决策的审计日志"
        },
        {
          "id": "协作",
          "title": "协作",
          "content": "1. Agent分析任务，生成建议方案\n2. Agent将方案提交给人类审核\n3. 暂停执行，等待人类决策\n4. 人类审核方案，选择批准、修改或拒绝\n5. 根据人类决策继续执行或调整"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：**\n- 最大化安全性——每次关键决策都有人类把关\n- 人类可以纠正Agent的错误\n- 逐步建立对Agent的信任\n- 完整的审计追踪\n\n**缺点：**\n- 人类参与成本高——每次都需要人工\n- 响应延迟大——需要等待人类响应\n- 人类疲劳——频繁的审批请求导致注意力下降\n- 不适合高吞吐量场景"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 医疗诊断（诊断建议需医生确认）\n- 法律文档生成（需律师审核）\n- 金融交易（大额操作需人工确认）\n- 安全敏感操作（数据删除、权限变更）"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Human-on-the-Loop**：HitL每次决策需要人类，HotL只需异常时介入\n- **Approval Gate**：HitL的通用化版本，聚焦于审批机制\n- **Guardrails**（第31章）：Guardrails是自动化的规则检查，HitL是人类的检查\n\n---"
        }
      ]
    },
    {
      "id": "33.3",
      "title": "33.3 Human-on-the-Loop 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "让Agent**自主执行**大部分操作，人类作为**监督者**在系统出现异常、不确定或超过阈值时介入。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "Human-in-the-Loop虽然安全，但人类参与成本太高——想象一下如果每次邮件分类都需要人工审批，那就失去了自动化的意义。Human-on-the-Loop模式找到了一个平衡点：Agent自主处理大部分常规任务，只在\"不确定\"或\"高风险\"时才通知人类。\n\n这种模式类似于工厂中的\"质量检验员\"——不参与每一道工序，但在关键检查点抽检，发现问题时及时介入。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "参与者",
          "title": "参与者",
          "content": "- **Agent**：自主执行任务\n- **Anomaly Detector**：检测执行过程中的异常\n- **Human Supervisor**：人类监督者，接收异常通知并决定是否介入\n- **Alert System**：异常通知系统"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：**\n- 人类参与成本低——只在必要时介入\n- Agent自主性高——大部分操作自动完成\n- 适合高吞吐量场景\n\n**缺点：**\n- 异常检测的准确性影响体验\n- 人类可能错过紧急通知\n- 需要设计合理的通知策略避免\"报警疲劳\""
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 内容审核（大部分内容自动处理，可疑内容人工审核）\n- 数据标注（自动标注 + 人工抽检）\n- 客服系统（常见问题自动回复，复杂问题转人工）"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Human-in-the-Loop**：HotL是HitL的轻量版\n- **Escalation**：HotL的异常检测可以触发Escalation升级流程\n\n---"
        }
      ]
    },
    {
      "id": "33.4",
      "title": "33.4 Human-over-the-Loop 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "人类设定**高层目标和约束**，Agent完全自主地规划和执行，人类只在任务完成后审查结果或调整方向。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "对于低风险、高重复性的任务——如数据报表生成、日志分析、信息检索——人类的精细控制不仅不必要，还可能降低效率。Human-over-the-Loop模式让人类专注于\"做什么\"和\"为什么做\"，Agent负责\"怎么做\"。\n\n这种模式类似于管理者给团队分配任务：管理者说明目标和要求，团队自主决定执行方式。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 人类参与成本最低、Agent自主性最高、适合大规模自动化\n**缺点：** 人类对执行过程的控制力弱、错误可能在完成后才被发现"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 数据报表自动生成\n- 日志分析和异常检测\n- 信息检索和摘要\n- 自动化测试执行"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Plan-and-Execute**（第31章）：HoTL天然支持计划-执行范式\n- **Delegation**：HoTL是Delegation的一种形式\n\n---"
        }
      ]
    },
    {
      "id": "33.5",
      "title": "33.5 Approval Gate 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "在Agent工作流的**特定节点**设置审批关卡，只有在人类批准后才能继续执行后续步骤。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "Human-in-the-Loop在每个决策点都需要人类参与，粒度太细。Approval Gate模式允许你在工作流中精确地选择哪些节点需要审批——比如在\"发送邮件\"之前设置关卡，但在\"搜索信息\"时不需要。\n\n这种模式类似于企业审批流程中的\"签字盖章\"——不是每个步骤都需要签字，但在关键节点（如合同签署、资金拨付）必须有签字。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 精确控制审批粒度、审批策略可配置、支持多级审批\n**缺点：** 需要预先定义审批节点、新增关卡需要修改工作流"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 企业审批流程（请假、报销、采购）\n- 内容发布流程（文章发布前的审核）\n- 数据操作（删除、导出敏感数据前的确认）"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Human-in-the-Loop**：Approval Gate是HitL在工作流中的精确实现\n- **Escalation**：Gate拒绝后可以触发Escalation\n\n---"
        }
      ]
    },
    {
      "id": "33.6",
      "title": "33.6 Delegation 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "人类将**特定任务委派**给Agent执行，并设定明确的期望、约束和验收标准，Agent独立完成任务后汇报结果。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "Delegation模式模拟了人类组织中的任务委派：管理者将任务分配给下属，说明期望和约束，下属自主完成并汇报。在Agent系统中，人类将某些任务委派给Agent，同时保留对其他任务的直接控制。\n\n与Human-over-the-Loop不同的是，Delegation更强调**任务边界**的明确性——哪些任务可以委派，哪些必须人类亲自处理。"
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 任务边界清晰、人类保持最终控制权、Agent可以专注于委派的任务\n**缺点：** 委派粒度需要经验、不合适的委派可能导致返工"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 项目管理（将子任务分配给Agent）\n- 研究助手（委托Agent进行信息搜集）\n- 代码审查（委托Agent进行初步审查）"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Human-over-the-Loop**：Delegation是HoTL的具体化形式\n- **Escalation**：Agent发现任务超出能力时，可以反向委派给人类\n\n---"
        }
      ]
    },
    {
      "id": "33.7",
      "title": "33.7 Escalation 模式",
      "level": 2,
      "content": "",
      "subsections": [
        {
          "id": "意图",
          "title": "意图",
          "content": "当Agent遇到**自身无法处理的情况**时，按照预定义的规则将问题**升级**给更有能力的人类或其他Agent处理。"
        },
        {
          "id": "动机",
          "title": "动机",
          "content": "Agent的能力是有边界的。当遇到超出能力范围的问题——如需要人类判断的主观问题、缺少必要权限的操作、系统异常情况——Agent不应该盲目尝试，而应该及时\"求助\"。Escalation模式定义了何时升级、升级给谁、升级后如何处理的标准化流程。"
        },
        {
          "id": "结构",
          "title": "结构",
          "content": ""
        },
        {
          "id": "效果",
          "title": "效果",
          "content": "**优点：** 避免Agent做出错误决策、问题能及时得到专业处理、有明确的升级路径\n**缺点：** 升级规则设计复杂、可能过度升级导致人类负担"
        },
        {
          "id": "实现",
          "title": "实现",
          "content": ""
        },
        {
          "id": "适用场景",
          "title": "适用场景",
          "content": "- 客服系统（Agent无法解答时转人工）\n- 安全监控（检测到异常时升级给安全团队）\n- 运维系统（系统异常时升级给运维人员）"
        },
        {
          "id": "相关模式",
          "title": "相关模式",
          "content": "- **Human-on-the-Loop**：Escalation是HotL的具体触发机制\n- **Router**（第31章）：Router做常规分发，Escalation做异常分发\n\n---"
        }
      ]
    },
    {
      "id": "33.8",
      "title": "33.8 模式选择指南",
      "level": 2,
      "content": "本章介绍了六种人机协作模式，它们的核心差异在于**人类参与的时机和深度**：\n\n\n**实践原则：**\n\n1. **从严格到宽松**：系统初期使用Human-in-the-Loop，逐步过渡到Human-on-the-Loop\n2. **风险驱动**：高风险操作必须有人类参与，低风险操作可以让Agent自主\n3. **渐进信任**：随着Agent可靠性的提升，减少人类的参与频率\n4. **可观测性**：无论使用哪种模式，都要确保人类可以随时了解Agent的状态\n\n---\n\n*\"最好的工具不是让人类变得更少，而是让人类变得更强大。人机协作的未来不是替代，而是增强。\"*",
      "subsections": []
    }
  ],
  "code_blocks": [
    {
      "id": "code-1",
      "language": "text",
      "description": "Microsoft的 Human-in-the-Loop AI 框架和IBM的 AI OpenScale 都将这种模式作为企业级AI部署的必备组件。",
      "code": "┌─────────────────────────────────────────┐\n│        Human-in-the-Loop Flow            │\n│                                         │\n│  Agent ──▶ 生成方案 ──▶ ⏸️ 等待人类审批  │\n│                              │          │\n│                        ┌─────┴─────┐    │\n│                        ▼           ▼    │\n│                      ✅ 批准      ❌ 拒绝  │\n│                        │           │    │\n│                        ▼           ▼    │\n│                     继续执行    修改/重试  │\n│                                         │\n│  关键决策点: 数据输入、工具调用、最终输出  │\n└─────────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-2",
      "language": "python",
      "description": "- 不适合高吞吐量场景",
      "code": "\"\"\"\nHuman-in-the-Loop 模式实现\n\"\"\"\nfrom typing import Callable, Optional, Any, Dict\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nimport time\n\n\nclass Decision(Enum):\n    APPROVE = \"approve\"\n    REJECT = \"reject\"\n    MODIFY = \"modify\"\n\n\n@dataclass\nclass ApprovalRequest:\n    \"\"\"审批请求\"\"\"\n    request_id: str\n    agent_name: str\n    action_type: str\n    action_description: str\n    action_details: Dict[str, Any]\n    risk_level: str = \"medium\"  # low, medium, high, critical\n    context: str = \"\"\n\n\n@dataclass\nclass ApprovalResponse:\n    \"\"\"审批响应\"\"\"\n    request_id: str\n    decision: Decision\n    comment: str = \"\"\n    modified_details: Optional[Dict[str, Any]] = None\n    reviewer: str = \"human\"\n\n\nclass HumanInLoopAgent:\n    \"\"\"\n    Human-in-the-Loop Agent\n    \n    在关键决策点暂停执行，等待人类审批。\n    支持同步和异步审批模式。\n    \"\"\"\n    \n    def __init__(\n        self,\n        agent_name: str,\n        approval_callback: Callable[[ApprovalRequest], ApprovalResponse],\n        auto_approve_low_risk: bool = True,\n        verbose: bool = False\n    ):\n        self.agent_name = agent_name\n        self.approval_callback = approval_callback\n        self.auto_approve_low_risk = auto_approve_low_risk\n        self.verbose = verbose\n        self.approval_history: list = []\n    \n    def _request_approval(self, request: ApprovalRequest) -> ApprovalResponse:\n        \"\"\"请求人类审批\"\"\"\n        # 低风险自动批准\n        if self.auto_approve_low_risk and request.risk_level == \"low\":\n            if self.verbose:\n                print(f\"  ⚡ 低风险自动批准: {request.action_type}\")\n            return ApprovalResponse(\n                request.request_id, Decision.APPROVE,\n                \"自动批准（低风险）\", reviewer=\"auto\"\n            )\n        \n        if self.verbose:\n            print(f\"  ⏸️ 等待人类审批: {request.action_type} [{request.risk_level}]\")\n            print(f\"     详情: {request.action_description}\")\n        \n        response = self.approval_callback(request)\n        self.approval_history.append({\n            \"request\": request, \"response\": response,\n            \"timestamp\": time.time()\n        })\n        \n        status = \"✅\" if response.decision == Decision.APPROVE else \"❌\"\n        if self.verbose:\n            print(f\"  {status} 审批结果: {response.decision.value} - {response.comment}\")\n        \n        return response\n    \n    def execute_with_approval(self, action_type: str, action_fn: Callable,\n                               action_args: dict, risk_level: str = \"medium\",\n                               context: str = \"\") -> Any:\n        \"\"\"执行需要审批的操作\"\"\"\n        request = ApprovalRequest(\n            request_id=f\"{self.agent_name}_{int(time.time())}\",\n            agent_name=self.agent_name,\n            action_type=action_type,\n            action_description=action_fn.__doc__ or action_type,\n            action_details=action_args,\n            risk_level=risk_level,\n            context=context\n        )\n        \n        response = self._request_approval(request)\n        \n        if response.decision == Decision.APPROVE:\n            return action_fn(**action_args)\n        elif response.decision == Decision.MODIFY:\n            modified_args = {**action_args, **(response.modified_details or {})}\n            return action_fn(**modified_args)\n        else:\n            return None\n\n\n# 使用示例\ndef mock_approval_ui(request: ApprovalRequest) -> ApprovalResponse:\n    \"\"\"模拟人类审批界面\"\"\"\n    print(f\"\\n📋 审批请求:\")\n    print(f\"   Agent: {request.agent_name}\")\n    print(f\"   操作: {request.action_type}\")\n    print(f\"   风险: {request.risk_level}\")\n    print(f\"   详情: {request.action_description}\")\n    # 模拟人类批准\n    return ApprovalResponse(request.request_id, Decision.APPROVE, \"同意执行\")\n\n\ndef demo_hitl():\n    def send_email(to: str, subject: str, body: str):\n        \"\"\"发送邮件\"\"\"\n        return f\"邮件已发送至 {to}\"\n    \n    agent = HumanInLoopAgent(\"email_agent\", mock_approval_ui, verbose=True)\n    result = agent.execute_with_approval(\n        \"send_email\", send_email,\n        {\"to\": \"user@example.com\", \"subject\": \"重要通知\", \"body\": \"...\"},\n        risk_level=\"high\"\n    )\n    print(f\"\\n执行结果: {result}\")",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-3",
      "language": "text",
      "description": "这种模式类似于工厂中的\"质量检验员\"——不参与每一道工序，但在关键检查点抽检，发现问题时及时介入。",
      "code": "┌─────────────────────────────────────────┐\n│        Human-on-the-Loop Flow            │\n│                                         │\n│  Agent 自主执行 ─────────────────┐      │\n│                                  │      │\n│                        ┌─────────▼────┐ │\n│                        │ 异常检测器   │ │\n│                        └──┬───────┬──┘ │\n│                           │       │    │\n│                    正常运行   检测到异常 │\n│                      │         │      │\n│                      ▼         ▼      │\n│                    继续    ⚠️ 通知人类  │\n│                                     │  │\n│                              ┌──────┴────┐│\n│                              ▼           ▼│\n│                            人类介入    忽略  │\n│                              │           ││\n│                              ▼           ▼│\n│                            修正继续    标记噪声│\n└─────────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-4",
      "language": "python",
      "description": "- 需要设计合理的通知策略避免\"报警疲劳\"",
      "code": "\"\"\"Human-on-the-Loop 模式实现\"\"\"\nfrom typing import Callable, Optional, Dict, Any, List\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nimport time\n\n\nclass AnomalyType(Enum):\n    LOW_CONFIDENCE = \"low_confidence\"\n    HIGH_RISK = \"high_risk\"\n    TIMEOUT = \"timeout\"\n    ERROR = \"error\"\n    POLICY_VIOLATION = \"policy_violation\"\n\n\n@dataclass\nclass AnomalyEvent:\n    event_type: AnomalyType\n    description: str\n    confidence: float\n    context: Dict[str, Any] = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n\n\n@dataclass\nclass HumanIntervention:\n    event: AnomalyEvent\n    action: str  # \"fix\", \"skip\", \"escalate\"\n    human_input: Any = None\n\n\nclass HumanOnLoopAgent:\n    \"\"\"Human-on-the-Loop Agent - 自主执行，异常时通知人类。\"\"\"\n    \n    def __init__(self, alert_callback: Callable[[AnomalyEvent], HumanIntervention],\n                 confidence_threshold: float = 0.7, verbose: bool = False):\n        self.alert_callback = alert_callback\n        self.confidence_threshold = confidence_threshold\n        self.verbose = verbose\n        self.events: List[Dict] = []\n    \n    def execute(self, task: str, executor: Callable) -> Any:\n        \"\"\"执行任务，自动检测异常\"\"\"\n        try:\n            result, confidence = executor(task)\n            \n            if confidence < self.confidence_threshold:\n                event = AnomalyEvent(\n                    AnomalyType.LOW_CONFIDENCE,\n                    f\"置信度 {confidence:.2f} 低于阈值 {self.confidence_threshold}\",\n                    confidence\n                )\n                intervention = self.alert_callback(event)\n                self.events.append({\"event\": event, \"intervention\": intervention})\n                \n                if intervention.action == \"fix\" and intervention.human_input:\n                    return intervention.human_input\n            \n            return result\n        except Exception as e:\n            event = AnomalyEvent(AnomalyType.ERROR, str(e), 0.0)\n            intervention = self.alert_callback(event)\n            if intervention.action == \"fix\":\n                return intervention.human_input\n            raise",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-5",
      "language": "text",
      "description": "这种模式类似于管理者给团队分配任务：管理者说明目标和要求，团队自主决定执行方式。",
      "code": "┌─────────────────────────────────────────┐\n│       Human-over-the-Loop Flow           │\n│                                         │\n│  人类: 设定目标 + 约束                    │\n│    │                                     │\n│    ▼                                     │\n│  Agent: 自主规划 + 执行                   │\n│    │                                     │\n│    ▼                                     │\n│  Agent: 输出结果 + 执行报告               │\n│    │                                     │\n│    ▼                                     │\n│  人类: 审查结果 (可选)                    │\n│    │                                     │\n│    ▼                                     │\n│  反馈 → 优化下一轮目标设定                 │\n└─────────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-6",
      "language": "python",
      "description": "缺点： 人类对执行过程的控制力弱、错误可能在完成后才被发现",
      "code": "\"\"\"Human-over-the-Loop 模式实现\"\"\"\nfrom dataclasses import dataclass, field\nfrom typing import List, Callable\n\n\n@dataclass\nclass AgentGoal:\n    objective: str\n    constraints: List[str] = field(default_factory=list)\n    success_criteria: str = \"\"\n    max_duration_seconds: int = 300\n\n\nclass HumanOverLoopAgent:\n    \"\"\"Agent完全自主执行，人类只设定目标。\"\"\"\n    \n    def __init__(self, planner: Callable, executor: Callable, verbose: bool = False):\n        self.planner = planner\n        self.executor = executor\n        self.verbose = verbose\n    \n    def run(self, goal: AgentGoal) -> dict:\n        plan = self.planner(goal)\n        result = self.executor(plan, goal.constraints)\n        return {\n            \"objective\": goal.objective,\n            \"plan\": plan,\n            \"result\": result\n        }",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-7",
      "language": "text",
      "description": "这种模式类似于企业审批流程中的\"签字盖章\"——不是每个步骤都需要签字，但在关键节点（如合同签署、资金拨付）必须有签字。",
      "code": "┌──────────────────────────────────────────┐\n│           Workflow with Gates             │\n│                                          │\n│ Step1 ──▶ Step2 ──▶ 🔒 Gate A ──▶ Step3 │\n│                              │          │\n│                         人类审批          │\n│                              │          │\n│ Step4 ──▶ Step5 ──▶ 🔒 Gate B ──▶ Step6 │\n│                                          │\n│ Gate配置:                                │\n│ - 需要审批的操作类型                       │\n│ - 审批超时策略                             │\n│ - 审批人/组                               │\n│ - 自动批准条件                            │\n└──────────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-8",
      "language": "python",
      "description": "缺点： 需要预先定义审批节点、新增关卡需要修改工作流",
      "code": "\"\"\"Approval Gate 模式实现\"\"\"\nfrom typing import Callable, Dict, Optional, List\nfrom dataclasses import dataclass, field\nfrom enum import Enum\n\n\nclass GateAction(Enum):\n    APPROVE = \"approve\"\n    REJECT = \"reject\"\n    REQUEST_CHANGE = \"request_change\"\n\n\n@dataclass\nclass ApprovalGate:\n    gate_id: str\n    name: str\n    description: str\n    required_action_types: List[str]\n    approvers: List[str]\n    timeout_seconds: int = 3600\n    auto_approve_after_timeout: bool = False\n\n\nclass GatedWorkflow:\n    \"\"\"带审批关卡的工作流\"\"\"\n    \n    def __init__(self, gates: List[ApprovalGate] = None, verbose: bool = False):\n        self.gates = gates or []\n        self.verbose = verbose\n    \n    def check_gate(self, action_type: str, action_details: dict,\n                   approval_fn: Callable) -> bool:\n        \"\"\"检查操作是否需要经过审批关卡\"\"\"\n        for gate in self.gates:\n            if action_type in gate.required_action_types:\n                if self.verbose:\n                    print(f\"🔒 触发审批关卡: {gate.name}\")\n                result = approval_fn(gate, action_details)\n                return result == GateAction.APPROVE\n        return True  # 无需审批",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-9",
      "language": "python",
      "description": "缺点： 委派粒度需要经验、不合适的委派可能导致返工",
      "code": "\"\"\"Delegation 模式实现\"\"\"\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional, Callable\n\n\n@dataclass\nclass DelegatedTask:\n    task_id: str\n    description: str\n    constraints: List[str] = field(default_factory=list)\n    deadline: Optional[str] = None\n    expected_output: str = \"\"\n    priority: int = 0\n\n\nclass DelegationManager:\n    \"\"\"任务委派管理器\"\"\"\n    \n    def __init__(self, agent_executor: Callable, verbose: bool = False):\n        self.executor = agent_executor\n        self.verbose = verbose\n        self.delegated: List[dict] = []\n    \n    def delegate(self, task: DelegatedTask) -> dict:\n        if self.verbose:\n            print(f\"📋 委派任务: {task.description}\")\n            print(f\"   约束: {', '.join(task.constraints)}\")\n        \n        result = self.executor(task)\n        self.delegated.append({\"task\": task, \"result\": result})\n        return result\n    \n    def review(self, task_id: str) -> Optional[dict]:\n        for item in self.delegated:\n            if item[\"task\"].task_id == task_id:\n                return item[\"result\"]\n        return None",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-10",
      "language": "text",
      "description": "Agent的能力是有边界的。当遇到超出能力范围的问题——如需要人类判断的主观问题、缺少必要权限的操作、系统异常情况——Agent不应该盲目尝试，而应该及时\"求助\"。Escalation模式定义了何时升",
      "code": "┌──────────────────────────────────────────┐\n│          Escalation Flow                  │\n│                                          │\n│  Agent 尝试处理                           │\n│       │                                  │\n│  遇到以下情况?                            │\n│  ├── 超出能力范围 ──▶ 升级到专家          │\n│  ├── 缺少权限 ────▶ 升级到管理员          │\n│  ├── 不确定结果 ──▶ 升级到人类审核        │\n│  └── 系统错误 ───▶ 升级到运维            │\n│                                          │\n│  升级规则:                                │\n│  - 触发条件                               │\n│  - 升级目标                               │\n│  - 升级级别 (L1→L2→L3)                   │\n│  - 超时未处理策略                          │\n└──────────────────────────────────────────┘",
      "section_ref": "结构",
      "runnable": false,
      "dependencies": []
    },
    {
      "id": "code-11",
      "language": "python",
      "description": "缺点： 升级规则设计复杂、可能过度升级导致人类负担",
      "code": "\"\"\"Escalation 模式实现\"\"\"\nfrom typing import Callable, Dict, List, Optional\nfrom dataclasses import dataclass, field\nfrom enum import Enum\n\n\nclass EscalationLevel(Enum):\n    L1_AGENT = \"l1_agent\"       # 升级给高级Agent\n    L2_SPECIALIST = \"l2_specialist\"  # 升级给领域专家\n    L3_HUMAN = \"l3_human\"       # 升级给人类\n\n\n@dataclass\nclass EscalationRule:\n    rule_id: str\n    condition: Callable[[dict], bool]\n    level: EscalationLevel\n    target: str\n    description: str\n    priority: int = 0\n\n\n@dataclass\nclass EscalationEvent:\n    rule: EscalationRule\n    context: Dict\n    resolved: bool = False\n    resolution: str = \"\"\n\n\nclass EscalationManager:\n    \"\"\"问题升级管理器\"\"\"\n    \n    def __init__(self, handlers: Dict[EscalationLevel, Callable],\n                 verbose: bool = False):\n        self.rules: List[EscalationRule] = []\n        self.handlers = handlers\n        self.verbose = verbose\n        self.history: List[EscalationEvent] = []\n    \n    def add_rule(self, rule: EscalationRule) -> None:\n        self.rules.append(rule)\n        self.rules.sort(key=lambda r: r.priority, reverse=True)\n    \n    def check_and_escalate(self, context: dict) -> Optional[dict]:\n        \"\"\"检查是否需要升级\"\"\"\n        for rule in self.rules:\n            if rule.condition(context):\n                if self.verbose:\n                    print(f\"⚠️ 升级 [{rule.level.value}]: {rule.description}\")\n                    print(f\"   目标: {rule.target}\")\n                \n                event = EscalationEvent(rule, context)\n                handler = self.handlers.get(rule.level)\n                if handler:\n                    result = handler(event)\n                    event.resolved = True\n                    event.resolution = str(result)\n                \n                self.history.append(event)\n                return result\n        \n        return None  # 无需升级",
      "section_ref": "实现",
      "runnable": true,
      "dependencies": []
    },
    {
      "id": "code-12",
      "language": "text",
      "description": "本章介绍了六种人机协作模式，它们的核心差异在于人类参与的时机和深度：",
      "code": "人类参与深度\n    ▲\n    │  ┌─────────────────────┐\n    │  │ Human-in-the-Loop   │  ← 每次关键决策\n    │  ├─────────────────────┤\n    │  │ Approval Gate       │  ← 特定审批节点\n    │  ├─────────────────────┤\n    │  │ Human-on-the-Loop   │  ← 异常时介入\n    │  ├─────────────────────┤\n    │  │ Delegation          │  ← 明确的任务边界\n    │  ├─────────────────────┤\n    │  │ Escalation          │  ← 能力不足时升级\n    │  ├─────────────────────┤\n    │  │ Human-over-the-Loop │  ← 仅设定目标\n    │  └─────────────────────┘\n    └──────────────────────────▶ Agent自主性",
      "section_ref": "33.8",
      "runnable": false,
      "dependencies": []
    }
  ],
  "tables": [
    {
      "headers": [
        "考量维度",
        "Human-in-the-Loop",
        "Human-on-the-Loop",
        "Human-over-the-Loop"
      ],
      "data": [
        [
          "人类参与频率",
          "每次关键决策",
          "异常时介入",
          "仅设定目标"
        ],
        [
          "适用风险等级",
          "高",
          "中",
          "低"
        ],
        [
          "人类时间成本",
          "高",
          "中",
          "低"
        ],
        [
          "Agent自主性",
          "低",
          "中",
          "高"
        ],
        [
          "典型场景",
          "医疗诊断",
          "内容审核",
          "数据报表"
        ]
      ]
    }
  ],
  "key_takeaways": [],
  "common_pitfalls": [],
  "related_chapters": [
    "ch08",
    "ch35"
  ]
}