{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f0102d3e",
   "metadata": {},
   "source": [
    "# 阶段5：多 Agent 协同与角色体系 实践\n",
    "\n",
    "本笔记本帮助你实践多 Agent 系统架构、协作模式和通信机制，参考 docs/stage5-multi-agent.md。\n",
    "\n",
    "## 本阶段目标\n",
    "- 理解多 Agent 系统的架构模式\n",
    "- 掌握 Manager-Worker、专家小组等协作模式\n",
    "- 学习 Agent 间的通信和协调机制\n",
    "- 实践构建多角色协作的 Agent 系统"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f15bb613",
   "metadata": {},
   "source": [
    "## 1. 环境配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "032025cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入必要的库\n",
    "import os\n",
    "import json\n",
    "from datetime import datetime\n",
    "from typing import List, Dict, Any\n",
    "from dotenv import load_dotenv\n",
    "from openai import AzureOpenAI\n",
    "\n",
    "# 加载环境变量\n",
    "load_dotenv(override=True)\n",
    "\n",
    "# 创建 Azure OpenAI 客户端\n",
    "client = AzureOpenAI(\n",
    "    azure_endpoint=os.getenv(\"AZURE_OPENAI_ENDPOINT\"),\n",
    "    api_key=os.getenv(\"AZURE_OPENAI_API_KEY\"),\n",
    "    api_version=os.getenv(\"AZURE_OPENAI_API_VERSION\", \"2024-12-01-preview\")\n",
    ")\n",
    "\n",
    "# 获取部署名称\n",
    "deployment = os.getenv(\"AZURE_OPENAI_DEPLOYMENT\", \"gpt-4o\")\n",
    "\n",
    "print(f\"✅ 环境配置完成\")\n",
    "print(f\"📌 使用部署: {deployment}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87bb491e",
   "metadata": {},
   "source": [
    "## 2. 为什么需要多 Agent 系统？\n",
    "\n",
    "### 单一 Agent 的局限性\n",
    "- ❌ 知识和能力有限\n",
    "- ❌ 难以处理多领域任务\n",
    "- ❌ 缺乏多角度思考\n",
    "- ❌ 质量控制不足\n",
    "\n",
    "### 多 Agent 系统的优势\n",
    "- ✅ 专业化分工\n",
    "- ✅ 并行处理能力\n",
    "- ✅ 互相验证和改进\n",
    "- ✅ 更好的可扩展性\n",
    "\n",
    "### 常见模式\n",
    "1. **Manager-Worker**: 管理者分配任务，工作者执行\n",
    "2. **Expert Panel**: 多个专家共同讨论决策\n",
    "3. **Self-Refine**: 通过多个角色迭代改进"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62befa53",
   "metadata": {},
   "source": [
    "## 3. Manager-Worker 模式\n",
    "\n",
    "```\n",
    "        ┌──────────┐\n",
    "        │ Manager  │\n",
    "        │  Agent   │\n",
    "        └─────┬────┘\n",
    "              │\n",
    "        ┌─────┴─────┐\n",
    "        ▼           ▼\n",
    "    ┌────────┐  ┌────────┐\n",
    "    │Worker 1│  │Worker 2│\n",
    "    └────────┘  └────────┘\n",
    "```\n",
    "\n",
    "**适用场景**：任务可以明确分解和分配"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cba3474",
   "metadata": {},
   "outputs": [],
   "source": [
    "class WorkerAgent:\n",
    "    \"\"\"工作者 Agent\n",
    "    \n",
    "    负责执行特定领域的任务。\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, name: str, description: str, system_prompt: str):\n",
    "        self.name = name\n",
    "        self.description = description\n",
    "        self.system_prompt = system_prompt\n",
    "    \n",
    "    def execute(self, task: str) -> str:\n",
    "        \"\"\"执行任务\"\"\"\n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": self.system_prompt},\n",
    "                {\"role\": \"user\", \"content\": task}\n",
    "            ]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "\n",
    "\n",
    "class ManagerAgent:\n",
    "    \"\"\"管理者 Agent\n",
    "    \n",
    "    负责：\n",
    "    1. 任务分解\n",
    "    2. 分配给合适的工作者\n",
    "    3. 整合结果\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.workers = {}\n",
    "    \n",
    "    def register_worker(self, name: str, worker: WorkerAgent):\n",
    "        \"\"\"注册工作者 Agent\"\"\"\n",
    "        self.workers[name] = worker\n",
    "        print(f\"✅ 已注册工作者: {name} - {worker.description}\")\n",
    "    \n",
    "    def decompose_task(self, task: str) -> List[Dict]:\n",
    "        \"\"\"分解任务\"\"\"\n",
    "        worker_descriptions = \"\\n\".join([\n",
    "            f\"- {name}: {worker.description}\"\n",
    "            for name, worker in self.workers.items()\n",
    "        ])\n",
    "        \n",
    "        prompt = f\"\"\"可用的工作者：\n",
    "{worker_descriptions}\n",
    "\n",
    "任务：{task}\n",
    "\n",
    "请将任务分解为子任务，并分配给合适的工作者。\n",
    "以 JSON 格式返回：\n",
    "{{\n",
    "    \"subtasks\": [\n",
    "        {{\n",
    "            \"id\": 1,\n",
    "            \"description\": \"子任务描述\",\n",
    "            \"assigned_to\": \"工作者名称\",\n",
    "            \"priority\": \"high/medium/low\"\n",
    "        }}\n",
    "    ]\n",
    "}}\"\"\"\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[{\"role\": \"user\", \"content\": prompt}],\n",
    "            response_format={\"type\": \"json_object\"}\n",
    "        )\n",
    "        \n",
    "        result = json.loads(response.choices[0].message.content)\n",
    "        return result.get(\"subtasks\", [])\n",
    "    \n",
    "    def synthesize_results(self, original_task: str, results: List[Dict]) -> str:\n",
    "        \"\"\"整合各个工作者的结果\"\"\"\n",
    "        results_text = \"\\n\\n\".join([\n",
    "            f\"子任务: {r['subtask']['description']}\\n结果: {r['result']}\"\n",
    "            for r in results\n",
    "        ])\n",
    "        \n",
    "        prompt = f\"\"\"原始任务: {original_task}\n",
    "\n",
    "各部分完成情况：\n",
    "{results_text}\n",
    "\n",
    "请将这些结果整合成一个完整、连贯的最终成果。\"\"\"\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[{\"role\": \"user\", \"content\": prompt}]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "    \n",
    "    def execute_task(self, task: str) -> Dict:\n",
    "        \"\"\"执行完整任务\"\"\"\n",
    "        print(f\"📋 Manager: 收到任务 - {task}\\n\")\n",
    "        print(\"=\" * 60)\n",
    "        \n",
    "        # 1. 分解任务\n",
    "        print(\"\\n✂️ 步骤1: 分解任务\")\n",
    "        print(\"-\" * 60)\n",
    "        subtasks = self.decompose_task(task)\n",
    "        print(f\"已分解为 {len(subtasks)} 个子任务：\")\n",
    "        for st in subtasks:\n",
    "            print(f\"  {st['id']}. [{st['assigned_to']}] {st['description']}\")\n",
    "        \n",
    "        # 2. 分配并执行\n",
    "        print(\"\\n👷 步骤2: 执行子任务\")\n",
    "        print(\"-\" * 60)\n",
    "        results = []\n",
    "        for subtask in subtasks:\n",
    "            worker_name = subtask[\"assigned_to\"]\n",
    "            if worker_name in self.workers:\n",
    "                print(f\"\\n🔧 {worker_name} 正在执行: {subtask['description'][:50]}...\")\n",
    "                \n",
    "                worker = self.workers[worker_name]\n",
    "                result = worker.execute(subtask[\"description\"])\n",
    "                \n",
    "                results.append({\n",
    "                    \"subtask\": subtask,\n",
    "                    \"result\": result\n",
    "                })\n",
    "                print(f\"✅ {worker_name} 已完成\")\n",
    "            else:\n",
    "                print(f\"⚠️ 找不到工作者: {worker_name}\")\n",
    "        \n",
    "        # 3. 整合结果\n",
    "        print(\"\\n📝 步骤3: 整合结果\")\n",
    "        print(\"-\" * 60)\n",
    "        final_result = self.synthesize_results(task, results)\n",
    "        print(\"✅ 结果整合完成\")\n",
    "        \n",
    "        return {\n",
    "            \"task\": task,\n",
    "            \"subtasks\": subtasks,\n",
    "            \"results\": results,\n",
    "            \"final_result\": final_result\n",
    "        }\n",
    "\n",
    "print(\"✅ ManagerAgent 和 WorkerAgent 类定义完成\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6da1833f",
   "metadata": {},
   "source": [
    "### 3.1 测试 Manager-Worker 模式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dee3541a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建管理者\n",
    "manager = ManagerAgent()\n",
    "\n",
    "# 创建专业工作者\n",
    "researcher = WorkerAgent(\n",
    "    \"Researcher\",\n",
    "    \"负责研究和收集信息\",\n",
    "    \"你是一个专业的研究员，擅长收集和整理信息。请提供准确、有深度的研究内容。\"\n",
    ")\n",
    "\n",
    "writer = WorkerAgent(\n",
    "    \"Writer\",\n",
    "    \"负责撰写和编辑内容\",\n",
    "    \"你是一个专业的作家，擅长撰写清晰、引人入胜的内容。\"\n",
    ")\n",
    "\n",
    "reviewer = WorkerAgent(\n",
    "    \"Reviewer\",\n",
    "    \"负责审核和改进内容\",\n",
    "    \"你是一个专业的审核员，擅长发现问题并提出改进建议。\"\n",
    ")\n",
    "\n",
    "# 注册工作者\n",
    "manager.register_worker(\"Researcher\", researcher)\n",
    "manager.register_worker(\"Writer\", writer)\n",
    "manager.register_worker(\"Reviewer\", reviewer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e14d2ee5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 执行任务\n",
    "task = \"写一篇关于 AI Agent 的简短介绍（200字左右）\"\n",
    "result = manager.execute_task(task)\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"📄 最终成果\")\n",
    "print(\"=\" * 60)\n",
    "print(result[\"final_result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb09e00b",
   "metadata": {},
   "source": [
    "## 4. 专家小组模式 (Expert Panel)\n",
    "\n",
    "多个专家共同讨论，从不同角度分析问题，最终达成共识或总结分歧。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14d4a73c",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ExpertPanel:\n",
    "    \"\"\"专家小组\n",
    "    \n",
    "    多个专家共同讨论决策，每个专家有不同的专业背景和观点。\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.experts = {}\n",
    "    \n",
    "    def add_expert(self, name: str, expertise: str, personality: str):\n",
    "        \"\"\"添加专家\"\"\"\n",
    "        self.experts[name] = {\n",
    "            \"expertise\": expertise,\n",
    "            \"personality\": personality,\n",
    "            \"opinions\": []\n",
    "        }\n",
    "        print(f\"✅ 已添加专家: {name} ({expertise})\")\n",
    "    \n",
    "    def get_expert_opinion(self, expert_name: str, topic: str, \n",
    "                          previous_opinions: List[Dict] = None) -> str:\n",
    "        \"\"\"获取专家意见\"\"\"\n",
    "        expert = self.experts[expert_name]\n",
    "        \n",
    "        system_prompt = f\"\"\"你是 {expert_name}，一位{expert['expertise']}专家。\n",
    "性格特点：{expert['personality']}\n",
    "\n",
    "请基于你的专业知识给出意见。回答要简洁（100字以内）。\"\"\"\n",
    "        \n",
    "        # 构建上下文（包括其他专家的意见）\n",
    "        context = f\"讨论主题：{topic}\\n\\n\"\n",
    "        if previous_opinions:\n",
    "            context += \"其他专家的意见：\\n\"\n",
    "            for opinion in previous_opinions:\n",
    "                context += f\"\\n【{opinion['expert']}】：{opinion['content']}\\n\"\n",
    "            context += f\"\\n现在轮到你发表意见，你可以同意、反对或补充其他专家的观点。\"\n",
    "        else:\n",
    "            context += \"你是第一个发言的专家，请给出你的专业意见。\"\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": system_prompt},\n",
    "                {\"role\": \"user\", \"content\": context}\n",
    "            ]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "    \n",
    "    def generate_summary(self, topic: str, opinions: List[Dict]) -> str:\n",
    "        \"\"\"生成讨论总结\"\"\"\n",
    "        opinions_text = \"\\n\\n\".join([\n",
    "            f\"[第{op['round']}轮] {op['expert']}:\\n{op['content']}\"\n",
    "            for op in opinions\n",
    "        ])\n",
    "        \n",
    "        prompt = f\"\"\"讨论主题: {topic}\n",
    "\n",
    "专家意见:\n",
    "{opinions_text}\n",
    "\n",
    "请总结这次专家讨论：\n",
    "1. 主要共识点\n",
    "2. 主要分歧点\n",
    "3. 最有价值的建议\n",
    "4. 最终结论\"\"\"\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[{\"role\": \"user\", \"content\": prompt}]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "    \n",
    "    def discuss(self, topic: str, rounds: int = 2) -> Dict:\n",
    "        \"\"\"进行多轮讨论\"\"\"\n",
    "        print(f\"🎯 讨论主题: {topic}\\n\")\n",
    "        print(\"=\" * 60)\n",
    "        \n",
    "        all_opinions = []\n",
    "        \n",
    "        for round_num in range(rounds):\n",
    "            print(f\"\\n📢 第 {round_num + 1} 轮讨论\")\n",
    "            print(\"-\" * 60)\n",
    "            \n",
    "            for expert_name in self.experts.keys():\n",
    "                # 获取之前的意见作为上下文\n",
    "                previous = all_opinions if round_num > 0 else None\n",
    "                \n",
    "                opinion = self.get_expert_opinion(\n",
    "                    expert_name, topic, previous\n",
    "                )\n",
    "                \n",
    "                opinion_dict = {\n",
    "                    \"round\": round_num + 1,\n",
    "                    \"expert\": expert_name,\n",
    "                    \"content\": opinion\n",
    "                }\n",
    "                \n",
    "                all_opinions.append(opinion_dict)\n",
    "                \n",
    "                print(f\"\\n💬 {expert_name}:\")\n",
    "                print(opinion)\n",
    "        \n",
    "        # 生成总结\n",
    "        print(\"\\n\" + \"=\" * 60)\n",
    "        print(\"📝 生成讨论总结...\")\n",
    "        summary = self.generate_summary(topic, all_opinions)\n",
    "        \n",
    "        return {\n",
    "            \"topic\": topic,\n",
    "            \"rounds\": rounds,\n",
    "            \"opinions\": all_opinions,\n",
    "            \"summary\": summary\n",
    "        }\n",
    "\n",
    "print(\"✅ ExpertPanel 类定义完成\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee72185f",
   "metadata": {},
   "source": [
    "### 4.1 测试专家小组讨论"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6fb78eee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建专家小组\n",
    "panel = ExpertPanel()\n",
    "\n",
    "# 添加不同领域的专家\n",
    "panel.add_expert(\n",
    "    \"技术架构师\",\n",
    "    \"软件架构和系统设计\",\n",
    "    \"注重技术可行性和系统稳定性，偏保守\"\n",
    ")\n",
    "\n",
    "panel.add_expert(\n",
    "    \"产品经理\",\n",
    "    \"产品规划和用户体验\",\n",
    "    \"注重用户需求和商业价值，偏激进\"\n",
    ")\n",
    "\n",
    "panel.add_expert(\n",
    "    \"安全专家\",\n",
    "    \"信息安全和数据保护\",\n",
    "    \"注重安全风险和合规性，谨慎务实\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e23d106",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 开始讨论\n",
    "topic = \"是否应该在我们的产品中引入 AI Agent 功能？\"\n",
    "result = panel.discuss(topic, rounds=2)\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"📋 讨论总结\")\n",
    "print(\"=\" * 60)\n",
    "print(result[\"summary\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59af1790",
   "metadata": {},
   "source": [
    "## 5. Self-Refine 模式\n",
    "\n",
    "通过「创作 → 批评 → 改进」的循环，不断提升内容质量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b1885787",
   "metadata": {},
   "outputs": [],
   "source": [
    "class SelfRefineAgent:\n",
    "    \"\"\"自我精炼 Agent\n",
    "    \n",
    "    通过多个角色迭代改进内容：\n",
    "    1. Creator: 生成初始内容\n",
    "    2. Critic: 评审和批评\n",
    "    3. Refiner: 根据反馈改进\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, max_iterations: int = 3):\n",
    "        self.max_iterations = max_iterations\n",
    "    \n",
    "    def generate(self, task: str) -> str:\n",
    "        \"\"\"生成初始内容\"\"\"\n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": \"你是一个内容创作者。\"},\n",
    "                {\"role\": \"user\", \"content\": task}\n",
    "            ]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "    \n",
    "    def critique(self, content: str, task: str) -> str:\n",
    "        \"\"\"批评和评估\"\"\"\n",
    "        prompt = f\"\"\"原始任务: {task}\n",
    "\n",
    "生成的内容:\n",
    "{content}\n",
    "\n",
    "请作为一个严格的评审者，指出这个内容的问题和可以改进的地方：\n",
    "1. 是否完成了任务要求？\n",
    "2. 内容是否清晰、准确？\n",
    "3. 结构是否合理？\n",
    "4. 有哪些具体的改进建议？\n",
    "\n",
    "请给出详细、建设性的反馈（简洁，不超过150字）。\"\"\"\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": \"你是一个专业的评审者，擅长发现问题并提出改进建议。\"},\n",
    "                {\"role\": \"user\", \"content\": prompt}\n",
    "            ]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "    \n",
    "    def refine(self, content: str, critique: str, task: str) -> str:\n",
    "        \"\"\"根据反馈改进内容\"\"\"\n",
    "        prompt = f\"\"\"原始任务: {task}\n",
    "\n",
    "当前内容:\n",
    "{content}\n",
    "\n",
    "评审意见:\n",
    "{critique}\n",
    "\n",
    "请根据评审意见改进内容，生成更好的版本。\"\"\"\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": \"你是一个内容创作者，擅长根据反馈改进作品。\"},\n",
    "                {\"role\": \"user\", \"content\": prompt}\n",
    "            ]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "    \n",
    "    def run(self, task: str) -> Dict:\n",
    "        \"\"\"执行完整的自我精炼流程\"\"\"\n",
    "        print(f\"📝 任务: {task}\\n\")\n",
    "        print(\"=\" * 60)\n",
    "        \n",
    "        # 初始生成\n",
    "        print(\"\\n🎨 第 1 版本 - 初始生成\")\n",
    "        print(\"-\" * 60)\n",
    "        content = self.generate(task)\n",
    "        print(content)\n",
    "        \n",
    "        history = [{\n",
    "            \"version\": 1,\n",
    "            \"content\": content,\n",
    "            \"critique\": None\n",
    "        }]\n",
    "        \n",
    "        # 迭代改进\n",
    "        for i in range(self.max_iterations - 1):\n",
    "            print(f\"\\n{'=' * 60}\")\n",
    "            print(f\"🔄 第 {i + 2} 版本 - 评审和改进\")\n",
    "            print(\"=\" * 60)\n",
    "            \n",
    "            # 评审\n",
    "            print(\"\\n🔍 评审意见:\")\n",
    "            print(\"-\" * 60)\n",
    "            critique = self.critique(content, task)\n",
    "            print(critique)\n",
    "            \n",
    "            # 改进\n",
    "            print(\"\\n✨ 改进后的内容:\")\n",
    "            print(\"-\" * 60)\n",
    "            content = self.refine(content, critique, task)\n",
    "            print(content)\n",
    "            \n",
    "            history.append({\n",
    "                \"version\": i + 2,\n",
    "                \"content\": content,\n",
    "                \"critique\": critique\n",
    "            })\n",
    "        \n",
    "        return {\n",
    "            \"task\": task,\n",
    "            \"history\": history,\n",
    "            \"final_content\": content\n",
    "        }\n",
    "\n",
    "print(\"✅ SelfRefineAgent 类定义完成\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f3507b8",
   "metadata": {},
   "source": [
    "### 5.1 测试 Self-Refine 模式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e7e34b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建自我精炼 Agent\n",
    "refine_agent = SelfRefineAgent(max_iterations=3)\n",
    "\n",
    "# 执行任务\n",
    "task = \"写一段关于 AI Agent 应用价值的介绍（100字左右）\"\n",
    "result = refine_agent.run(task)\n",
    "\n",
    "print(\"\\n\\n\" + \"=\" * 60)\n",
    "print(\"🏆 最终版本\")\n",
    "print(\"=\" * 60)\n",
    "print(result[\"final_content\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20805bb8",
   "metadata": {},
   "source": [
    "## 6. 综合项目：文档创作团队\n",
    "\n",
    "结合多种模式，构建一个完整的多 Agent 文档创作系统。\n",
    "\n",
    "```\n",
    "Outliner → Researcher → Writer → Editor → Reviewer\n",
    "  (大纲)    (研究)      (写作)    (编辑)    (审核)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "171c7f6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "class DocumentCreationTeam:\n",
    "    \"\"\"文档创作团队\n",
    "    \n",
    "    多 Agent 协作创作文档：\n",
    "    1. Outliner: 设计文档大纲\n",
    "    2. Researcher: 收集研究信息\n",
    "    3. Writer: 撰写内容\n",
    "    4. Editor: 编辑优化\n",
    "    5. Reviewer: 质量审核\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.agents = {\n",
    "            \"outliner\": {\n",
    "                \"role\": \"大纲设计师\",\n",
    "                \"system_prompt\": \"你是一个专业的内容架构师，擅长设计文档大纲和结构。请设计清晰、逻辑性强的大纲。\"\n",
    "            },\n",
    "            \"researcher\": {\n",
    "                \"role\": \"研究员\",\n",
    "                \"system_prompt\": \"你是一个研究员，负责收集和组织相关信息。请提供准确、有深度的研究内容。\"\n",
    "            },\n",
    "            \"writer\": {\n",
    "                \"role\": \"写作者\",\n",
    "                \"system_prompt\": \"你是一个专业作家，擅长将信息转化为清晰、引人入胜的文字。\"\n",
    "            },\n",
    "            \"editor\": {\n",
    "                \"role\": \"编辑\",\n",
    "                \"system_prompt\": \"你是一个编辑，负责优化文字表达和结构，使内容更加流畅和专业。\"\n",
    "            },\n",
    "            \"reviewer\": {\n",
    "                \"role\": \"审核者\",\n",
    "                \"system_prompt\": \"你是一个质量审核员，负责检查内容的准确性、完整性和专业性。\"\n",
    "            }\n",
    "        }\n",
    "    \n",
    "    def agent_execute(self, agent_key: str, task: str) -> str:\n",
    "        \"\"\"执行 Agent 任务\"\"\"\n",
    "        agent = self.agents[agent_key]\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=deployment,\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": agent[\"system_prompt\"]},\n",
    "                {\"role\": \"user\", \"content\": task}\n",
    "            ]\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "    \n",
    "    def create_document(self, topic: str) -> Dict:\n",
    "        \"\"\"完整的文档创作流程\"\"\"\n",
    "        print(f\"📚 开始创作文档: {topic}\\n\")\n",
    "        print(\"=\" * 60)\n",
    "        \n",
    "        # 1. 设计大纲\n",
    "        print(\"\\n📋 步骤 1: 设计大纲\")\n",
    "        print(\"-\" * 60)\n",
    "        outline = self.agent_execute(\n",
    "            \"outliner\",\n",
    "            f\"为'{topic}'设计一个简洁的文档大纲，包括3-4个主要章节。\"\n",
    "        )\n",
    "        print(outline)\n",
    "        \n",
    "        # 2. 研究收集\n",
    "        print(\"\\n🔍 步骤 2: 研究和收集信息\")\n",
    "        print(\"-\" * 60)\n",
    "        research = self.agent_execute(\n",
    "            \"researcher\",\n",
    "            f\"基于以下大纲，收集相关信息和要点（简洁）：\\n{outline}\"\n",
    "        )\n",
    "        print(research[:500] + \"...\" if len(research) > 500 else research)\n",
    "        \n",
    "        # 3. 撰写内容\n",
    "        print(\"\\n✍️ 步骤 3: 撰写文档\")\n",
    "        print(\"-\" * 60)\n",
    "        draft = self.agent_execute(\n",
    "            \"writer\",\n",
    "            f\"基于以下研究内容撰写文档（300字左右）：\\n大纲：{outline}\\n研究内容：{research}\"\n",
    "        )\n",
    "        print(draft[:500] + \"...\" if len(draft) > 500 else draft)\n",
    "        \n",
    "        # 4. 编辑优化\n",
    "        print(\"\\n📝 步骤 4: 编辑优化\")\n",
    "        print(\"-\" * 60)\n",
    "        edited = self.agent_execute(\n",
    "            \"editor\",\n",
    "            f\"优化以下文档的表达和结构：\\n{draft}\"\n",
    "        )\n",
    "        print(edited[:500] + \"...\" if len(edited) > 500 else edited)\n",
    "        \n",
    "        # 5. 最终审核\n",
    "        print(\"\\n✅ 步骤 5: 质量审核\")\n",
    "        print(\"-\" * 60)\n",
    "        review = self.agent_execute(\n",
    "            \"reviewer\",\n",
    "            f\"审核以下文档，给出质量评估和改进建议：\\n{edited}\"\n",
    "        )\n",
    "        print(review)\n",
    "        \n",
    "        return {\n",
    "            \"topic\": topic,\n",
    "            \"outline\": outline,\n",
    "            \"research\": research,\n",
    "            \"draft\": draft,\n",
    "            \"edited\": edited,\n",
    "            \"review\": review,\n",
    "            \"final_document\": edited\n",
    "        }\n",
    "\n",
    "print(\"✅ DocumentCreationTeam 类定义完成\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3da9890",
   "metadata": {},
   "source": [
    "### 6.1 测试文档创作团队"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7354ab02",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建文档创作团队\n",
    "team = DocumentCreationTeam()\n",
    "\n",
    "# 执行文档创作\n",
    "result = team.create_document(\"AI Agent 在企业中的应用\")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"📄 最终文档\")\n",
    "print(\"=\" * 60)\n",
    "print(result[\"final_document\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f65e2fcf",
   "metadata": {},
   "source": [
    "## 7. Agent 间通信协议\n",
    "\n",
    "标准化 Agent 间的消息传递。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42936d6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from dataclasses import dataclass\n",
    "from enum import Enum\n",
    "\n",
    "class MessageType(Enum):\n",
    "    \"\"\"消息类型\"\"\"\n",
    "    REQUEST = \"request\"      # 请求\n",
    "    RESPONSE = \"response\"    # 响应\n",
    "    INFO = \"info\"            # 信息\n",
    "    ERROR = \"error\"          # 错误\n",
    "\n",
    "@dataclass\n",
    "class Message:\n",
    "    \"\"\"Agent 间消息\"\"\"\n",
    "    sender: str\n",
    "    receiver: str\n",
    "    content: str\n",
    "    message_type: MessageType\n",
    "    timestamp: datetime = None\n",
    "    \n",
    "    def __post_init__(self):\n",
    "        if self.timestamp is None:\n",
    "            self.timestamp = datetime.now()\n",
    "    \n",
    "    def to_dict(self) -> Dict:\n",
    "        return {\n",
    "            \"sender\": self.sender,\n",
    "            \"receiver\": self.receiver,\n",
    "            \"content\": self.content,\n",
    "            \"type\": self.message_type.value,\n",
    "            \"timestamp\": self.timestamp.isoformat()\n",
    "        }\n",
    "\n",
    "# 示例\n",
    "msg = Message(\n",
    "    sender=\"Manager\",\n",
    "    receiver=\"Worker1\",\n",
    "    content=\"请分析用户需求\",\n",
    "    message_type=MessageType.REQUEST\n",
    ")\n",
    "\n",
    "print(\"📬 消息示例:\")\n",
    "print(json.dumps(msg.to_dict(), ensure_ascii=False, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3b0de59",
   "metadata": {},
   "source": [
    "## 8. 总结\n",
    "\n",
    "本阶段我们学习了：\n",
    "\n",
    "### 8.1 多 Agent 模式\n",
    "| 模式 | 特点 | 适用场景 |\n",
    "|------|------|----------|\n",
    "| **Manager-Worker** | 中心化管理，任务分发 | 可分解的任务 |\n",
    "| **Expert Panel** | 多角度讨论，共同决策 | 需要多方意见 |\n",
    "| **Self-Refine** | 迭代改进，自我提升 | 内容创作优化 |\n",
    "\n",
    "### 8.2 实践项目\n",
    "1. **ManagerAgent + WorkerAgent**: 任务分解与执行\n",
    "2. **ExpertPanel**: 专家讨论系统\n",
    "3. **SelfRefineAgent**: 内容迭代优化\n",
    "4. **DocumentCreationTeam**: 完整的多 Agent 协作\n",
    "\n",
    "### 8.3 关键要点\n",
    "- 合理的角色分工\n",
    "- 清晰的通信协议\n",
    "- 有效的结果整合\n",
    "- 冲突解决机制\n",
    "\n",
    "### 8.4 下一步\n",
    "进入 [阶段 6：成熟 Agent 框架实践](../docs/stage6-frameworks.md)，学习使用主流框架构建 Agent。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
