《AI Agent 开发入门》14.2 超时、取消与结构化并发

asyncio.timeout 与 TaskGroup 通过取消协作任务实施超时。工具在 CancelledError 后清理资源并重新抛出,不能吞掉取消继续运行。同步线程、阻塞扩展和外部副作用不会因此被强制终止。to_thread 只转移阻塞工作;取消 await 不停止已经执行的线程。强终止需要独立进程与相应资源生命周期设计。

14.2 协作取消与任务清理

asyncio.timeout 与 TaskGroup 通过取消协作任务实施超时。工具在 CancelledError 后清理资源并重新抛出,不能吞掉取消继续运行。

实现选择

run_tools 接受异步 exec_tool,并检查正预算和重复调用 id。超时后未完成调用获得 timeout 反馈;组退出前等待任务 finally 完成。

同步线程、阻塞扩展和外部副作用不会因此被强制终止。to_thread 只转移阻塞工作;取消 await 不停止已经执行的线程。强终止需要独立进程与相应资源生命周期设计。

minagent/cancellation.py

# file: minagent/cancellation.py | write
from __future__ import annotations

import asyncio

async def run_with_timeout(coro, seconds: float):
    async with asyncio.timeout(seconds):
        return await coro

async def slow_tool(name: str, delay: float, log: dict) -> str:
    log["started"] += 1
    try:
        await asyncio.sleep(delay)
        log["ok"] += 1
        return f"{name} ok"
    except asyncio.CancelledError:
        log["cancelled"] += 1
        raise
    finally:
        log["finally"] += 1

async def leaky():
    log = {"started": 0, "ok": 0, "cancelled": 0, "finally": 0}
    orphan = asyncio.create_task(slow_tool("orphan", 5.0, log))  # 裸 task
    try:
        async with asyncio.timeout(0.2):
            await slow_tool("main", 1.0, log)
    except TimeoutError:
        print("超时触发(裸 task 版)")
    print("孤儿任务仍在运行:", not orphan.done())
    orphan.cancel()            # 必须手动收拾,否则泄漏
    await asyncio.gather(orphan,return_exceptions=True)

async def run_tools(calls, budget, exec_tool):
    if budget<=0 or len({tc.id for tc in calls})!=len(calls): raise ValueError("invalid budget/ids")
    results={}
    async def one(tc): results[tc.id]=await exec_tool(tc)
    try:
        async with asyncio.timeout(budget):
            async with asyncio.TaskGroup() as tg:
                for tc in calls: tg.create_task(one(tc))
    except TimeoutError:
        for tc in calls: results.setdefault(tc.id,'{"error":"timeout"}')
    return results

demo_cancel.py

# file: demo_cancel.py | write
from minagent.cancellation import slow_tool, leaky
import asyncio
async def main() -> None:
    log = {"started": 0, "ok": 0, "cancelled": 0, "finally": 0}
    try:
        async with asyncio.timeout(0.3):
            async with asyncio.TaskGroup() as tg:
                tg.create_task(slow_tool("a", 0.1, log))
                tg.create_task(slow_tool("b", 5.0, log))   # 远超预算
                tg.create_task(slow_tool("c", 0.2, log))
    except TimeoutError:
        print("超时触发:整组取消")
    print("统计:", log)
    leaked = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
    print("未完成的残留任务数:", len(leaked))
asyncio.run(main())
asyncio.run(leaky())

运行与练习

运行 demo_cancel.py;练习一个长工具触发 timeout 后,finally 应执行且没有残留协程。参考 ReliabilityTests.test_async_timeout_cleans_tasks。

下载全卷项目 。在项目根运行本节 demo 文件;练习检查与故障用例见 tests/test_book.py、tests/test_extensions.py 和附录 B。

阅读导航:上一节:14.1 分类错误与重试 · 下一节:14.3 幂等与副作用 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「agent」更多文章

  1. 《AI Agent 高级编程》目录
  2. 《AI Agent 高级编程》11.3 全景回顾:从零到框架的完整路径与展望
  3. 《AI Agent 高级编程》11.2 真实 API 冒烟:假模型 vs 真模型量化差距