{"id":"kpj9-8eZ","creatorId":"anonymous","title":"#12686: run_stream() ends the run on a deferred tool call, bypassing HandleDeferredToolCalls","createdAt":1793955418141,"updatedAt":1793955418141,"latestVersionNum":1,"versions":[{"versionNum":1,"version":null,"branchName":null,"branchSha":null,"runRelease":true,"runBranch":false,"sdkDeps":{"pip":["Run with any Python >= 3.10; no model credentials needed (FunctionModel)","pydantic-ai with HandleDeferredToolCalls capability (capabilities module)"]},"snippets":[{"id":"repro","name":"run_stream() vs run()/run_stream_events() with a deferred tool call and an approve-all handler","code":"import asyncio\n\nfrom pydantic_ai import Agent, DeferredToolRequests\nfrom pydantic_ai.capabilities import HandleDeferredToolCalls\nfrom pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart\nfrom pydantic_ai.models.function import DeltaToolCall, FunctionModel\nfrom pydantic_ai.run import AgentRunResultEvent\n\n\ndef tool_ran(messages):\n    return any(isinstance(p, ToolReturnPart) and p.tool_name == 'delete_file' for m in messages for p in m.parts)\n\n\ndef fn(messages, info):\n    if tool_ran(messages):\n        return ModelResponse(parts=[TextPart('done')])\n    return ModelResponse(parts=[ToolCallPart('delete_file', {'path': 'a.txt'}, 'c1')])\n\n\nasync def stream_fn(messages, info):\n    if tool_ran(messages):\n        yield 'done'\n        return\n    yield {0: DeltaToolCall(name='delete_file', json_args='{\"path\": \"a.txt\"}', tool_call_id='c1')}\n\n\nasync def main():\n    for output_type in (str, [str, DeferredToolRequests]):\n        print(f'output_type={output_type}')\n        handler_calls = 0\n\n        async def approve_all(ctx, requests: DeferredToolRequests):\n            nonlocal handler_calls\n            handler_calls += 1\n            print(f'    [handler invoked #{handler_calls}]')\n            return requests.build_results(approve_all=True)\n\n        agent = Agent(\n            FunctionModel(fn, stream_function=stream_fn),\n            output_type=output_type,\n            capabilities=[HandleDeferredToolCalls(handler=approve_all)],\n        )\n\n        @agent.tool_plain(requires_approval=True)\n        def delete_file(path: str) -> str:\n            return f'deleted {path}'\n\n        result = await agent.run('rm a.txt')\n        print(f'  run():               {result.output!r}')\n\n        async with agent.run_stream_events('rm a.txt') as events:\n            async for ev in events:\n                if isinstance(ev, AgentRunResultEvent):\n                    print(f'  run_stream_events(): {ev.result.output!r}')\n\n        try:\n            async with agent.run_stream('rm a.txt') as s:\n                print(f'  run_stream():        {await s.get_output()!r}')\n        except Exception as e:\n            print(f'  run_stream():        {type(e).__name__}: {e}')\n        print(f'  handler invocations total across the three methods: {handler_calls}')\n\n\nasyncio.run(main())\n# Observed (pydantic-ai c833840):\n# output_type=<class 'str'>\n#   run():               'done'                      (handler invoked #1)\n#   run_stream_events(): 'done'                      (handler invoked #2)\n#   run_stream():        UserError: A deferred tool call was present, but `DeferredToolRequests` is not among output types. To resolve this, add `DeferredToolRequests` to the list of output types for this agent.\n# output_type=[<class 'str'>, <class 'pydantic_ai._deferred.DeferredToolRequests'>]\n#   run():               'done'                      (handler invoked #1)\n#   run_stream_events(): 'done'                      (handler invoked #2)\n#   run_stream():        DeferredToolRequests(calls=[], approvals=[ToolCallPart(tool_name='delete_file', args='{\"path\": \"a.txt\"}', tool_call_id='c1')], metadata={})\n#   handler invocations total across the three methods: 2   <- 0 during run_stream()","primaryOutput":null,"comparisonOutput":null}],"createdAt":1793955418141}]}