s13:Background Tasks——慢操作丢后台,Agent 继续思考
s13:Background Tasks——慢操作丢后台,Agent 继续思考
“慢操作丢后台,Agent 继续处理。” ——后台线程跑命令,完成后注入通知。
问题
你用过洗衣机吗?把衣服扔进去,按下启动,然后去干别的——做饭、回消息、看论文。30 分钟后洗衣机”滴滴滴”提醒你:好了。你不会站在洗衣机前面干等 30 分钟。
Agent 的 bash 工具也一样。pip install torch 要 10 分钟,npm run build 要 3 分钟。这些命令一跑,Agent 就在等 bash 工具返回,没法利用这段时间处理别的任务。
读文件是毫秒级,不等。git status 一秒内返回,不等。但 npm install?分钟级。Agent 等 10 分钟什么都不做,而 LLM 按 token 计费,空转就是浪费。
解决方案
慢操作扔到后台线程,Agent 继续跑循环,后台完成后把通知注入到对话里。
同步 vs 后台
| 同步 (s12) | 后台 (s13) | |
|---|---|---|
| 慢操作 | Agent 干等 | 后台线程执行 |
| Agent 空闲 | 是 | 否,继续处理 |
| 结果 | 立即返回 | 下轮注入通知 |
| 判断标准 | — | run_in_background 参数(模型显式请求),启发式兜底 |
工作原理
判断慢操作:显式请求优先,启发式兜底
模型通过 bash 工具的 run_in_background 参数显式请求后台执行。如果模型没指定,用关键词兜底:
def is_slow_operation(tool_name: str, tool_input: dict) -> bool:
if tool_name != "bash":
return False
cmd = tool_input.get("command", "").lower()
slow_keywords = ["install", "build", "test", "deploy", "compile",
"docker build", "pip install", "npm install",
"cargo build", "pytest", "make"]
return any(kw in cmd for kw in slow_keywords)
def should_run_background(tool_name: str, tool_input: dict) -> bool:
if tool_input.get("run_in_background"):
return True
return is_slow_operation(tool_name, tool_input)
后台执行:daemon 线程 + 状态追踪
background_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}
background_results: dict[str, str] = {} # bg_id → output
def start_background_task(block) -> str:
bg_id = f"bg_{next_counter():04d}"
def worker():
result = execute_tool(block)
with background_lock:
background_tasks[bg_id]["status"] = "completed"
background_results[bg_id] = result
with background_lock:
background_tasks[bg_id] = {
"tool_use_id": block.id,
"command": block.input.get("command", ""),
"status": "running",
}
thread = threading.Thread(target=worker, daemon=True)
thread.start()
return bg_id
返回 bg_id 而不是只返回 [Running in background...]。daemon=True 确保 Agent 进程退出时线程跟着退出。
通知收集:task_notification 格式
def collect_background_results() -> list[str]:
with background_lock:
ready_ids = [bid for bid, t in background_tasks.items()
if t["status"] == "completed"]
notifications = []
for bg_id in ready_ids:
with background_lock:
task = background_tasks.pop(bg_id)
output = background_results.pop(bg_id, "")
notifications.append(
f"<task_notification>\n"
f" <task_id>{bg_id}</task_id>\n"
f" <status>completed</status>\n"
f" <command>{task['command']}</command>\n"
f" <summary>{output[:200]}</summary>\n"
f"</task_notification>")
return notifications
通知不复用原始 tool_use_id。原始 tool call 已经用占位 tool_result 回复了,后台完成是独立事件。
循环中的集成
for block in response.content:
if block.type != "tool_use": continue
if should_run_background(block.name, block.input):
bg_id = start_background_task(block)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": f"[Background task {bg_id} started] "
f"Result will be available when complete."})
else:
output = execute_tool(block)
results.append({"type": "tool_result",
"tool_use_id": block.id, "content": output})
# 通知和工具结果合入同一条 user 消息
user_content = []
bg_notifications = collect_background_results()
for notif in bg_notifications:
user_content.append({"type": "text", "text": notif})
user_content.extend(results)
messages.append({"role": "user", "content": user_content})
合起来看
Turn 1:
LLM → bash "npm install" (run_in_background=true)
→ bg_0001 started
→ tool_result: "[Background task bg_0001 started]..."
→ LLM: "OK, I'll check later. Let me also read the config."
Turn 2:
LLM → read_file "package.json" (fast, sync)
→ bg_0001 done! inject <task_notification>
→ LLM sees: config file + install notification in one message
Agent 没干等——npm install 跑后台的时候,它去读了配置文件。
对比上一章
| 组件 | s12 | s13 |
|---|---|---|
| 执行模型 | 全部同步 | 慢操作后台线程 + 通知注入 |
| bash schema | command |
command + run_in_background |
| 循环 | 工具串行执行 | 慢操作异步,快操作同步,通知每轮收集 |
试一下
python s13_background_tasks/code.py
试试:
Run pip list in the background and find all Python filesRun npm install (use run_in_background) and while waiting, read package.json
观察:慢操作有没有被送到后台?后台通知有没有以 <task_notification> 格式注入?
接下来
后台任务解决了”慢操作不阻塞”。但如果想定时做某件事呢?比如”每天早上 9 点跑测试”。
s14 Cron Scheduler → 给 Agent 装一个闹钟。