页面简介
Add human-in-the-loop tool approval to Pydantic AI agents, or hand tool calls to a frontend or background worker, and resume the run with the results.
正文摘录
Deferred Tools There are a few scenarios where the model should be able to call a tool that should not or cannot be executed during the same agent run inside the same Python process: it may need to be approved by the user first it may depend on an upstream service, frontend, or user to provide the result the result could take longer to generate than it’s reasonable to keep the agent process running To support these use cases, Pydantic AI provides the concept of deferred tools, which come in two flavors documented below: tools that require approval tools that are executed externally When the model calls a deferred tool, there are two ways to resolve it: Resolve it inline, using a HandleDeferredToolCalls capability with a handler that resolves some or all of the pending calls. The agent run continues in a single call without needing to end and restart — use this when the resolver (e.g. an approval gate, an external service client) lives in the same process as the agent. See Resolving deferred calls with a handler. End the run with a DeferredToolRequests output object containing information about the deferred tool calls; the caller gathers approvals/results and then starts a new agent run with the original run’s message history plus a DeferredToolResults object. That follow-up is a separate agent run with its own run_id (do not reuse the paused run’s); keep pause/resume correlation via conversation_id. Use this when the resolver lives outside the agent process — e.g. a UI adapter that surfaces pending calls to a user and starts a follow-up run once it has their response. The two flows compose: a handler can resolve a subset of calls and let the rest bubble up as DeferredToolRequests output for an outer caller to handle. To wait for an answer from outside the process without ending the run, give the HandleDeferredToolCalls handler a third parameter, a resume token. It either answers right away or hands the token to the approver, and your approval endpoint resolves the token with the decision. By default the wait happens in your process. In a durable execution run on an engine that supports it, currently Temporal and AWS Lambda durable functions, the engine records the wait and suspends the run until the decision arrives. Each pending call says what it waits for: DeferredToolRequests.kind() returns 'approval' for a call in approvals, and 'question' or 'external' for one in calls. A tool marks a call as a question for the user, rather than work done elsewhere, with raise CallDeferred(kind='question'); Pydantic AI Harness’s AskUser does. The answer can say who gave it in DeferredToolResults.answered_by, which Pydantic AI reports but doesn’t check. The stop-the-world flow requires DeferredToolRequests to be in the Agent’s output_type so that the possible types of the agent run output are correctly inferred. If your agent can also be used in a context where no deferred tools are available and you don’t want to deal with that type everywhere you use the agent, you can instead pass the output_type argument when you run the agent using agent.run(), agent.run_sync(), agent.run_stream(), or agent.iter(). Note that the run-time output_type overrides the one specified at construction time (for type inference reasons), so you’ll need to include the original output type explicitly. Resolving deferred calls with a handler The recommended way to handle deferred tool calls is to register a HandleDeferredToolCalls capability whose handler receives the DeferredToolRequests and returns a DeferredToolResults resolving some or all of them. The tool execution pipeline applies the results inline and the agent run continues in a single call, as if the deferred tools had returned normally. With a handler in place, DeferredToolRequests no longer needs to be declared as an output type — unless you also want unresolved calls to bubble up to the caller (see below). DeferredToolRequests.build_results() is a convenience constructor — it validates that every tool call ID refers to a pending request of the correct kind, and accepts approve_all=True to auto-approve any approval requests not otherwise specified. deferred_tool_handler.py from pydantic_ai import ( Agent, ApprovalRequired, CallDeferred, DeferredToolRequests, DeferredToolResults, RunContext, ToolDenied, ) from pydantic_ai.capabilities import HandleDeferredToolCalls async def handle_deferred( ctx: RunContext, requests: DeferredToolRequests ) -> DeferredToolResults: approvals: dict[str, bool | ToolDenied] = {} for call in requests.approvals: if call.tool_name == 'delete_file': approvals[call.tool_call_id] = ToolDenied('Deleting files is not allowed') else: approvals[call.tool_call_id] = True calls = {call.tool_call_id: f'(external result for {call.tool_name})' for call in requests.calls} return requests.build_results(approvals=approvals, calls=calls) agent = Agent( 'openai:gpt-6.1-sol', capabilities=[HandleDeferredToolCalls(handler=handle_deferred)], ) @agent.tool_plain(requires_approval=True) def delete_file(path: str) -> str: return f'File {path!r} deleted' # (1) @agent.tool def update_file(ctx: RunContext, path: str, content: str) -> str: if path == '.env' and not ctx.tool_call_approved: raise ApprovalRequired return f'File {path!r} updated: {content!r}' @agent.tool_plain async def send_to_worker(task: str) -> str: raise CallDeferred # (2) Never reached here — the handler denies this call, so the model sees the denial message instead. The handler supplies the result for this external call, so the tool body just signals the deferral. If the handler declines to resolve some or all of the calls (by omitting them from the returned DeferredToolResults or returning None), the next HandleDeferredToolCalls (or any other capability that overrides the handle_deferred_tool_calls hook) gets a chance, and any still-unresolved calls bubble up as a DeferredToolRequests output. To allow that bubble-up, include DeferredToolRequests in the agent’s output_type — so you can combine inline handling with the stop-the-world flow when it makes sense. If you’re building a custom capability that needs to resolve approvals or external calls itself (e.g. a sandbox that exposes deferred tools), override the handle_deferred_tool_calls hook directly on your capability instead of registering a separate HandleDeferredToolCalls. The same hook is also available via the Hooks capability — see Hooks. The sections below describe the two kinds of deferred tools the handler can resolve, as well as the alternative stop-the-world flow for each. See Capabilities for how multiple capabilities compose, including WrapperCapability and the capabilities=[...] list. Human-in-the-Loop Tool Approval If a tool function always requires approval, you can pass the requires_approval=True argument to the @agent.tool decorator, @agent.tool_plain decorator, Tool class, FunctionToolset.tool decorator, or FunctionToolset.add_function() method. Inside the function, you can then assume that the tool call has been approved. To require approval for every tool in a FunctionToolset, pass requires_approval=True to its constructor. It applies to Tool instances too; only a function added with requires_approval=False opts out. In a realtime session, approval must be resolved inline, typically by a HandleDeferredToolCalls handler (a capability hook can resolve it too); a call nothing resolves is refused every time. If approval depends on the tool call’s arguments or the agent run context, such as dependencies or message history, raise ApprovalRequired from the tool function. The RunContext.tool_call_approved property will be True if the tool call has already been approved. You can also raise it from the tool’s args_validator, which runs before the tool function and lets you reject invalid arguments before asking a human to approve them. Base the decision on arguments and context your code can check, not on a confidence or risk score the model reports: see Don’t gate actions on model-reported confidence. To require approval for calls to tools provided by a toolset (like an MCP server), see the ApprovalRequiredToolset documentation. When the model calls a tool that requires approval, the agent run will end with a DeferredToolRequests output object with an approvals list holding ToolCallParts containing the tool name, the arguments as the model sent them, and a unique tool call ID. To show whoever approves a call what will run, read validated_args[call.tool_call_id] instead: the arguments the tool will receive, once validated against its schema and rewritten by any tool validation hook, such as after_tool_validate. The validated_args reference covers the form they’re stored in. run_stream() and run_stream_sync() don’t fill it for a call they end on because its tool requires approval or is external (#13690). validated_args includes each parameter’s default and any value a validation hook added, and it travels wherever the requests do, such as into a stored conversation, so a validation hook shouldn’t add a value, such as a credential, that the approver mustn’t see. The AG-UI approval prompt shows the client only the arguments the model sent. When the approved call resumes, the model’s arguments are validated again, hooks included. A validation hook whose output isn’t determined by the arguments alone, such as one that reads the time or an account balance, can then give the tool different arguments than validated_args showed. To make such a change only once the call is approved, rewrite the arguments in before_tool_execute instead, which for a requires_approval=True tool runs only once the call is approved. To let whoever approves the call change its arguments, approve it with ToolApproved(override_args=...); validation, hooks included, then runs on those arguments instead of the model’s. Once you’ve gathered the user’s approvals or denials, you can build a DeferredToolResults object with an approvals dictionary that maps each tool call ID to a boolean, a Tool