ByteNoteByteNote

字节笔记本

2026年6月21日

hermes教程-委托与并行工作

API中转
¥120

何时委托

适合委托的任务:

  • 推理密集型子任务(调试、代码审查、研究综合)
  • 会向你的上下文注入大量中间数据的任务
  • 可并行执行的独立工作流(同时研究 A 和 B)
  • 需要代理以无偏见方式处理的全新上下文任务

应使用其他方式的情况:

  • 单个工具调用 → 直接使用工具
  • 步骤间有逻辑的机械性多步工作 → 使用 execute_code
  • 需要用户交互的任务 → 子代理无法使用 clarify
  • 快速文件编辑 → 直接操作
  • 需要持久运行且跨越当前轮次的长期任务 → 使用 cronjobterminal(background=True, notify_on_complete=True)delegate_task同步的:如果父轮次被中断,活跃的子代理将被取消,其工作将被丢弃。

模式:并行研究

同时研究三个主题,并返回结构化摘要:

text
同时研究以下三个主题:
1. WebAssembly 在浏览器之外的最新状态
2. 2025 年 RISC-V 服务器芯片的采用情况
3. 实用的量子计算应用

重点关注近期发展和关键参与者。

在幕后,Hermes 使用:

python
delegate_task(tasks=[
    {
        "goal": "Research WebAssembly outside the browser in 2025",
        "context": "Focus on: runtimes (Wasmtime, Wasmer), cloud/edge use cases, WASI progress",
        "toolsets": ["web"]
    },
    {
        "goal": "Research RISC-V server chip adoption",
        "context": "Focus on: server chips shipping, cloud providers adopting, software ecosystem",
        "toolsets": ["web"]
    },
    {
        "goal": "Research practical quantum computing applications",
        "context": "Focus on: error correction breakthroughs, real-world use cases, key companies",
        "toolsets": ["web"]
    }
])

三个任务同时运行。每个子代理独立搜索网络并返回摘要。父代理随后将它们综合成一份清晰的简报。


模式:代码审查

将安全审查委托给一个全新上下文的子代理,使其不带先入为主的观念审查代码:

text
审查 src/auth/ 目录下的认证模块是否存在安全问题。
检查 SQL 注入、JWT 验证问题、密码处理和会话管理。
修复你发现的任何问题并运行测试。

关键在于 context 字段——它必须包含子代理所需的一切:

python
delegate_task(
    goal="Review src/auth/ for security issues and fix any found",
    context="""Project at /home/user/webapp. Python 3.11, Flask, PyJWT, bcrypt.
    Auth files: src/auth/login.py, src/auth/jwt.py, src/auth/middleware.py
    Test command: pytest tests/auth/ -v
    Focus on: SQL injection, JWT validation, password hashing, session management.
    Fix issues found and verify tests pass.""",
    toolsets=["terminal", "file"]
)

警告——上下文问题

子代理对你的对话一无所知。它们从完全空白的状态开始。如果你委托“修复我们刚才讨论的 bug”,子代理根本不知道你指的是哪个 bug。务必显式传递文件路径、错误信息、项目结构和约束条件。


模式:比较备选方案

并行评估同一问题的多种方法,然后选择最佳方案:

text
我需要为 Django 应用添加全文搜索功能。并行评估三种方案:
1. PostgreSQL tsvector(内置)
2. 通过 django-elasticsearch-dsl 使用 Elasticsearch
3. 通过 meilisearch-python 使用 Meilisearch

针对每种方案评估:设置复杂度、查询能力、资源需求和维护开销。
比较它们并推荐一个。

每个子代理独立研究一个选项。由于它们相互隔离,不会产生交叉污染——每个评估都基于自身优点。父代理获取所有三个摘要并进行比较。


模式:多文件重构

将大型重构任务拆分为多个并行子代理,每个处理代码库的不同部分:

python
delegate_task(tasks=[
    {
        "goal": "Refactor all API endpoint handlers to use the new response format",
        "context": """Project at /home/user/api-server.
        Files: src/handlers/users.py, src/handlers/auth.py, src/handlers/billing.py
        Old format: return {"data": result, "status": "ok"}
        New format: return APIResponse(data=result, status=200).to_dict()
        Import: from src.responses import APIResponse
        Run tests after: pytest tests/handlers/ -v""",
        "toolsets": ["terminal", "file"]
    },
    {
        "goal": "Update all client SDK methods to handle the new response format",
        "context": """Project at /home/user/api-server.
        Files: sdk/python/client.py, sdk/python/models.py
        Old parsing: result = response.json()["data"]
        New parsing: result = response.json()["data"] (same key, but add status code checking)
        Also update sdk/python/tests/test_client.py""",
        "toolsets": ["terminal", "file"]
    },
    {
        "goal": "Update API documentation to reflect the new response format",
        "context": """Project at /home/user/api-server.
        Docs at: docs/api/. Format: Markdown with code examples.
        Update all response examples from old format to new format.
        Add a 'Response Format' section to docs/api/overview.md explaining the schema.""",
        "toolsets": ["terminal", "file"]
    }
])

提示

每个子代理拥有独立的终端会话。它们可以在同一项目目录下工作而不会互相干扰——只要它们编辑的是不同文件。如果两个子代理可能触及同一文件,请在并行工作完成后自行处理该文件。


模式:收集后分析

使用 execute_code 进行机械性数据收集,然后将推理密集型分析委托出去:

python
## Step 1: Mechanical gathering (execute_code is better here — no reasoning needed)
execute_code("""
from hermes_tools import web_search, web_extract

results = []
for query in ["AI funding Q1 2026", "AI startup acquisitions 2026", "AI IPOs 2026"]:
    r = web_search(query, limit=5)
    for item in r["data"]["web"]:
        results.append({"title": item["title"], "url": item["url"], "desc": item["description"]})
## Extract full content from top 5 most relevant
urls = [r["url"] for r in results[:5]]
content = web_extract(urls)
## Save for the analysis step
import json
with open("/tmp/ai-funding-data.json", "w") as f:
    json.dump({"search_results": results, "extracted": content["results"]}, f)
print(f"Collected {len(results)} results, extracted {len(content['results'])} pages")
""")
## Step 2: Reasoning-heavy analysis (delegation is better here)
delegate_task(
    goal="Analyze AI funding data and write a market report",
    context="""Raw data at /tmp/ai-funding-data.json contains search results and
    extracted web pages about AI funding, acquisitions, and IPOs in Q1 2026.
    Write a structured market report: key deals, trends, notable players,
    and outlook. Focus on deals over $100M.""",
    toolsets=["terminal", "file"]
)

这通常是最有效的模式:execute_code 以低成本处理 10 次以上的顺序工具调用,然后子代理在干净的上下文中执行一次昂贵的推理任务。


工具集选择

根据子代理的需求选择工具集:

任务类型工具集原因
网络研究["web"]仅 web_search + web_extract
代码工作["terminal", "file"]Shell 访问 + 文件操作
全栈["terminal", "file", "web"]除消息外的一切
只读分析["file"]只能读取文件,无 shell

限制工具集可以让子代理保持专注,并防止意外副作用(例如研究子代理运行 shell 命令)。


约束

  • 默认 3 个并行任务:批次默认最多 3 个并发子代理(可通过 config.yaml 中的 delegation.max_concurrent_children 配置,无硬性上限,仅下限为 1)
  • 嵌套委托为可选:叶子子代理(默认)不能调用 delegate_taskclarifymemorysend_messageexecute_code。编排器子代理(role="orchestrator")保留 delegate_task 以进行进一步委托,但仅当 delegation.max_spawn_depth 提升至默认值 1 以上时(下限为 1,无上限);其余四个仍被阻止。可通过 delegation.orchestrator_enabled: false 全局禁用。

调整并发与深度

配置项默认值范围效果
max_concurrent_children3>=1每次 delegate_task 调用的并行批次大小
max_spawn_depth1>=1可进一步生成子代理的委托层级数

示例:运行 30 个并行工作器并允许嵌套子代理:

yaml
delegation:
  max_concurrent_children: 30
  max_spawn_depth: 2
  • 独立的终端——每个子代理拥有独立的终端会话,具有独立的工作目录和状态
  • 无对话历史——子代理只能看到父代理调用 delegate_task 时传递的 goalcontext
  • 默认 50 次迭代——对于简单任务,可设置更低的 max_iterations 以节省成本
  • 非持久性——delegate_task 是同步的,在父轮次内运行。如果父轮次被中断(新用户消息、/stop/new),所有活跃的子代理将被取消(status="interrupted"),其工作将被丢弃。对于需要跨越当前轮次的工作,请使用 cronjobterminal(background=True, notify_on_complete=True)

提示

目标要具体。“修复 bug”过于模糊。“修复 api/handlers.py 第 47 行中 process_request() 从 parse_body() 收到 None 导致的 TypeError”为子代理提供了足够的信息。

**包含文件路径。**子代理不知道你的项目结构。始终包含相关文件的绝对路径、项目根目录和测试命令。

**利用委托实现上下文隔离。**有时你需要一个全新的视角。委托迫使你清晰地阐述问题,而子代理不会受到对话中积累的假设影响。

**检查结果。**子代理的摘要只是摘要。如果子代理说“已修复 bug 且测试通过”,请通过自行运行测试或查看 diff 来验证。


有关完整的委托参考——所有参数、ACP 集成和高级配置——请参阅子代理委托


分享: