页面简介
Resolve deferred tool calls inside a Pydantic AI run with HandleDeferredToolCalls: approve, deny or answer them from a handler, or hand a resume token to a person and wait in process or suspended and recorded by a durable engine such as Temporal or AWS Lambda durable functions.
正文摘录
Handle Deferred Tool Calls HandleDeferredToolCalls is a capability that adds no tool for the model. It resolves the deferred tool calls that other tools raise: tools that require approval, external tools and CallDeferred calls, and the questions Pydantic AI Harness’s AskUser asks with answerer=None. Without it, the run ends with DeferredToolRequests output. With it, your handler resolves the calls and the same run continues: approved calls execute, denied ones are reported to the model, and external results and answers are filled in. handle_deferred_tool_calls.py from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import HandleDeferredToolCalls from pydantic_ai.tools import DeferredToolRequests, DeferredToolResults async def handle_deferred(ctx: RunContext, requests: DeferredToolRequests) -> DeferredToolResults: return requests.build_results(approve_all=True) # (1) agent = Agent('openai:gpt-6.1-sol', capabilities=[HandleDeferredToolCalls(handle_deferred)]) Auto-approve every call that's waiting on approval. Real handlers typically inspect requests.approvals and requests.calls and decide per call: check a policy, ask an operator, or execute an external call. Two forms of handler The handler is called with the run context and the pending DeferredToolRequests, and takes one of two forms: handler(ctx, requests) answers in place. It returns DeferredToolResults with results for some or all pending calls, or None to decline. The next deferred tool call handler gets what it leaves, and calls that no handler resolves end the run as DeferredToolRequests output as usual. It can be sync or async. handler(ctx, requests, token) can also hand a resume token on. A third required positional parameter selects this form. The handler answers in place the same way, or hands the token to whoever will answer and returns None. The run then waits until the token is resolved with the answer. Use the first form when the handler decides without waiting on anything outside the process. In a durable run, it isn’t recorded: when the engine replays the run, the handler runs again. Use the second form when the decision comes from outside, such as a person, or when a durable engine should record the answer. The handler then runs through wait_for_external_event, which a durable engine can implement. The engine records the token and the answer, and suspends the execution until the answer arrives. Without a durable engine, the wait happens in your process. Ending the run with DeferredToolRequests output and starting a new run with the answer, as Deferred Tools shows, remains an option when the run can’t stay open while it waits and has no durable engine to keep it. A handler that takes a token A handler that takes a token does one of two things: Answer in place: return the answer as DeferredToolResults, as a terminal prompt, a bot, a judge model or a policy does. Hand the token on: deliver the question and the token to where a person will see it and return None. That could be a Slack message with Approve and Deny buttons, an email with a link, or a row in a database table an admin UI lists. The answer comes back separately, through code you write elsewhere, such as the webhook behind the buttons, which resolves the token with it: Without a durable engine, call resolve_external_event(token, answer) in the process the run is waiting in. To end the wait without an answer, call fail_external_event(token, reason). On Temporal, the token names the workflow: send the answer with resolve_external_event(client, token, answer) from pydantic_ai.durable_exec.temporal, or end the wait with fail_external_event(client, token, reason). See The same agent on Temporal. On AWS Lambda durable functions, the token is a callback ID: send the answer with SendDurableExecutionCallbackSuccess, or end the wait with SendDurableExecutionCallbackFailure. See Approvals. The handler can be sync or async; a sync function runs in a worker thread, like a sync tool. An answer it returns goes through its JSON form, as a resolved answer does, so the run sees the same value either way. In a durable run, the handler runs once, inside a durable unit that records its answer and isn’t run again on replay. The engine can retry it when it fails, so make it return quickly and keep it idempotent, for example by keying the message or database row on the token. Anything that can take a while, such as a person, should answer through the token. A token handler that wants to leave every call to later handlers returns empty results, requests.build_results(). Returning None would make the run wait for the token. requests.kind(tool_call_id) tells you what each pending call waits for: an 'approval', an answer to a 'question' (such as those AskUser asks), or an 'external' result. Answering in place This handler approves refunds up to $100 itself and denies the rest, recording who answered: deferred_tool_policy.pyfrom pydantic_ai import Agent, DeferredToolRequests, DeferredToolResults, RunContext from pydantic_ai.capabilities import HandleDeferredToolCalls def refund_policy(ctx: RunContext, requests: DeferredToolRequests) -> DeferredToolResults: return requests.build_results( approvals={ call.tool_call_id: requests.validated_args[call.tool_call_id]['amount'] <= 100 for call in requests.approvals }, answered_by={call.tool_call_id: 'refund-policy' for call in requests.approvals}, ) agent = Agent('openai:gpt-6.1-sol', capabilities=[HandleDeferredToolCalls(refund_policy)]) @agent.tool_plain(requires_approval=True) def issue_refund(order_id: str, amount: int) -> str: return f'Refunded ${amount} for order {order_id}' result = agent.run_sync('Refund order 1234, it arrived broken.') print(result.output) #> I've refunded $50 for order 1234. answered_by is reported in the run’s DeferredToolResultsEvent. Pydantic AI does not check it. To have a durable engine record the policy’s answer, so a replay reuses it instead of deciding again, give the handler a token parameter: def refund_policy(ctx, requests, token). It still answers in place. A round trip in one process This FastAPI app hands the token on: it lists the pending approvals and resolves one when the approver posts a decision: deferred_tool_approval_endpoint.py import asyncio from datetime import timedelta from fastapi import FastAPI from pydantic_ai import Agent, DeferredToolRequests, RunContext from pydantic_ai.capabilities import HandleDeferredToolCalls from pydantic_ai.external_events import resolve_external_event pending: dict[str, DeferredToolRequests] = {} # (1) def ask(ctx: RunContext, requests: DeferredToolRequests, token: str) -> None: pending[token] = requests # (2) agent = Agent( 'openai:gpt-6.1-sol', capabilities=[HandleDeferredToolCalls(ask, timeout=timedelta(hours=1))], ) @agent.tool_plain(requires_approval=True) def issue_refund(order_id: str, amount: int) -> str: return f'Refunded ${amount} for order {order_id}' app = FastAPI() @app.get('/approvals') async def list_approvals() -> dict[str, list[str]]: return { token: [f'{call.tool_name}({call.args_as_json_str()})' for call in requests.approvals] for token, requests in pending.items() } @app.post('/approvals/{token}') async def decide(token: str, approved: bool) -> None: requests = pending.pop(token) decision = {'approvals': {call.tool_call_id: approved for call in requests.approvals}} resolve_external_event(token, decision) # (3) async def main(): run = asyncio.create_task(agent.run('Refund order 1234, it arrived broken.')) while not pending: # (4) await asyncio.sleep(0.01) print(list((await list_approvals()).values())) #> [['issue_refund({"order_id":"1234","amount":50})']] [token] = pending await decide(token, approved=True) result = await run print(result.output) #> I've refunded $50 for order 1234. The pending approvals, by token. A real app keeps them in a database, so an admin UI can list them. Hands the question and the token on, and returns None: the answer arrives through the token. Ends the wait the run is in. The run continues with the decision: the approved refund runs, and the model writes its reply. Stands in for the approver, who opens the approvals page and clicks Approve, which posts to /approvals/{token}. (To run this example, add asyncio.run(main()); no other changes are needed.) The wait lives in the process: if the process restarts, the run and its wait are gone, and resolving the old token raises a UserError. So does a token that is wrong, from another process, or already resolved, timed out or cancelled. For waits that must survive restarts, use a durable engine, or end the run with DeferredToolRequests output and store the conversation as Pausing a conversation shows. The same agent on AWS Lambda Under AWS Lambda durable functions, add AWSLambdaDurability and run the agent from a durable handler. The token is now a Lambda callback ID. The wait is recorded and suspends the execution, and the approval endpoint resolves the token through the Lambda API instead of resolve_external_event: deferred_tool_calls_lambda.py import json from datetime import timedelta from typing import Any import boto3 from aws_durable_execution_sdk_python import DurableContext, durable_execution from pydantic_ai_harness.aws_lambda import AWSLambdaDurability, durable_agent_handler from pydantic_ai import Agent, DeferredToolRequests, RunContext from pydantic_ai.capabilities import HandleDeferredToolCalls lambda_client = boto3.client('lambda') def ask(ctx: RunContext, requests: DeferredToolRequests, callback_id: str) -> None: ... # (1) agent = Agent( 'bedrock:global.anthropic.claude-sonnet-5-5', name='support', capabilities=[AWSLambdaDurability(), HandleDeferredToolCalls(ask, timeout=timedelta(days=1))], ) @agent.tool_plain(requires_approval=True) def issue_refund(order_id: str, amount: int) -> str: return f'Refunded ${amount} for order {order_id}' @durable_execution @durable_agent_handler async def handler(event: dict[str, Any], context: DurableContext) -> str: result = await a