Learning resourcesReviewed · Pydantic

Pydantic AI Agents Guide

The Pydantic AI Agents guide helps Python developers build AI applications, but streamed answers can finish before requested tools run. It covers typed tools, validated outputs, conversation state, cancellation and usage controls.

Researched 23 Nov 2026

In short.

The Pydantic AI Agents guide is a practical reference for Python developers building AI applications, but its convenient streaming mode can finish before requested tools execute. It explains how to connect models to Python functions, validate returned data, retain conversations and recover interrupted work. Advanced sections cover execution events, concurrency and spending controls. Cost limits remain approximate, and cancellation does not undo tool side effects. Installation details, licence terms and the applicable package version are not established by this page. No examples were executed.

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

Coverage is limited to the complete selected Agents documentation page at [https://pydantic.dev/docs/ai/core-concepts/agent/index.md], including its documentation-index and query-parameter notices and supplied examples. Linked pages, API references, repositories, issue threads and licence documents are excluded. No code or provider calls were executed. Example outputs, costs, compatibility and operational behavior were not independently tested.

The overview

Resource identity

This is the Agents documentation page for Pydantic AI at [https://pydantic.dev/docs/ai/core-concepts/agent/index.md]. It teaches the framework's main interface for interacting with language models through explanatory text and Python examples.

The resource is a guide to configuring and running agents. Its scope extends from a small tool-calling example to streaming, execution graphs, usage limits, cancellation, monitoring and declarative agent configuration.

Practical assessment

The guide is useful when an application needs model responses connected to ordinary Python functions and validated data structures. Its strongest material explains operational details that short introductory examples can miss, including incomplete tool execution during streaming and recovery after failures.

It works best as an implementation reference for readers who already understand basic Python. The page provides no comparative benchmarks establishing better accuracy, lower latency or lower operating cost than other approaches.

Who it suits

Python developers adding AI features to services can use the guide to connect models to application data and functions. Developers building interactive assistants will find material on progress events, streamed responses, stop controls and conversation continuity.

Beginners can start with Agent, a registered tool and result.output. The later sections require familiarity with asynchronous programming, type hints, exceptions and application state.

What it covers

The page documents synchronous and asynchronous runs, text and structured-output streaming, raw execution events and node-by-node graph control. Agents can combine instructions, Python tools, typed dependencies, output types and reusable capabilities.

Additional topics include validation retries, conversation history, cancellation and resumption, model settings, run metadata, concurrency limits and queue limits. Agent configuration can also be loaded from YAML or JSON.

CustomEvent supports application progress signals, while CapabilityEvent serves reusable capabilities. The page also introduces Logfire tracing, OpenTelemetry-compatible backends and Pydantic Evals, although their full setup is covered elsewhere.

Using it

Requirements

Following the examples requires Python and the relevant Pydantic AI imports. Real model calls need a configured model backend; some demonstrations instead use TestModel or FunctionModel. Supported Python versions, package versions, installation commands, authentication requirements and hardware requirements are not specified here.

Type hints on tool parameters and output_type are used for runtime schemas and validation. Static checking with mypy or pyright is optional and can identify mismatched dependency or output types.

How agents work

An Agent combines developer instructions, a model, callable tools and optional dependency and output types. Dependencies provide application services or state through RunContext. The underlying pydantic-graph execution flow handles model requests, responses, tool calls and completion.

Pydantic validates tool arguments and structured output. Validation failures or an explicit ModelRetry can request another model response within configured retry budgets. Matching a schema establishes the requested data structure; it does not establish factual correctness.

The guide distinguishes instructions, which belong to the current agent, from system prompts that can remain in conversation history. Named instructions can append changing application state without repeatedly rewriting the original prompt prefix. Untrusted input belongs in user messages or tool results rather than privileged instructions.

Getting started

The documented starting pattern is to import Agent, select a model and supply instructions. Add output_type for a validated result, register functions with agent.tool or agent.tool_plain, and configure deps_type when tools need application dependencies.

Call run_sync for a synchronous entry point or await run in asynchronous code, then read result.output. Several asynchronous examples require adding an asyncio import and asyncio.run(main()). Package installation and provider authentication must be established separately.

An illustrative example

The introductory roulette example defines an Agent with an integer dependency and a boolean output. Its roulette_wheel tool compares the number supplied by the model with the dependency value, and the agent returns a validated boolean.

Despite the roulette framing, this example performs a fixed comparison rather than simulating a random wheel. It demonstrates how model-selected tool arguments, application-provided dependencies and typed results connect. The displayed True and False outputs are documentation examples; they were not reproduced through execution.

Assessment & evidence

Important limitations

With the default completion strategy, run_stream and run_stream_sync treat the first matching output as final. If a model returns text and additional tool calls while output_type is str, those tools may never run. The graceful and exhaustive strategies can execute remaining calls, but their results are not returned to the model after completion. Use run, run_stream_events or iter when the full tool-processing flow is required.

Cancellation is cooperative. A synchronous tool running in a worker thread can continue after cancellation, and completed side effects are not rolled back. Provider-side generation may also continue. Cancelled-stream usage is partial and unsuitable for precise billing accounting.

Unsupported model settings may be ignored, with warnings for settings that affect request guarantees. Raw event streaming requires assembling output from events. Custom-event payloads reach supported frontends by default unless configured otherwise, and serialization requires compatible event definitions.

The page does not establish application-specific accuracy, security, throughput or production reliability.

Why these features matter

Typed dependencies and validated outputs are useful when model responses must become inputs to other Python code. Graph inspection, event handling and resumable history offer control for applications that need visible progress and recovery from interruption.

The practical fit depends on whether these controls justify the additional framework concepts. Schema validation can catch malformed data, but application checks and task-specific evaluation are still needed to establish useful answers and appropriate tool behavior.

Available approaches

The page explains choices within Pydantic AI rather than comparing competing agent frameworks. run and run_sync return completed results; run_stream simplifies final-output streaming; run_stream_events exposes execution events; iter provides graph-level control with additional implementation complexity.

It identifies pydantic-graph as a standalone option for finite-state workflows, including work unrelated to generative AI. Relative simplicity, performance and cost against other libraries are not assessed.

Evidence and its limits

The source is the Agents page at [https://pydantic.dev/docs/ai/core-concepts/agent/index.md]. It provides API explanations, Python examples, illustrative outputs and explicit caveats about execution behavior.

The documentation supports descriptions of intended functionality. Its printed results are not independent measurements or deployment evidence. No code or provider calls were executed, and linked documentation, repositories and issue threads were not assessed.

Access & freshness

Costs and usage controls

Actual provider prices, any library or service charges, and total deployment costs are unknown from this page. Dollar amounts printed in examples do not establish the cost of a reader's workload. The Caching capability is described, but cache charges and savings are not quantified here.

UsageLimits can bound requests, tokens, successful tool calls and estimated USD cost. Token and cost checks generally occur after a response has arrived and been billed, so they can overshoot. Pre-request token counting can reject excessive input or an input-cost lower bound before sending a request.

Cost estimates depend on genai-prices and provider-reported usage. Missing prices or usage can leave totals incomplete. Request limits count committed model responses rather than every provider attempt, continuation or transport retry. The page recommends pairing cost_limit with request limits or provider spending controls.

Passing only message_history into a resumed run resets its usage accounting. Passing a Conversation carries cumulative usage forward, which matters when limits should cover earlier work too.

Licence and reuse

The page does not establish licence terms for the documentation, included examples or Pydantic AI library. Commercial-use and redistribution permissions are therefore unknown from this resource.

Version and freshness

The page was captured on 23 November 2026. Its applicable package version and last revision date are not stated.

Model identifiers, sample dates and example costs do not establish current model availability or pricing. Compatibility with a particular installed release remains unknown.

Suggested next steps

Confirm Python support, installation, provider authentication and licence terms for the package version you intend to use. Start with one harmless tool and a small output schema to understand the dependency and validation model.

Choose a run method based on whether you need streamed final text, complete tool execution or graph-level control. Evaluate mixed text-and-tool responses, invalid outputs, exhausted limits and cancellation with representative tasks.

Decide how to persist conversation usage, handle missing-usage warnings and record traces. Measure accuracy, latency and actual provider charges for your workload before relying on the documented patterns.

Evidence for this report

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