代码讲解.md 3.2 KB

S13 Background Tasks 代码讲解

这一节只讲相对 S12 新增的内容:

让慢工具调用进入后台线程执行,Agent 不必一直卡在原地等待。


1. 本节新增内容

  • background_tasks:记录后台任务状态。
  • background_results:保存后台任务结果。
  • background_lock:保护多线程共享数据。
  • is_slow_operation():判断某个命令是否可能很慢。
  • should_run_background():决定是否后台执行。
  • execute_tool():统一执行工具。
  • start_background_task():启动后台线程。
  • collect_background_results():收集已完成的后台任务结果。

2. 后台任务数据结构

background_tasks 是:

background_tasks: dict[str, dict]

结构大概是:

{
    "bg_0001": {
        "tool_use_id": "toolu_01xxx",
        "command": "npm install",
        "status": "running"
    }
}

background_results 是:

background_results: dict[str, str]

结构大概是:

{
    "bg_0001": "命令执行完成后的输出"
}

3. 为什么需要后台任务

有些命令会很慢:

npm install
pytest
docker build
make

如果同步执行,Agent Loop 会一直阻塞。

后台任务的目标是:

先返回一个“任务已启动”的 tool_result
慢命令在线程里继续跑
完成后再把结果作为通知注入 messages

4. should_run_background()

判断顺序:

如果模型显式传了 run_in_background=True:
    后台执行
否则:
    用 is_slow_operation() 做兜底判断

模型传参示例:

{
    "command": "npm install",
    "run_in_background": True
}

5. start_background_task(block)

block 是模型返回的 tool_use 对象:

{
    "type": "tool_use",
    "id": "toolu_01",
    "name": "bash",
    "input": {
        "command": "npm install",
        "run_in_background": True
    }
}

执行流程:

生成 bg_id
把任务登记到 background_tasks
启动 threading.Thread
立即返回 bg_id

后台线程执行完成后,会写入:

background_tasks[bg_id]["status"] = "completed"
background_results[bg_id] = output

6. collect_background_results()

作用:把完成的后台任务变成通知。

通知格式:

<task_notification>
  <task_id>bg_0001</task_id>
  <status>completed</status>
  <command>npm install</command>
  <summary>输出摘要</summary>
</task_notification>

这个通知会作为普通文本 block 注入下一轮用户消息。


7. Agent Loop 中的变化

工具调用时:

if should_run_background(block.name, block.input):
    bg_id = start_background_task(block)
    返回“后台任务已启动”
else:
    正常同步执行工具

每轮结束时:

bg_notifications = collect_background_results()
messages.append({"role": "user", "content": 工具结果 + 后台通知})

8. 本节课堂重点

后台任务让 Agent 可以处理慢操作。

它的本质不是模型变异步,而是 Harness 做了异步:

模型提出工具调用
程序决定后台执行
线程运行真实工具
结果完成后通过通知重新进入上下文