#7172·adk-python

并行工具子任务取消后,同级任务继续运行到调用完成

作者: jaywang172创建于 2026年9月18日更新于 2026年9月30日
标签toolsrequest clarification

import asyncio from google.adk.agents import LlmAgent from google.adk.runners import Runner from google.adk.sessions import InMemorySessionService from google.genai import types from tests.unittests.testing_utils import MockModel

async def main(): trace = [] started, release = asyncio.Event(), asyncio.Event() sibling_task = None

async def stopper() -> dict:
    """Cancel this tool after its sibling starts."""
    await started.wait()
    trace.append("stopper:self_cancel")
    asyncio.current_task().cancel()
    await asyncio.sleep(0)  # Deliver this task's own cancellation.
    return {}

async def sibling() -> dict:
    """Represent a delayed side effect."""
    nonlocal sibling_task
    sibling_task = asyncio.current_task()
    trace.append("sibling:start")
    started.set()
    try:
        await release.wait()
        trace.append("sibling:side_effect")  # Local append only.
        return {"ok": True}
    finally:
        trace.append("sibling:finally")

async def after_agent(callback_context):
    trace.append("after_agent")

async def after_tool(tool, args, tool_context, tool_response):
    trace.append("after_tool:" + tool.name)

model = MockModel.create(responses=[[
    types.Part(function_call=types.FunctionCall(name=n, id=n, args={}))
    for n in ("stopper", "sibling")
]])
agent = LlmAgent(
    name="probe", model=model, tools=[stopper, sibling],
    after_agent_callback=after_agent, after_tool_callback=after_tool,
)
service = InMemorySessionService()
runner = Runner(app_name="scout", agent=agent, session_service=service)
session = await service.create_session(app_name="scout",

内容来源: google/adk-python