Skip to content

pydantic_ai.output

ToolOutput

Bases: Generic[OutputDataT]

Marker class to use a tool for output and optionally customize the tool.

Example:

tool_output.py
from pydantic import BaseModel

from pydantic_ai import Agent, ToolOutput


class Fruit(BaseModel):
    name: str
    color: str


class Vehicle(BaseModel):
    name: str
    wheels: int


agent = Agent(
    'openai:gpt-5.2',
    output_type=[
        ToolOutput(Fruit, name='return_fruit'),
        ToolOutput(Vehicle, name='return_vehicle'),
    ],
)
result = agent.run_sync('What is a banana?')
print(repr(result.output))
#> Fruit(name='banana', color='yellow')

Attributes

output

An output type or function.

Type: OutputTypeOrFunction[OutputDataT] Default: type_

name

The name of the tool that will be passed to the model. If not specified and only one output is provided, final_result will be used. If multiple outputs are provided, the name of the output type or function will be added to the tool name.

Type: str | None Default: name

description

The description of the tool that will be passed to the model. If not specified, the docstring of the output type or function will be used.

Type: str | None Default: description

max_retries

Per-tool retry limit for this output tool.

Overrides the agent-level output_retries default (which itself acts as the per-tool default for output tools that do not specify their own limit). If not set, the agent-level value is used.

Type: int | None Default: max_retries

strict

Whether to use strict mode for the tool.

Type: bool | None Default: strict

NativeOutput

Bases: Generic[OutputDataT]

Marker class to use the model’s native structured outputs functionality for outputs and optionally customize the name and description.

Example:

native_output.py
from pydantic_ai import Agent, NativeOutput

from tool_output import Fruit, Vehicle

agent = Agent(
    'openai:gpt-5.2',
    output_type=NativeOutput(
        [Fruit, Vehicle],
        name='Fruit or vehicle',
        description='Return a fruit or vehicle.'
    ),
)
result = agent.run_sync('What is a Ford Explorer?')
print(repr(result.output))
#> Vehicle(name='Ford Explorer', wheels=4)

Attributes

outputs

The output types or functions.

Type: OutputTypeOrFunction[OutputDataT] | Sequence[OutputTypeOrFunction[OutputDataT]] Default: outputs

name

The name of the structured output that will be passed to the model. If not specified and only one output is provided, the name of the output type or function will be used.

Type: str | None Default: name

description

The description of the structured output that will be passed to the model. If not specified and only one output is provided, the docstring of the output type or function will be used.

Type: str | None Default: description

strict

Whether to use strict mode for the output, if the model supports it.

Type: bool | None Default: strict

template

Template for the prompt passed to the model. The ‘{schema}’ placeholder will be replaced with the output JSON schema. If no template is specified but the model’s profile indicates that it requires the schema to be sent as a prompt, the default template specified on the profile will be used. Set to False to disable the schema prompt entirely.

Type: str | Literal[False] | None Default: template

PromptedOutput

Bases: Generic[OutputDataT]

Marker class to use a prompt to tell the model what to output and optionally customize the prompt.

Example:

prompted_output.py
from pydantic import BaseModel

from pydantic_ai import Agent, PromptedOutput

from tool_output import Vehicle


class Device(BaseModel):
    name: str
    kind: str


agent = Agent(
    'openai:gpt-5.2',
    output_type=PromptedOutput(
        [Vehicle, Device],
        name='Vehicle or device',
        description='Return a vehicle or device.'
    ),
)
result = agent.run_sync('What is a MacBook?')
print(repr(result.output))
#> Device(name='MacBook', kind='laptop')

agent = Agent(
    'openai:gpt-5.2',
    output_type=PromptedOutput(
        [Vehicle, Device],
        template='Gimme some JSON: {schema}'
    ),
)
result = agent.run_sync('What is a Ford Explorer?')
print(repr(result.output))
#> Vehicle(name='Ford Explorer', wheels=4)

Attributes

outputs

The output types or functions.

Type: OutputTypeOrFunction[OutputDataT] | Sequence[OutputTypeOrFunction[OutputDataT]] Default: outputs

name

The name of the structured output that will be passed to the model. If not specified and only one output is provided, the name of the output type or function will be used.

Type: str | None Default: name

description

The description that will be passed to the model. If not specified and only one output is provided, the docstring of the output type or function will be used.

Type: str | None Default: description

template

Template for the prompt passed to the model. The ‘{schema}’ placeholder will be replaced with the output JSON schema. If not specified, the default template specified on the model’s profile will be used. Set to False to disable the schema prompt entirely.

Type: str | Literal[False] | None Default: template

TextOutput

Bases: Generic[OutputDataT]

Marker class to use text output for an output function taking a string argument.

Example:

from pydantic_ai import Agent, TextOutput


def split_into_words(text: str) -> list[str]:
    return text.split()


agent = Agent(
    'openai:gpt-5.2',
    output_type=TextOutput(split_into_words),
)
result = agent.run_sync('Who was Albert Einstein?')
print(result.output)
#> ['Albert', 'Einstein', 'was', 'a', 'German-born', 'theoretical', 'physicist.']

Attributes

output_function

The function that will be called to process the model’s plain text output. The function must take a single string argument.

Type: TextOutputFunc[OutputDataT]

DeferredToolRequests

Tool calls that require approval or external execution.

This can be used as an agent’s output_type and will be used as the output of the agent run if the model called any deferred tools.

Results can be passed to the next agent run using a DeferredToolResults object with the same tool call IDs.

See deferred tools docs for more information.

Attributes

calls

Tool calls that require external execution.

Type: list[ToolCallPart] Default: field(default_factory=(list[ToolCallPart]))

approvals

Tool calls that require human-in-the-loop approval.

Type: list[ToolCallPart] Default: field(default_factory=(list[ToolCallPart]))

metadata

Metadata for deferred tool calls, keyed by tool_call_id.

Type: dict[str, dict[str, Any]] Default: field(default_factory=(dict[str, dict[str, Any]]))

Methods

build_results
def build_results(
    approvals: dict[str, bool | DeferredToolApprovalResult] | None = None,
    calls: dict[str, DeferredToolCallResult | Any] | None = None,
    metadata: dict[str, dict[str, Any]] | None = None,
    approve_all: bool = False,
) -> DeferredToolResults

Create a DeferredToolResults for these requests.

Returns

DeferredToolResults

Parameters

approvals : dict[str, bool | DeferredToolApprovalResult] | None Default: None

Results for tool calls that required approval. Keys must match tool_call_ids in self.approvals.

calls : dict[str, DeferredToolCallResult | Any] | None Default: None

Results for tool calls that required external execution. Keys must match tool_call_ids in self.calls.

metadata : dict[str, dict[str, Any]] | None Default: None

Per-call metadata, keyed by tool_call_id.

approve_all : bool Default: False

If True, every approval-requesting call not already listed in approvals is approved (with default ToolApproved()).

Raises
  • ValueError — If a key in approvals/calls doesn’t match a pending request of the appropriate kind.
remaining
def remaining(results: DeferredToolResults) -> DeferredToolRequests | None

Return unresolved requests after applying results, or None if all resolved.

Returns

DeferredToolRequests | None

StructuredDict

def StructuredDict(
    json_schema: JsonSchemaValue,
    name: str | None = None,
    description: str | None = None,
) -> type[JsonSchemaValue]

Returns a dict[str, Any] subclass with a JSON schema attached that will be used for structured output.

Example:

structured_dict.py
from pydantic_ai import Agent, StructuredDict

schema = {
    'type': 'object',
    'properties': {
        'name': {'type': 'string'},
        'age': {'type': 'integer'}
    },
    'required': ['name', 'age']
}

agent = Agent('openai:gpt-5.2', output_type=StructuredDict(schema))
result = agent.run_sync('Create a person')
print(result.output)
#> {'name': 'John Doe', 'age': 30}

Returns

type[JsonSchemaValue]

Parameters

json_schema : JsonSchemaValue

A JSON schema of type object defining the structure of the dictionary content.

name : str | None Default: None

Optional name of the structured output. If not provided, the title field of the JSON schema will be used if it’s present.

description : str | None Default: None

Optional description of the structured output. If not provided, the description field of the JSON schema will be used if it’s present.

OutputDataT

Covariant type variable for the output data type of a run.

Default: TypeVar('OutputDataT', default=str, covariant=True)