跳到主要内容

委派与并行工作

Hermes 可以生成独立的子 Agent 来并行处理任务。每个子 Agent 拥有自己的对话、终端会话和工具集。只有最终摘要会返回——中间工具调用永远不会进入你的上下文窗口。

完整的功能参考,请参阅子 Agent 委派


何时使用委派

适合委派的场景:

  • 推理密集型子任务(调试、代码审查、研究综合)
  • 会用中间数据淹没上下文的任务
  • 可并行的独立工作流(同时研究主题 A 和 B)
  • 需要全新上下文、希望 Agent 无偏见介入的任务

使用其他方式的场景:

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

模式:并行研究

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

Research these three topics in parallel:
1. Current state of WebAssembly outside the browser
2. RISC-V server chip adoption in 2025
3. Practical quantum computing applications

Focus on recent developments and key players.

底层,Hermes 使用:

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"]
}
])

三个任务同时运行。每个子 Agent 独立搜索网络并返回摘要。父 Agent 再将它们整合成一份连贯的简报。


模式:代码审查

将安全审查委派给全新上下文的子 Agent,让其在没有先入为主的情况下审视代码:

Review the authentication module at src/auth/ for security issues.
Check for SQL injection, JWT validation problems, password handling,
and session management. Fix anything you find and run the tests.

关键在于 context 字段——它必须包含子 Agent 需要的一切:

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"]
)
上下文问题

子 Agent 对你的对话一无所知。它们从零开始。如果你委派"修复我们讨论的那个 bug",子 Agent 根本不知道你说的是哪个 bug。始终明确传递文件路径、错误消息、项目结构和约束条件。


模式:比较替代方案

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

I need to add full-text search to our Django app. Evaluate three approaches
in parallel:
1. PostgreSQL tsvector (built-in)
2. Elasticsearch via django-elasticsearch-dsl
3. Meilisearch via meilisearch-python

For each: setup complexity, query capabilities, resource requirements,
and maintenance overhead. Compare them and recommend one.

每个子 Agent 独立研究一种方案。由于它们相互隔离,不会有交叉影响——每个评估自成一体。父 Agent 获取所有三份摘要后进行比较。


模式:多文件重构

将大型重构任务分配给并行子 Agent,每个负责代码库的不同部分:

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"]
}
])
提示

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


模式:收集后分析

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

# 步骤 1:机械性收集(这里 execute_code 更合适——不需要推理)
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"]})

# 从最相关的前 5 个提取完整内容
urls = [r["url"] for r in results[:5]]
content = web_extract(urls)

# 保存供分析步骤使用
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")
""")

# 步骤 2:推理密集型分析(这里委派更合适)
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 多个顺序工具调用,然后子 Agent 在干净的上下文中完成那一个昂贵的推理任务。


工具集选择

根据子 Agent 的需要选择工具集:

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

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


约束条件

  • 默认 3 个并行任务:批次默认同时运行 3 个子 Agent(可通过 config.yaml 中的 delegation.max_concurrent_children 配置,没有上限,最低为 1)
  • 嵌套委派需要显式开启:叶子子 Agent(默认)无法调用 delegate_taskclarifymemorysend_messageexecute_code。编排者子 Agent(role="orchestrator")保留 delegate_task 以实现进一步委派,但仅当 delegation.max_spawn_depth 高于默认值 1(支持 1-3)时才生效;其他四个仍然被阻止。通过 delegation.orchestrator_enabled: false 全局禁用。

调整并发度和深度

配置默认值范围效果
max_concurrent_children3>=1每次 delegate_task 调用的并行批次大小
max_spawn_depth11-3可进一步生成子 Agent 的委派层级数

示例:运行 30 个带嵌套子 Agent 的并行工作者:

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

提示

目标要具体。 "修复 bug"太模糊。"修复 api/handlers.py 第 47 行的 TypeError——process_request()parse_body() 接收到 None"才能给子 Agent 足够的信息。

包含文件路径。 子 Agent 不了解你的项目结构。始终包含相关文件的绝对路径、项目根目录和测试命令。

用委派实现上下文隔离。 有时你需要全新的视角。委派强迫你清晰地表达问题,子 Agent 在没有对话中积累的假设的情况下处理它。

检查结果。 子 Agent 的摘要只是摘要。如果子 Agent 说"修复了 bug 且测试通过",请自己运行测试或查看差异来验证。


完整的委派参考——所有参数、ACP 集成和高级配置——请参阅子 Agent 委派