Learning resourcesReviewed · Pydantic

Pydantic AI Harness Background Tools Guide

This guide helps Python developers run slow Pydantic AI tools while an agent keeps working, but some streaming methods wait without delivering completed tool results. It documents the BackgroundTools capability, including tool selection, result messages, cancellation and integration limits.

Researched 25 Nov 2026

In short.

This guide shows Python developers how to let Pydantic AI agents continue during slow tool calls, but result delivery depends on the run interface and synchronous tools can delay cancellation. BackgroundTools immediately reports that a tool has started, then queues its result for a later model request using the same task ID. The documentation covers tool selection, retries, deferred calls, tracing and durable execution, and warns that Harness APIs can change between minor 0.x releases. No examples were executed, and pricing and licence terms are unknown from this page.

Researched and written by an AI model and checked by a second AI model. How it works

Coverage is limited to the complete documentation page at [https://pydantic.dev/docs/ai/harness/background-tools/index.md]. It includes installation, selectors, optional execution, bulk metadata, result and error handling, deferred calls, streaming and cancellation cautions, tracing, durable execution, agent specifications and the 0.x API stability notice. Linked documentation, the documentation index, repository contents and release guidance are excluded. No code was executed, links were not checked, and runtime behavior, performance, security effectiveness and provider compatibility were not independently assessed. Exact package versions, costs and licence terms remain unknown.

The overview

identity

Background Tools is a documentation guide for the BackgroundTools capability in Pydantic AI Harness. Its address is [https://pydantic.dev/docs/ai/harness/background-tools/index.md]. The resource teaches a Python framework feature rather than providing a standalone application.

The page links to implementation source at [https://github.com/pydantic/pydantic-ai/tree/main/src/pydantic_ai_harness/pydantic_ai_harness/background_tools/]. That repository's contents are outside the evidence available here.

assessment

The guide is useful when an agent has independent work to do while a slow tool runs. It explains both basic configuration and consequential edge cases, including which streaming methods omit results and how cancellation, retries and deferred tools interact.

Background execution permits overlap; the run normally still waits for its tools to finish. The page supplies no measured latency improvement, throughput benchmark or reliability results. Performance and suitability for a particular application remain unassessed.

users

The main audience is Python developers building Pydantic AI agents with slow research, crawling or similar tools. The feature is most relevant when another tool call or useful model work can proceed before those results arrive.

Beginners get installation commands and small examples, but the guide assumes familiarity with Python functions, decorators and agent configuration. Developers maintaining streaming interfaces, shared application state, execution hooks or durable workflows need the more detailed lifecycle sections.

capabilities

BackgroundTools() selects tools marked with metadata={'background': True}. Its tools parameter also accepts metadata filters, tool names or a predicate receiving the run context and tool definition. SetToolMetadata and FunctionToolset.with_metadata(...) can mark multiple tools together.

With metadata={'background': 'optional'}, the model chooses per call through a run_in_background argument. That argument is added to the model-facing tool interface and is not passed to the Python function. Tools explicitly selected through tools= always run in the background, subject to the documented execution exclusions.

The page also documents Temporal compatibility. For DBOS, durable work belongs in an explicit DBOS step called from the background tool. It warns against calling ctx.enqueue() inside a durable activity or task because those messages cannot be restored during replay.

Using it

requirements

The main example requires pydantic-ai-harness and the OpenAI extra for pydantic-ai-slim. It imports Agent from pydantic_ai and BackgroundTools from pydantic_ai_harness. The example model identifier is openai:gpt-6.1-sol; its availability and compatibility were not independently assessed.

The page does not specify a minimum Python version, pinned package versions, operating-system requirements or provider authentication steps. Applications using asynchronous tools must allow cancellation, and overlapping tools need appropriate protection for shared data.

mechanism

A selected call immediately returns a started message with a task ID. The model can continue working or end its turn. When the tool completes, its result becomes a BackgroundToolResultPart capability part queued for the next ModelRequest. The follow-up identifies the call through tool_name, tool_call_id and outcome fields.

The result reaches the model on the user channel, framed as tool-authored content with tool and call identifiers. Text, files and ToolReturn.content are included; ToolReturn.metadata is discarded. Vercel AI and AG-UI message conversions omit these capability parts, leaving the follow-ups in server-side history.

The page documents framed notifications for ModelRetry, ToolFailed, approval and deferral errors, and ValidationError raised by execution hooks. ModelRetry and ValidationError count toward retries when their follow-ups are delivered; a successful result resets the count. The started message does neither. Other exceptions, exhausted retries and CancelledError end the run, with any model request already in progress finishing first.

A run waits for background tools even when pausing for deferred calls. Pending calls count toward tool_calls_limit. At a deferred pause, results enter history after the paused step in call order so that a resumed run can see them, including after a restart.

setup

The documented installation commands are pip install "pydantic-ai-slim[openai]" pydantic-ai-harness or uv add "pydantic-ai-slim[openai]" pydantic-ai-harness. The example then constructs Agent('openai:gpt-6.1-sol', capabilities=[BackgroundTools()]) and decorates an asynchronous tool with @agent.tool_plain(metadata={'background': True}).

For model-controlled execution, use metadata={'background': 'optional'} and keep run_in_background out of the function's own parameters. For several related tools, the guide shows FunctionToolset([...]).with_metadata(background=True).

The separate YAML/JSON agent-spec example installs pydantic-ai-slim[spec] and pydantic-ai-harness, lists BackgroundTools under capabilities, and loads the file with Agent.from_file('agent.yaml', custom_capability_types=[BackgroundTools]). These are documented setup examples; none was run.

example

The main example defines slow_research(query: str), marks it for background execution, waits with asyncio.sleep(60), and returns a short research-findings string. The sleep is explicitly a placeholder for real work; the page supplies no research backend or measured output.

A practical adaptation would replace that placeholder with a research operation while allowing independent agent work to continue. If the final answer must incorporate the research, the guide directs readers to run(), run_sync(), run_stream_events(), or complete consumption of agent.iter().

Assessment & evidence

limitations

run_stream() and run_stream_sync() wait for background tools but do not deliver their results; the streamed response may only announce that work started. Results also remain undelivered in specified queue states involving a ModelResponse, an interrupted request or PendingModelResponse. agent.iter() exposes remaining content through AgentRun.pending_messages; run(), run_sync(), run_stream() and UI adapters drop undelivered queued results.

Stopping a run cancels unfinished background tools and drops results that have not been delivered. Asynchronous tools must cooperate with cancellation. Python cannot stop a synchronous tool before it returns, so cancellation still waits for that tool. A tool timeout bounds its wait, and a run timeout bounds the whole wait.

Sequential tools can overlap background work already underway, creating shared-state risks. Tools configured for sequential execution, realtime sessions and calls made by code mode's sandboxed run_code retain their normal behavior. DeferredToolRequests reaches the caller only after the slowest background tool finishes; HandleDeferredToolCalls can resolve approvals inside the run while background work continues.

Tool output is labelled as tool-authored, and the framing adds notices for text resembling frame tags. The page nevertheless warns that untrusted output can imitate another task's result and recommends delimiting or sanitizing it inside the tool. The effectiveness of these protections was not assessed.

BackgroundTools adds no tracing spans. The ordinary tool span ends with the started message and does not cover the actual work or record its failure. Hooks also observe different stages depending on capability order: execution hooks after BackgroundTools see the real result, while wrapping hooks before it and tool-result events see the started message.

RepairToolArguments, or Coder which includes it, should precede BackgroundTools. Otherwise malformed calls involving run_in_background are retried rather than repaired. A repaired call executes in the foreground.

reasoning

The strongest fit is a workflow with a slow tool and useful independent work that can proceed before its result arrives. Overlap offers little benefit when every next step depends on that result, and normal run completion still waits for pending work.

Interface choice is a central design decision because waiting for a tool does not guarantee that its output reaches the final answer. Cancellation behavior, shared-state protection and the tracing gap also affect whether the feature fits an application's operational needs. These conclusions follow from documented behavior rather than runtime measurements.

alternatives

Ordinary foreground execution is an option when the next step needs the tool's result immediately. For mixed workloads, optional background metadata lets the model choose per call instead of configuring every call to run in the background.

Realtime sessions already run tools concurrently, so this capability leaves them unchanged. The page offers no comparative evidence about other agent frameworks, task queues or background-job systems; their relative suitability is not assessed.

evidence

The evidence consists of the complete Background Tools documentation page at [https://pydantic.dev/docs/ai/harness/background-tools/index.md]. It includes installation commands, Python and agent-spec examples, lifecycle explanations and explicit cautions.

Linked documentation and implementation files were not examined. No commands, tools or examples were executed. Runtime behavior, provider compatibility, security properties and performance therefore remain documented claims rather than independently verified results.

Access & freshness

costs

The page states no package price, model rate, subscription requirement or total operating cost. Costs are unknown from this evidence.

Budgeting would require the chosen provider's pricing, actual model requests and token usage, and the work performed by each tool. The documentation supplies none of those measurements and establishes no cost saving from background execution.

rights

The page contains no licence text establishing reuse terms for the documentation, examples or implementation. Commercial-use and redistribution permissions are unknown from this evidence. The link to a GitHub source directory does not establish those permissions.

freshness

The documentation copy was captured on 25 November 2026 at 17:52:59.996 UTC. It provides no publication date, last-updated date or exact package release tied to the examples.

The page warns that Pydantic AI Harness APIs may change between minor releases while on 0.x, with deprecation warnings and release-note migration guidance. Compatibility with a particular installed version and changes after capture are unknown.

actions

Identify a slow tool with independent work the agent can do during the wait, then choose explicit or model-controlled background execution. Follow the installation and registration examples, checking compatibility with the package versions you intend to use.

Choose a run interface that delivers results when the final answer needs them. Before relying on the integration, verify result delivery, handled and unhandled failures, timeouts, cancellation, deferred approvals and shared-state behavior in your application. Account for the tracing gap and review the documented capability ordering if using RepairToolArguments or Coder.

For tools returning external content, delimit or sanitize that output as the guide recommends. Obtain applicable licence terms and provider pricing separately; neither is established by this page.

Evidence for this report

selected-page.txtselected · checked 2026-11-25