pydantic_ai.durable_exec
Temporal Workflow base class that provides __pydantic_ai_agents__ for direct agent registration.
Accepts any AbstractAgent — either a regular Agent carrying a
TemporalDurability
capability, or the deprecated
TemporalAgent wrapper.
PydanticAIPlugin
walks the sequence and registers each agent’s activities with the worker.
Bases: DurableRunContext[AgentDepsT]
The RunContext subclass to use to serialize and deserialize the run context for use inside a Temporal activity.
By default, only the deps, run_id, conversation_id, metadata, retries, tool_call_id, tool_name, tool_call_approved, tool_call_metadata, retry, max_retries, run_step, usage, usage_limits, deadline, partial_output, trace_include_content, instrumentation_version, loaded_capability_ids, discovered_tool_names, the private dispatch-only availability supplements, and capability_active attributes will be available. Reading any other attribute (except validation_context, which is rebuilt as described below) raises a UserError explaining how to make it available, rather than returning its default value, so a field that didn’t cross the boundary can’t be mistaken for real run state.
agent and root_capability are re-attached from the worker’s agent instance, pending_messages holds a guard that makes enqueue raise inside an activity, and tool_manager and realtime_session are None: they hold live run state that isn’t serializable (for tool_manager, available_tool_names returns the resolved snapshot serialized at activity dispatch time, falling back to discovered_tool_names if a custom subclass doesn’t carry it, and tool_name_for_kind answers from a kind-to-name snapshot taken at the same time; for realtime_session, None already means “not available here”). The capabilities registry is excluded for the same reason — it holds live capability objects (toolsets, hooks, callables) — so active_capability_ids likewise returns a snapshot serialized at dispatch time, which is what lets is_tool_available answer for a capability-owned tool inside an activity; reading capabilities itself still raises. model is excluded as a live object too. tracer can’t cross the boundary either, so it’s resolved from the worker’s agent instead: the tracer of its instrumentation settings when it’s instrumented, otherwise the no-op tracer an uninstrumented run uses, so a tool that opens spans works inside an activity as it does in-process. trace_include_content then stays True only if that instrumentation also includes content, since the activity’s spans go to it. A subclass whose deserialize_run_context sets tracer itself keeps that value and its carried trace_include_content. messages is excluded because the full history would be duplicated into every activity payload, and prompt is excluded because a multi-modal prompt can carry large BinaryContent that would likewise ride in every activity payload, risking Temporal’s 2 MB limit. model_settings is excluded because it’s only set for model requests, which receive it as their own activity parameter, and validation_context because it’s an arbitrary user object with no serialization contract: it’s rebuilt from the agent’s validation_context setting the first time it’s read. A live workspace cannot cross the activity boundary either: only its WorkspaceRef is serialized, and the activity rebuilds workspace from it through the agent’s capabilities (their get_workspace, which may read only deps and the fields listed here), policy wrappers included. A subclass whose deserialize_run_context sets workspace itself keeps that value.
To make another attribute available, create a TemporalRunContext subclass with a custom serialize_run_context class method that returns a dictionary that includes the attribute and pass it as the run_context_type argument to TemporalDurability. A subclass can use this escape hatch to opt in to carrying prompt if it knows its prompts are text-only.
@async
def emit(event: CustomEventT, /) -> CustomEventT
def emit(event: CapabilityEventT, /) -> CapabilityEventT
Reject emit from inside a Temporal activity.
Tools and event stream handlers run inside activities where the run’s event stream isn’t
reachable, so events emitted there can’t currently flow back into the stream; raising beats
silently dropping them. This covers a capability’s own tools emitting a CapabilityEvent,
which run in activities like any other tool. Events emitted workflow-side (e.g. from
capability hooks) work as usual.
Lifting this needs a transport from the activity back to the workflow and a decision on what a retried attempt’s events mean; tracked in https://github.com/pydantic/pydantic-ai/issues/7971.
@classmethod
def deserialize_run_context(
cls,
ctx: dict[str, Any],
deps: Any,
) -> TemporalRunContext[Any]
Deserialize the run context from a dict[str, Any].
TemporalRunContext[Any]
Bases: DurableOperationNamer
Generate Temporal activity names that are persisted compatibility data.
These names must essentially never change. Changing them can strand in-flight workflows and recorded runs.
Bases: SimplePlugin
Temporal client plugin for Logfire.
Function that configures Logfire and Pydantic AI instrumentation and returns the
Logfire instance. By default, the plugin uses the already-configured global instance (configuring it
if needed) and instruments Pydantic AI unless it already is. With replay_safe (the default), the
function is called once, the first time the plugin needs the instance.
metrics : bool Default: True
Whether to send Temporal metrics to Logfire.
How often to export Temporal metrics. Defaults to 60 seconds.
replay_safe : bool Default: True
Whether to make the Logfire instance’s tracing replay-safe, so replaying workflow history
doesn’t emit duplicate spans. Applies to the instance returned by setup_logfire too.
The Workflow Stream topic a durable agent run publishes its events to.
Pass this — or, for the default settings, just the topic name — as
TemporalDurability’s
event_stream_topic. The capability keeps it, so
stream_agent_events()
knows which topic to subscribe to without the name being written out again.
The topic name. Different agents (or different purposes) belong on different topics.
Type: str
Optional predicate selecting which events to publish; by default every event is published.
A model stream emits a PartDeltaEvent per token, and
every published event stays in workflow state for the life of the run, so dropping deltas can
substantially cut both cost and workflow size.
The terminal AgentRunResultEvent is always published: it
is what tells a subscriber the run is over.
Type: Callable[[AgentStreamEvent], bool] | None Default: None
How often a model-request activity flushes buffered events to the workflow.
Type: timedelta Default: _DEFAULT_BATCH_INTERVAL
Bases: PydanticPayloadConverter
Temporal Pydantic payload converter with memoized deserialization adapters.
Custom payload converters can inherit from this class to retain the adapter cache while replacing or extending other conversion behavior.
Hosts the Workflow Stream a durable agent run publishes its events to.
Construct one in your workflow’s @workflow.init and use it as an async context manager around
the agent run:
from temporalio import workflow
from pydantic_ai import Agent
from pydantic_ai.durable_exec.temporal import AgentEventStream, TemporalDurability
agent = Agent(
'openai:gpt-5.6-sol',
name='assistant',
capabilities=[TemporalDurability(event_stream_topic='agent-events')],
)
@workflow.defn
class AssistantWorkflow:
@workflow.init
def __init__(self, prompt: str) -> None:
self.events = AgentEventStream()
@workflow.run
async def run(self, prompt: str) -> str:
async with self.events:
result = await agent.run(prompt)
return result.output
Leaving the block waits for a subscriber to acknowledge that it consumed the terminal
AgentRunResultEvent. That wait is not bookkeeping: a
Workflow Stream is served by the workflow itself, so once the workflow returns, its stream can no
longer be read and anything a subscriber had not yet polled is gone. Nobody watching, or a
subscriber that went away, is not an error — the wait is bounded by drain_timeout and the run’s
result stays authoritative either way.
The underlying WorkflowStream, for publishing your own topics or for continue_as_new().
Type: WorkflowStream
def __init__(
stream: WorkflowStream | None = None,
*,
prior_state: WorkflowStreamState | None = None,
drain_timeout: timedelta = _DEFAULT_DRAIN_TIMEOUT,
) -> None
Construct the stream. Must be called from the workflow’s @workflow.init method.
stream : WorkflowStream | None Default: None
An existing WorkflowStream to publish to, if your workflow already hosts one for
its own topics. By default a new one is created. Only one WorkflowStream can be
registered per workflow.
prior_state : WorkflowStreamState | None Default: None
Stream state carried across continue-as-new, when the stream is created here.
Ignored when stream is given, as that one was constructed with its own.
How long to wait for a subscriber to acknowledge the terminal event before finishing anyway, so a run nobody is watching can’t hang.
@async
def close() -> None
Wait for a subscriber to drain the stream, then release any that are still polling.
Bases: WrapperAgent[AgentDepsT, OutputDataT]
def __init__(
wrapped: AbstractAgent[AgentDepsT, OutputDataT],
*,
name: str | None = None,
models: Mapping[str, Model] | None = None,
provider_factory: TemporalProviderFactory | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
activity_config: ActivityConfig | None = None,
model_activity_config: ActivityConfig | None = None,
toolset_activity_config: dict[str, ActivityConfig] | None = None,
tool_activity_config: dict[str, dict[str, ActivityConfig | Literal[False]]] | None = None,
run_context_type: type[TemporalRunContext[AgentDepsT]] = TemporalRunContext[AgentDepsT],
temporalize_toolset_func: Callable[[AbstractToolset[AgentDepsT], str, ActivityConfig, dict[str, ActivityConfig | Literal[False]], type[AgentDepsT], type[TemporalRunContext[AgentDepsT]], AbstractAgent[AgentDepsT, Any] | None], AbstractToolset[AgentDepsT]] = temporalize_toolset,
)
Wrap an agent to enable it to be used inside a Temporal workflow, by automatically offloading model requests, tool calls, and MCP server communication to Temporal activities.
After wrapping, the original agent can still be used as normal outside of the Temporal workflow, but any changes to its model or toolsets after wrapping will not be reflected in the durable agent.
The agent to wrap.
Optional unique agent name to use in the Temporal activities’ names. If not provided, the agent’s name will be used.
Optional mapping of model instances to register with the agent.
Keys define the names that can be referenced at runtime and the values are Model instances.
Registered model instances can be passed directly to run(model=...).
If the wrapped agent doesn’t have a model set and none is provided to run(),
the first model in this mapping will be used as the default.
provider_factory : TemporalProviderFactory | None Default: None
Optional callable used when instantiating models from provider strings (those supplied at runtime).
The callable receives the provider name and the current run context, allowing custom configuration such as injecting API keys stored on deps.
Note: This factory is only used inside Temporal workflows. Outside workflows, model strings are resolved using the default provider behavior.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use instead of the one set on the wrapped agent.
activity_config : ActivityConfig | None Default: None
The base Temporal activity config to use for all activities. If no config is provided, a start_to_close_timeout of 60 seconds is used.
model_activity_config : ActivityConfig | None Default: None
The Temporal activity config to use for model request activities. This is merged with the base activity config.
The Temporal activity config to use for get-tools and call-tool activities for specific toolsets identified by ID. This is merged with the base activity config.
The Temporal activity config to use for specific tool call activities identified by toolset ID and tool name.
This is merged with the base and toolset-specific activity configs.
If a tool does not use IO, you can specify False to disable using an activity.
Note that the tool is required to be defined as an async function as non-async tools are run in threads which are non-deterministic and thus not supported outside of activities.
run_context_type : type[TemporalRunContext[AgentDepsT]] Default: TemporalRunContext[AgentDepsT]
The TemporalRunContext subclass to use to serialize and deserialize the run context for use inside a Temporal activity.
See TemporalRunContext for the attributes that are available by default.
To make another attribute available, create a TemporalRunContext subclass with a custom serialize_run_context class method that returns a dictionary that includes the attribute.
temporalize_toolset_func : Callable[[AbstractToolset[AgentDepsT], str, ActivityConfig, dict[str, ActivityConfig | Literal[False]], type[AgentDepsT], type[TemporalRunContext[AgentDepsT]], AbstractAgent[AgentDepsT, Any] | None], AbstractToolset[AgentDepsT]] Default: temporalize_toolset
Optional function to use to prepare “leaf” toolsets (i.e. those that implement their own tool listing and calling) for Temporal by wrapping them in a TemporalWrapperToolset that moves methods that require IO to Temporal activities.
If not provided, only FunctionToolset and MCPToolset will be prepared for Temporal.
The function takes the toolset, the activity name prefix, the toolset-specific activity config, the tool-specific activity configs and the run context type.
@async
def run(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[OutputDataT]
def run(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[RunOutputDataT]
Run the agent with a user prompt in async mode.
This method builds an internal agent graph (using system prompts, tools and result schemas) and then runs the graph to completion. The result of the run is returned.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
agent_run = await agent.run('What is the capital of France?')
print(agent_run.output)
#> The capital of France is Paris.
AgentRunResult[Any] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
Inside workflows, only registered model instances, registered names, or provider strings are valid.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Token used to cancel this run from another task or thread. Single-use:
mint a fresh token per run, as a reused (already-cancelled) token prevents the run from starting.
Inside a workflow, create it in workflow code and fire it from a @workflow.signal handler so
the cancellation is deterministic on replay.
Unsupported by the deprecated TemporalAgent; passing one raises UserError. Use the
TemporalDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def compact_history(
message_history: Sequence[_messages.ModelMessage],
*,
focus: str | None = None,
reason: _messages.CompactionReason = 'manual',
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
spec: dict[str, Any] | AgentSpec | None = None,
) -> CompactionRunResult
Compact a message history without continuing the conversation, as a run of this agent’s Temporal-wrapped run.
See AbstractAgent.compact_history. Run through this
agent’s own run(), not forwarded to the wrapped agent as WrapperAgent does, so it gets the wrapper’s model activity and toolsets inside a workflow.
def run_sync(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[OutputDataT]
def run_sync(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[RunOutputDataT]
Synchronously run the agent with a user prompt.
This is a convenience method that wraps self.run with loop.run_until_complete(...).
You therefore can’t use this method inside async code or if there’s an active event loop.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
result_sync = agent.run_sync('What is the capital of Italy?')
print(result_sync.output)
#> The capital of Italy is Rome.
AgentRunResult[Any] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Token used to cancel this run from another task or thread. Single-use: mint a fresh token per run, as a reused (already-cancelled) token prevents the run from starting.
Unsupported by the deprecated TemporalAgent; passing one raises UserError. Use the
TemporalDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def run_stream(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, OutputDataT]]
def run_stream(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, RunOutputDataT]]
Run the agent with a user prompt in async mode, returning a streamed response.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
async with agent.run_stream('What is the capital of the UK?') as response:
print(await response.get_output())
#> The capital of the UK is London.
AsyncGenerator[StreamedRunResult[AgentDepsT, Any]] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Token used to cancel this run from another task or thread. Single-use: mint a fresh token per run, as a reused (already-cancelled) token prevents the run from starting.
Unsupported by the deprecated TemporalAgent; passing one raises UserError. Use the
TemporalDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run. It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
def run_stream_events(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRunEvents[OutputDataT]]
def run_stream_events(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRunEvents[RunOutputDataT]]
Run the agent with a user prompt in async mode and stream events from the run.
This is a convenience method that wraps self.run and
uses the event_stream_handler kwarg to get a stream of events from the run.
Example:
from pydantic_ai import Agent, AgentRunResultEvent, AgentStreamEvent
agent = Agent('openai:gpt-5.2')
async def main():
collected: list[AgentStreamEvent | AgentRunResultEvent] = []
async with agent.run_stream_events('What is the capital of France?') as events:
async for event in events:
collected.append(event)
print(collected)
'''
[
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
FinalResultEvent(tool_name=None, tool_call_id=None),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
PartEndEvent(
index=0, part=TextPart(content='The capital of France is Paris. ')
),
AgentRunResultEvent(
result=AgentRunResult(output='The capital of France is Paris. ')
),
]
'''
Arguments are the same as for self.run,
except that event_stream_handler is now allowed.
AbstractAsyncContextManager[AgentRunEvents[Any]] — An async context manager that yields an AgentRunEvents
AbstractAsyncContextManager[AgentRunEvents[Any]] — handle over AgentStreamEvents ending with a final AgentRunResultEvent carrying the run result.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Token used to cancel this run from another task or thread. Single-use: mint a fresh token per run, as a reused (already-cancelled) token prevents the run from starting.
Unsupported by the deprecated TemporalAgent; passing one raises UserError. Use the
TemporalDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def iter(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, OutputDataT]]
def iter(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, RunOutputDataT]]
A contextmanager which can be used to iterate over the agent graph’s nodes as they are executed.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
AgentRun object. The AgentRun can be used to async-iterate over the nodes of the graph as they are
executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
stream of events coming from the execution of tools.
The AgentRun also provides methods to access the full message history, new messages, and usage statistics,
and the final result of the run once it has completed.
For more details, see the documentation of AgentRun.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
nodes = []
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
UserPromptNode(
user_prompt='What is the capital of France?',
instructions_functions=[],
system_prompts=(),
system_prompt_functions=[],
system_prompt_dynamic_functions={},
),
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
conversation_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(
cost=Decimal('0.000196'), input_tokens=56, output_tokens=7
),
model_name='gpt-5.2',
model_id='openai:gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
conversation_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
assert agent_run.result is not None
print(agent_run.result.output)
#> The capital of France is Paris.
AsyncGenerator[AgentRun[AgentDepsT, Any]] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Token used to cancel this run from another task or thread. Single-use:
mint a fresh token per run, as a reused (already-cancelled) token prevents the run from starting.
Inside a workflow, create it in workflow code and fire it from a @workflow.signal handler so
the cancellation is deterministic on replay.
Unsupported by the deprecated TemporalAgent; passing one raises UserError. Use the
TemporalDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
def override(
*,
name: str | _utils.Unset = _utils.UNSET,
deps: AgentDepsT | _utils.Unset = _utils.UNSET,
model: models.Model | models.KnownModelName | str | _utils.Unset = _utils.UNSET,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | _utils.Unset = _utils.UNSET,
tools: Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | _utils.Unset = _utils.UNSET,
native_tools: Sequence[AgentNativeTool[AgentDepsT]] | _utils.Unset = _utils.UNSET,
instructions: _instructions.AgentInstructions[AgentDepsT] | _utils.Unset = _utils.UNSET,
capabilities: Sequence[AgentCapability[AgentDepsT]] | _utils.Unset = _utils.UNSET,
metadata: AgentMetadata[AgentDepsT] | _utils.Unset = _utils.UNSET,
model_settings: AgentModelSettings[AgentDepsT] | _utils.Unset = _utils.UNSET,
retries: int | AgentRetries | _utils.Unset = _utils.UNSET,
spec: dict[str, Any] | AgentSpec | None = None,
workspace: WorkspaceBackend | Workspace | WorkspaceRef | Literal['new'] | _utils.Unset = _utils.UNSET,
) -> Generator[None]
Context manager to temporarily override agent configuration.
This is particularly useful when testing. You can find an example of this here.
name : str | _utils.Unset Default: _utils.UNSET
The name to use instead of the name passed to the agent constructor and agent run.
The dependencies to use instead of the dependencies passed to the agent run.
model : models.Model | models.KnownModelName | str | _utils.Unset Default: _utils.UNSET
The model to use instead of the model passed to the agent run.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The toolsets to use instead of the toolsets passed to the agent constructor and agent run.
tools : Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, …]] | _utils.Unset Default: _utils.UNSET
The tools to use instead of the tools registered with the agent.
native_tools : Sequence[AgentNativeTool[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The native tools to use instead of the agent’s configured native tools.
instructions : _instructions.AgentInstructions[AgentDepsT] | _utils.Unset Default: _utils.UNSET
The instructions to use instead of the instructions registered with the agent.
capabilities : Sequence[AgentCapability[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The capabilities to use instead of the agent’s configured capabilities. When set,
these replace (not merge with) the agent’s existing capabilities. To add to the existing
set, include them explicitly:
agent.override(capabilities=[*agent.root_capability.capabilities, extra]).
Inside a Temporal workflow, capabilities can’t be overridden and raises a UserError.
The metadata to use instead of the metadata passed to the agent constructor. When set, any
per-run metadata argument is ignored.
model_settings : AgentModelSettings[AgentDepsT] | _utils.Unset Default: _utils.UNSET
The model settings to use instead of the model settings passed to the agent constructor.
When set, any per-run model_settings argument is ignored.
retries : int | AgentRetries | _utils.Unset Default: _utils.UNSET
The retry budgets to use instead of the agent-level configuration. Pass an int to
override both the tool-retry and output budgets, or an AgentRetries
dict to override just one (e.g. retries={'tools': 3}). When set, any per-run retries argument is ignored.
Optional agent spec to apply as overrides.
workspace : WorkspaceBackend | Workspace | WorkspaceRef | Literal[‘new’] | _utils.Unset Default: _utils.UNSET
Workspace for every run in this context, in place of a per-run workspace= argument.
Bases: BaseDurabilityCapability[AgentDepsT]
Capability that makes an agent durable by routing I/O through Temporal activities.
When added to an agent, this capability intercepts model requests and wraps toolsets to route their I/O through Temporal activities. Outside of workflows, the capability is transparent.
The capability discovers the agent’s model, name, and toolsets
automatically via for_agent(). Only Temporal-specific configuration
needs to be passed to the constructor.
The TemporalRunContext subclass used to serialize/deserialize the run context.
Type: type[TemporalRunContext[AgentDepsT]] Default: run_context_type
Function called when Temporal suggests continuing as new, or None to disable continuation.
Type: ContinueAsNewHandler[AgentDepsT] | None Default: continue_as_new
Base Temporal activity config used for all activities.
Type: ActivityConfig Default: activity_config
All Temporal activities registered by this capability.
These can be registered directly with a Temporal worker only when no tool is configured
to run as a child workflow. Use AgentPlugin or PydanticAIPlugin when child workflows
are present so both activity and workflow definitions are registered.
def __init__(
*,
models: Mapping[str, Model] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
event_stream_topic: str | WorkflowStreamTopic | None = None,
name: str | None = None,
deps_type: type[AgentDepsT] | None = None,
activity_config: ActivityConfig | None = None,
model_activity_config: ActivityConfig | None = None,
event_stream_handler_activity_config: ActivityConfig | None = None,
toolset_activity_config: dict[str, ActivityConfig] | None = None,
run_context_type: type[TemporalRunContext[AgentDepsT]] = TemporalRunContext[AgentDepsT],
continue_as_new: ContinueAsNewHandler[AgentDepsT] | None = None,
non_retryable_model_errors: Sequence[type[ModelAPIError]] = _DEFAULT_NON_RETRYABLE_MODEL_ERRORS,
)
Create a TemporalDurability capability.
The agent’s model, name, and toolsets are discovered automatically
when the capability is attached to an agent (via for_agent()).
Optional additional models keyed by ID for runtime model
switching. The agent’s primary model is always registered as
'default'. A Model instance can’t be serialized across the
activity boundary, so a run-time model (via agent.run(model=...)
/ agent.override(model=...), or swapped in by an outer capability)
has to be registered here and referenced by key (or passed as the
registered instance); an unregistered instance is rejected, because
rebuilding it from its model_id would build a different model.
Model-name strings never need registering: they cross as the string
the caller wrote and are built on the worker by the agent’s
resolve_model_id capability chain, then infer_model. To build a
specific instance on the worker from such a string — a custom
provider, or per-user credentials carried on deps — use the
ResolveModelId capability.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler. Model events are handled live inside model-request activities, and tool events are handled in per-event activities.
If set, the run’s events are published to this
Workflow Stream
topic on the workflow running the agent, so a consumer outside the workflow can
observe them in real time with
stream_agent_events()
— no separate message queue needed. The workflow has to host an
AgentEventStream. Pass a
WorkflowStreamTopic rather
than a bare name to filter which events are published or to tune the flush interval.
Orthogonal to event_stream_handler: setting the topic enables streaming on its own,
and when both are set the handler still sees every event.
Unique agent name used in the Temporal activity names. Defaults to the agent’s
name when the capability is bound.
The type of the agent’s dependencies, needed for Temporal
serialization of activity parameters. Defaults to the agent’s own
deps_type, discovered when the capability binds via for_agent().
activity_config : ActivityConfig | None Default: None
Base Temporal activity config for all activities.
Defaults to a 60-second start_to_close_timeout.
model_activity_config : ActivityConfig | None Default: None
Activity config merged on top of the base for model request activities.
event_stream_handler_activity_config : ActivityConfig | None Default: None
Activity config merged on top of the base for event stream handler activities.
Per-toolset activity configs keyed by toolset ID, merged on top of the base config.
run_context_type : type[TemporalRunContext[AgentDepsT]] Default: TemporalRunContext[AgentDepsT]
The TemporalRunContext subclass for run context
serialization/deserialization.
continue_as_new : ContinueAsNewHandler[AgentDepsT] | None Default: None
Sync or async function called just before each model request
when running inside a workflow and workflow.info().is_continue_as_new_suggested()
is true. It receives the run’s RunContext and calls workflow.continue_as_new()
with the arguments the workflow needs to resume, or returns without calling it to
defer to the next model request. None disables continuation.
non_retryable_model_errors : Sequence[type[ModelAPIError]] Default: _DEFAULT_NON_RETRYABLE_MODEL_ERRORS
Model error classes that fail a model activity without Temporal
retrying it, whatever its retry policy says. An error matches when it’s an instance of a listed
class, so a category also covers its subclasses. The workflow still receives the error as its
own class. Defaults to the errors another attempt can’t fix:
ModelRequestRejectedError (which covers
ModelContextWindowExceededError,
ModelAuthenticationError,
ModelNotFoundError and
ModelSchemaTooComplexError),
ModelQuotaExceededError and
ModelRequestTimeout. A list you pass replaces
the default, and () lets the retry policy retry every model error. When the agent is built
with RetryOnModelErrors, every model error is
non-retryable, so that capability is the one that retries them, and the retry policy still
covers worker crashes and activity timeouts. A non_retryable_model_errors other than the default
is then ignored, with a UserWarning. A RetryOnModelErrors that only a
DynamicCapability returns for the run raises a UserError inside a workflow instead.
@async
def durable_sleep(seconds: float) -> None
Wait with a durable Temporal timer, which holds no worker slot and survives replays.
@async
def wrap_run(
ctx: RunContext[AgentDepsT],
*,
handler: WrapRunHandler,
) -> AgentRunResult[Any]
Disable threads inside Temporal workflows, keep replayed work out of telemetry, and wait for external events durably.
@async
def wrap_run_event_stream(
ctx: RunContext[AgentDepsT],
*,
stream: AsyncIterable[AgentStreamEvent],
) -> AsyncIterable[AgentStreamEvent]
Publish the run’s workflow-side events to the topic.
AsyncIterable[AgentStreamEvent]
def stream_agent_events(
client: Client,
handle: WorkflowHandle[Any, Any],
*,
output_type: type[OutputDataT] = cast('type[Any]', Any),
topic: str | WorkflowStreamTopic | None = None,
from_offset: int = 0,
poll_cooldown: timedelta = timedelta(milliseconds=100),
) -> DurableAgentRunEvents[OutputDataT]
Subscribe to the events a durable agent run publishes to its event_stream_topic.
This is a durable run_stream_events()
across the workflow boundary: the events arrive typed and in order, ending with the
AgentRunResultEvent that carries the run’s result.
They can be handed straight to a UIAdapter to drive a frontend.
DurableAgentRunEvents[OutputDataT]
A Temporal Client configured with
PydanticAIPlugin, so events
decode back into typed Pydantic AI events.
The handle for the workflow running the agent.
output_type : type[OutputDataT] Default: cast('type[Any]', Any)
The agent’s output type, so the terminal event’s result is decoded into it.
The topic to subscribe to. Defaults to this capability’s event_stream_topic.
from_offset : int Default: 0
The stream offset to start from, inclusive; pass offset + 1 to resume.
How long to wait between polls when no new events are ready. Must be greater than zero.
@async
def on_run_error(
ctx: RunContext[AgentDepsT],
*,
error: BaseException,
) -> AgentRunResult[Any]
Explain a serialization failure raised while scheduling an activity.
This is the run’s error-transformation hook: an exception raised from wrap_run
would only be attached as the original error’s __context__, never propagated.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Let continue_as_new continue the workflow as new when Temporal suggests it.
Bases: SimplePlugin
Temporal client and worker plugin for Pydantic AI.
Bases: SimplePlugin
Temporal worker plugin for a specific Pydantic AI agent.
Accepts either a regular Agent carrying a
TemporalDurability
capability (whose chain is walked to find the bound capability), or the
deprecated TemporalAgent
wrapper, and registers the agent’s activities on the worker, along with the child
workflows of any tools configured to run as one.
The agent whose activities and child workflows to register.
register_workflows : bool Default: True
Whether to register the agent’s child workflows. Pass False on a
worker that only runs activities to register only the agent’s activities; the worker
that runs your workflows must then register the child workflows.
Bases: Generic[OutputDataT], AsyncIterator['NativeEvent']
The event iterator returned by TemporalDurability.stream_agent_events().
A durable run_stream_events(): it yields the
run’s AgentStreamEvents in order, ending with the
trailing AgentRunResultEvent that carries the result —
except that these events crossed a workflow boundary, so the run itself may be executing in
another process entirely.
One iterator covers one agent run. A workflow that runs the agent repeatedly publishes a terminal
event per run, so a consumer that wants the next run reconnects with from_offset=offset + 1.
The stream offset of the last event yielded, or -1 before the first.
Workflow Streams are offset-addressed, so a consumer that checkpoints this can reconnect with
from_offset=offset + 1 and pick up exactly where it left off — which is more than ordinary
in-process streaming can offer. Offsets run over the whole stream rather than per topic, so
they skip whatever the workflow published to its other topics.
Type: int
The run’s result, once the terminal event has been yielded.
Type: AgentRunResult[OutputDataT] | None
@async
def aclose() -> None
Stop the underlying subscription.
Reaching the terminal event does this for you. Call it (or use the iterator as an async context manager) when you stop early, so the long-poll against Temporal doesn’t stay open until the generator is collected.
@async
def resolve_external_event(client: Client, token: str, payload: object) -> None
End a wait for an external event in a Temporal workflow with payload.
The token is the one a wait_for_external_event
in a workflow running an agent with
TemporalDurability handed to its ask, such
as the handler of HandleDeferredToolCalls. It
names the workflow, which this signals with the payload. Call it from anywhere with a client for the workflow’s namespace, such as the
endpoint your approval UI posts to.
payload is converted to its JSON form, as it would be in process. Once the wait ended, because it
was already resolved or timed out, resolving it again has no effect.
A Temporal client for the namespace the workflow runs in.
token : str
The resume token ask received.
payload : object
The answer, such as the JSON form of DeferredToolResults for HandleDeferredToolCalls.
UserError— The token was not handed out by a Temporal workflow, orpayloadcan’t be converted to JSON.temporalio.service.RPCError— The workflow is not running, for example because it already completed.
@async
def fail_external_event(client: Client, token: str, reason: str) -> None
End a wait for an external event in a Temporal workflow without a payload.
The wait raises ExternalEventError with reason,
as it does when it times out. HandleDeferredToolCalls
then denies the pending calls with reason in the message to the model.
A Temporal client for the namespace the workflow runs in.
token : str
The resume token ask received.
reason : str
Why no answer is coming, which the wait’s ExternalEventError carries.
UserError— The token was not handed out by a Temporal workflow.temporalio.service.RPCError— The workflow is not running, for example because it already completed.
def workflow_stream_event_handler(
topic: str | WorkflowStreamTopic,
*,
handler: EventStreamHandler[AgentDepsT] | None = None,
) -> EventStreamHandler[AgentDepsT]
Build an EventStreamHandler that publishes the events it sees to a Workflow Stream topic.
This is the building block TemporalDurability(event_stream_topic=...) uses for the live model
stream, exposed so it can be composed or wrapped. Reach for the capability argument first: it
additionally publishes the run’s workflow-side events from workflow code — no activity, no signal,
exactly once — and the terminal
AgentRunResultEvent that ends a subscription. Installed
on its own as an event_stream_handler, this handler publishes only what it is handed, and every
event it publishes goes out from an activity, so an activity retry republishes it.
The handler publishes to the workflow that scheduled the activity it runs in. Outside an activity
— an agent run outside a workflow, or a workflow-side replay through
ProcessEventStream — there is nothing to publish
to, so the events pass through untouched. Events are serialized with the integration’s Pydantic
payload converter, so subscribers decode them back into typed events.
EventStreamHandler[AgentDepsT]
topic : str | WorkflowStreamTopic
The topic to publish to.
handler : EventStreamHandler[AgentDepsT] | None Default: None
An optional handler to run alongside publishing. Each event is published and then passed on to this handler, which sees exactly the stream it would have seen on its own.
def stream_agent_events(
client: Client,
handle: WorkflowHandle[Any, Any],
topic: str | WorkflowStreamTopic,
*,
output_type: type[OutputDataT] = cast('type[Any]', Any),
from_offset: int = 0,
poll_cooldown: timedelta = _DEFAULT_POLL_COOLDOWN,
) -> DurableAgentRunEvents[OutputDataT]
Subscribe to the events a durable agent run publishes to a Workflow Stream topic.
Prefer TemporalDurability.stream_agent_events(),
which fills in the topic and output type from the capability. Use this function from a consumer
that holds neither, only a workflow handle.
The terminal event carries the result every capability has finished shaping, but the run lifecycle finalizes after that, and nothing in the capability system wraps that step. A run cancelled there publishes a terminal event and then fails, so treat the workflow’s own result as the authoritative outcome.
DurableAgentRunEvents[OutputDataT]
A Temporal Client configured with PydanticAIPlugin,
so events decode back into typed Pydantic AI events.
The handle for the workflow running the agent.
topic : str | WorkflowStreamTopic
The topic the agent publishes to.
output_type : type[OutputDataT] Default: cast('type[Any]', Any)
The agent’s output type, so the terminal event’s result is decoded into it.
from_offset : int Default: 0
The stream offset to start from, inclusive; pass offset + 1 to resume.
How long to wait between polls when no new events are ready. Must be greater than zero.
Sync or async function called when Temporal suggests continuing the workflow as new.
It receives the run’s RunContext, including the current
messages, usage, and usage_limits, and calls temporalio.workflow.continue_as_new() with the
arguments the workflow’s run method needs to resume. Returning without calling it defers the
continuation to the next model request.
Type: TypeAlias Default: Callable[[RunContext[AgentDepsT]], Awaitable[None] | None]
Bases: JournalOperationNamer
Generate DBOS step names that are persisted compatibility data.
These names must essentially never change. Changing them can strand in-flight workflows and recorded runs.
Bases: TypedDict
Configuration for a step in the DBOS workflow.
Bases: TypedDict
Configuration for a tool call run as a DBOS child workflow.
Passed to DBOS’s SetWorkflowTimeout when the child workflow starts.
When it expires, DBOS cancels the child workflow and the tool call raises DBOSAwaitedWorkflowCancelledError.
Type: float
Bases: WrapperModel
A wrapper for Model that integrates with DBOS, turning request and request_stream to DBOS steps.
Bases: BaseDurabilityCapability[AgentDepsT]
Capability that makes an agent durable by routing I/O through DBOS steps.
The capability routes model requests, MCP I/O, and optionally event-stream
handling through DBOS steps when the agent runs inside a DBOS workflow. Call
agent.run() inside your own @DBOS.workflow to make that run durable;
outside a workflow the capability is transparent and the run is a normal,
non-durable agent run.
The capability discovers the agent’s model, name, and toolsets
automatically via for_agent().
def __init__(
*,
models: Mapping[str, Model] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
name: str | None = None,
model_step_config: StepConfig | None = None,
event_stream_handler_step_config: StepConfig | None = None,
mcp_step_config: StepConfig | None = None,
parallel_execution_mode: DBOSParallelExecutionMode = 'parallel_ordered_events',
register_legacy_workflows: bool = False,
)
Create a DBOSDurability capability.
The agent’s model, name, and toolsets are discovered automatically.
Optional additional models keyed by ID for runtime model
switching. The agent’s primary model is always registered as
'default'. A Model instance can’t be serialized across the
step boundary, so a run-time model (via agent.run(model=...)
/ agent.override(model=...), or swapped in by an outer capability)
has to be registered here and referenced by key (or passed as the
registered instance); an unregistered instance is rejected, because
rebuilding it from its model_id would build a different model.
Model-name strings never need registering: they cross as the string
the caller wrote and are built inside the step by the agent’s
resolve_model_id capability chain, then infer_model. To build a
specific instance inside the step from such a string — a custom
provider, or per-user credentials carried on deps — use the
ResolveModelId capability.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler. Model events are handled
live inside model-request steps, and each tool event is handled in its own
event-handler step. Tool emissions reserve that step’s position during ctx.emit();
the handler still runs at stream position, without blocking the emitter.
Unique agent name used in the DBOS step names. Defaults to the agent’s
name when the capability is bound.
model_step_config : StepConfig | None Default: None
DBOS step config for model request steps.
event_stream_handler_step_config : StepConfig | None Default: None
DBOS step config for event stream handler steps.
mcp_step_config : StepConfig | None Default: None
DBOS step config for MCP server steps.
Tool-call execution mode applied for the duration
of every run. Defaults to 'parallel_ordered_events' so events
replay deterministically. Set to 'sequential' for strict ordering.
A run with a workspace runs its tool calls sequentially, except that tools
that run in a child workflow run in parallel.
register_legacy_workflows : bool Default: False
Register the workflow names used by the deprecated
DBOSAgent so in-flight wrapper-era workflows can recover during migration.
@async
def durable_sleep(seconds: float) -> None
Wait with DBOS.sleep_async, a recorded step, so recovery skips a completed wait.
@async
def prepare_tools(
ctx: RunContext[AgentDepsT],
tool_defs: list[ToolDefinition],
) -> list[ToolDefinition]
With a workspace and child-workflow tools, run each tool outside a child workflow alone.
DBOS numbers steps as they start, so steps from concurrent tools could replay into the wrong call.
@async
def wrap_run(
ctx: RunContext[AgentDepsT],
*,
handler: WrapRunHandler,
) -> AgentRunResult[Any]
Apply the configured parallel-execution mode to every run, inside a workflow or not.
Bases: WrapperAgent[AgentDepsT, OutputDataT], DBOSConfiguredInstance
def __init__(
wrapped: AbstractAgent[AgentDepsT, OutputDataT],
*,
name: str | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
mcp_step_config: StepConfig | None = None,
model_step_config: StepConfig | None = None,
parallel_execution_mode: DBOSParallelExecutionMode = 'parallel_ordered_events',
)
Wrap an agent to enable it with DBOS durable workflows, by automatically offloading model requests, tool calls, and MCP server communication to DBOS steps.
After wrapping, the original agent can still be used as normal outside of the DBOS workflow.
The agent to wrap.
Optional unique agent name to use as the DBOS configured instance name. If not provided, the agent’s name will be used.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use instead of the one set on the wrapped agent.
mcp_step_config : StepConfig | None Default: None
The base DBOS step config to use for MCP server steps. If no config is provided, use the default settings of DBOS.
model_step_config : StepConfig | None Default: None
The DBOS step config to use for model request steps. If no config is provided, use the default settings of DBOS.
The mode for executing tool calls:
- ‘parallel_ordered_events’ (default): Run tool calls in parallel, but events are emitted in order, after all calls complete.
- ‘sequential’: Run tool calls one at a time in order.
@async
def run(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[OutputDataT]
def run(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[RunOutputDataT]
Run the agent with a user prompt in async mode.
This method builds an internal agent graph (using system prompts, tools and result schemas) and then runs the graph to completion. The result of the run is returned.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
agent_run = await agent.run('What is the capital of France?')
print(agent_run.output)
#> The capital of France is Paris.
AgentRunResult[Any] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for DBOS durable execution; passing one raises UserError.
Unsupported by the deprecated DBOSAgent; passing one raises UserError. Use the
DBOSDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def compact_history(
message_history: Sequence[_messages.ModelMessage],
*,
focus: str | None = None,
reason: _messages.CompactionReason = 'manual',
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
spec: dict[str, Any] | AgentSpec | None = None,
) -> CompactionRunResult
Compact a message history without continuing the conversation, in a DBOS workflow of its own.
See AbstractAgent.compact_history. The workflow makes
the run compaction-only itself, so a recovered workflow compacts again rather than continuing the
conversation. As for run(), passing cancellation_token,
timeout or a model that isn’t a DBOS model raises UserError.
def run_sync(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[OutputDataT]
def run_sync(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[RunOutputDataT]
Synchronously run the agent with a user prompt.
This is a convenience method that wraps self.run with loop.run_until_complete(...).
You therefore can’t use this method inside async code or if there’s an active event loop.
This method cannot be used inside a synchronous tool, output function, or other function called during an agent run.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
result_sync = agent.run_sync('What is the capital of Italy?')
print(result_sync.output)
#> The capital of Italy is Rome.
AgentRunResult[Any] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for DBOS durable execution; passing one raises UserError.
Unsupported by the deprecated DBOSAgent; passing one raises UserError. Use the
DBOSDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def run_stream(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, OutputDataT]]
def run_stream(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
deps: AgentDepsT = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, RunOutputDataT]]
Run the agent with a user prompt in async mode, returning a streamed response.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
async with agent.run_stream('What is the capital of the UK?') as response:
print(await response.get_output())
#> The capital of the UK is London.
AsyncGenerator[StreamedRunResult[AgentDepsT, Any]] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for DBOS durable execution; passing one raises UserError.
Unsupported by the deprecated DBOSAgent; passing one raises UserError. Use the
DBOSDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run. It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
def run_stream_events(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRunEvents[OutputDataT]]
def run_stream_events(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRunEvents[RunOutputDataT]]
Run the agent with a user prompt in async mode and stream events from the run.
This is a convenience method that wraps self.run and
uses the event_stream_handler kwarg to get a stream of events from the run.
Example:
from pydantic_ai import Agent, AgentRunResultEvent, AgentStreamEvent
agent = Agent('openai:gpt-5.2')
async def main():
collected: list[AgentStreamEvent | AgentRunResultEvent] = []
async with agent.run_stream_events('What is the capital of France?') as events:
async for event in events:
collected.append(event)
print(collected)
'''
[
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
FinalResultEvent(tool_name=None, tool_call_id=None),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
PartEndEvent(
index=0, part=TextPart(content='The capital of France is Paris. ')
),
AgentRunResultEvent(
result=AgentRunResult(output='The capital of France is Paris. ')
),
]
'''
Arguments are the same as for self.run,
except that event_stream_handler is now allowed.
AbstractAsyncContextManager[AgentRunEvents[Any]] — An async context manager that yields an AgentRunEvents
AbstractAsyncContextManager[AgentRunEvents[Any]] — handle over AgentStreamEvents ending with a final AgentRunResultEvent carrying the run result.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for DBOS durable execution; passing one raises UserError.
Unsupported by the deprecated DBOSAgent; passing one raises UserError. Use the
DBOSDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def iter(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, OutputDataT]]
def iter(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, RunOutputDataT]]
A contextmanager which can be used to iterate over the agent graph’s nodes as they are executed.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
AgentRun object. The AgentRun can be used to async-iterate over the nodes of the graph as they are
executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
stream of events coming from the execution of tools.
The AgentRun also provides methods to access the full message history, new messages, and usage statistics,
and the final result of the run once it has completed.
For more details, see the documentation of AgentRun.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
nodes = []
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
UserPromptNode(
user_prompt='What is the capital of France?',
instructions_functions=[],
system_prompts=(),
system_prompt_functions=[],
system_prompt_dynamic_functions={},
),
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
conversation_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(
cost=Decimal('0.000196'), input_tokens=56, output_tokens=7
),
model_name='gpt-5.2',
model_id='openai:gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
conversation_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
assert agent_run.result is not None
print(agent_run.result.output)
#> The capital of France is Paris.
AsyncGenerator[AgentRun[AgentDepsT, Any]] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for DBOS durable execution; passing one raises UserError.
Unsupported by the deprecated DBOSAgent; passing one raises UserError. Use the
DBOSDurability capability, which keeps the run’s deadline when the workflow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
def override(
*,
name: str | _utils.Unset = _utils.UNSET,
deps: AgentDepsT | _utils.Unset = _utils.UNSET,
model: models.Model | models.KnownModelName | str | _utils.Unset = _utils.UNSET,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | _utils.Unset = _utils.UNSET,
tools: Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | _utils.Unset = _utils.UNSET,
native_tools: Sequence[AgentNativeTool[AgentDepsT]] | _utils.Unset = _utils.UNSET,
instructions: _instructions.AgentInstructions[AgentDepsT] | _utils.Unset = _utils.UNSET,
capabilities: Sequence[AgentCapability[AgentDepsT]] | _utils.Unset = _utils.UNSET,
metadata: AgentMetadata[AgentDepsT] | _utils.Unset = _utils.UNSET,
model_settings: AgentModelSettings[AgentDepsT] | _utils.Unset = _utils.UNSET,
retries: int | AgentRetries | _utils.Unset = _utils.UNSET,
spec: dict[str, Any] | AgentSpec | None = None,
workspace: WorkspaceBackend | Workspace | WorkspaceRef | Literal['new'] | _utils.Unset = _utils.UNSET,
) -> Generator[None]
Context manager to temporarily override agent configuration.
This is particularly useful when testing. You can find an example of this here.
name : str | _utils.Unset Default: _utils.UNSET
The name to use instead of the name passed to the agent constructor and agent run.
The dependencies to use instead of the dependencies passed to the agent run.
model : models.Model | models.KnownModelName | str | _utils.Unset Default: _utils.UNSET
The model to use instead of the model passed to the agent run.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The toolsets to use instead of the toolsets passed to the agent constructor and agent run.
tools : Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, …]] | _utils.Unset Default: _utils.UNSET
The tools to use instead of the tools registered with the agent.
native_tools : Sequence[AgentNativeTool[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The native tools to use instead of the agent’s configured native tools.
instructions : _instructions.AgentInstructions[AgentDepsT] | _utils.Unset Default: _utils.UNSET
The instructions to use instead of the instructions registered with the agent.
capabilities : Sequence[AgentCapability[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The capabilities to use instead of the agent’s configured capabilities. When set,
these replace (not merge with) the agent’s existing capabilities. To add to the existing
set, include them explicitly:
agent.override(capabilities=[*agent.root_capability.capabilities, extra]).
On an agent with a durability capability, build the list this way: a list without the bound
durability capability raises a UserError, and inside a durable workflow or flow, the
capabilities the list adds follow the rules for capabilities passed to a run.
The metadata to use instead of the metadata passed to the agent constructor. When set, any
per-run metadata argument is ignored.
model_settings : AgentModelSettings[AgentDepsT] | _utils.Unset Default: _utils.UNSET
The model settings to use instead of the model settings passed to the agent constructor.
When set, any per-run model_settings argument is ignored.
retries : int | AgentRetries | _utils.Unset Default: _utils.UNSET
The retry budgets to use instead of the agent-level configuration. Pass an int to
override both the tool-retry and output budgets, or an AgentRetries
dict to override just one (e.g. retries={'tools': 3}). When set, any per-run retries argument is ignored.
Optional agent spec to apply as overrides.
workspace : WorkspaceBackend | Workspace | WorkspaceRef | Literal[‘new’] | _utils.Unset Default: _utils.UNSET
Workspace for every run in this context, in place of a per-run workspace= argument.
The mode for executing tool calls in DBOS durable workflows. This is a subset of the ParallelExecutionMode because ‘parallel’ cannot guarantee deterministic ordering.
Default: Literal['sequential', 'parallel_ordered_events']
Bases: TypedDict
Configuration for a task in Prefect.
These options are passed to the @task decorator.
Maximum number of retries for the task.
Type: int
Delay between retries in seconds. Can be a single value or a list for custom backoff.
Predicate deciding whether a failed task should be retried.
Type: RetryConditionCallable
Maximum time in seconds for the task to complete.
Type: float
Prefect cache policy for the task.
Type: CachePolicy
Whether to persist the task result.
Type: bool
Prefect result storage for the task. Should be a storage block or a block slug like s3-bucket/my-storage.
Type: ResultStorage
Whether to log print statements from the task.
Type: bool
Bases: DurableOperationNamer
Generate Prefect task names that are persisted compatibility data.
These names must essentially never change. Changing them can strand in-flight flows and recorded runs.
Bases: WrapperModel
A wrapper for Model that integrates with Prefect, turning request and request_stream into Prefect tasks.
@async
def request(
messages: list[ModelMessage],
model_settings: ModelSettings | None,
model_request_parameters: ModelRequestParameters,
) -> ModelResponse
Make a model request, wrapped as a Prefect task when in a flow.
@async
def cancel_suspended_response(response: ModelResponse) -> None
Cancel a server-side suspended/background response, wrapped as a Prefect task.
The teardown performs a raw HTTP call to the provider, so it runs as a task (durable, retried) rather than inline in the flow.
@async
def request_stream(
messages: list[ModelMessage],
model_settings: ModelSettings | None,
model_request_parameters: ModelRequestParameters,
run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]
Make a streaming model request.
When inside a Prefect flow, the stream is consumed within a task and a non-streaming response is returned. When not in a flow, behaves normally.
AsyncGenerator[StreamedResponse]
Bases: BaseDurabilityCapability[AgentDepsT]
Capability that makes an agent durable by routing I/O through Prefect tasks.
Built on the declarative base: the base owns toolset/model/event assembly, and this capability contributes the Prefect operation backend, transparency gate, and task configuration.
def __init__(
*,
models: Mapping[str, Model] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
name: str | None = None,
event_stream_handler_task_config: TaskConfig | None = None,
model_task_config: TaskConfig | None = None,
mcp_task_config: TaskConfig | None = None,
tool_task_config: TaskConfig | None = None,
)
Create a PrefectDurability capability.
The agent’s model, name, and toolsets are discovered automatically.
Optional additional models keyed by ID for runtime model
switching. The agent’s primary model is always registered as
'default'. A Model instance can’t be serialized across the
task boundary, so a run-time model (via agent.run(model=...)
/ agent.override(model=...), or swapped in by an outer capability)
has to be registered here and referenced by key (or passed as the
registered instance); an unregistered instance is rejected, because
rebuilding it from its model_id would build a different model.
Model-name strings never need registering: they cross as the string
the caller wrote and are built inside the task by the agent’s
resolve_model_id capability chain, then infer_model. To build a
specific instance inside the task from such a string — a custom
provider, or per-user credentials carried on deps — use the
ResolveModelId capability.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler. Model events are handled live inside model-request tasks, and tool events are handled in per-event tasks.
Unique agent name used in the Prefect task names. Defaults to the agent’s
name when the capability is bound.
event_stream_handler_task_config : TaskConfig | None Default: None
Prefect task config for event stream handler tasks.
model_task_config : TaskConfig | None Default: None
Prefect task config for model request tasks.
mcp_task_config : TaskConfig | None Default: None
Prefect task config for MCP server tasks.
tool_task_config : TaskConfig | None Default: None
Default Prefect task config for tool call tasks. Per-tool
overrides are configured via tool metadata, e.g.
@my_toolset.tool(metadata={'prefect': TaskConfig(...)}) (or False to skip
task wrapping), or via the
SetToolMetadata capability.
def get_default_run_id() -> str | None
Return an ID using the legacy flow-counter policy, or None outside a flow.
This synchronous hook is retained for existing overrides. An override delegating to
super() keeps the counter policy and its arrival-order dependence.
Standard agent runs use cached random IDs instead; read the actual ID from
RunContext.run_id or the run result’s run_id.
Bases: DurableFunctionToolset[AgentDepsT]
A wrapper for FunctionToolset that runs tool calls as Prefect tasks inside flows.
Bases: DurableMCPToolset[AgentDepsT]
A wrapper for MCPToolset that runs tool calls as Prefect tasks inside flows.
Bases: WrapperAgent[AgentDepsT, OutputDataT]
def __init__(
wrapped: AbstractAgent[AgentDepsT, OutputDataT],
*,
name: str | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
mcp_task_config: TaskConfig | None = None,
model_task_config: TaskConfig | None = None,
tool_task_config: TaskConfig | None = None,
tool_task_config_by_name: dict[str, TaskConfig | None] | None = None,
event_stream_handler_task_config: TaskConfig | None = None,
prefectify_toolset_func: Callable[[AbstractToolset[AgentDepsT], TaskConfig, TaskConfig, dict[str, TaskConfig | None]], AbstractToolset[AgentDepsT]] = prefectify_toolset,
)
Wrap an agent to enable it with Prefect durable flows, by automatically offloading model requests, tool calls, and MCP server communication to Prefect tasks.
After wrapping, the original agent can still be used as normal outside of the Prefect flow.
The agent to wrap.
Optional unique agent name to use as the Prefect flow name prefix. If not provided, the agent’s name will be used.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use instead of the one set on the wrapped agent.
mcp_task_config : TaskConfig | None Default: None
The base Prefect task config to use for MCP server tasks. If no config is provided, use the default settings of Prefect.
model_task_config : TaskConfig | None Default: None
The Prefect task config to use for model request tasks. If no config is provided, use the default settings of Prefect.
tool_task_config : TaskConfig | None Default: None
The default Prefect task config to use for tool calls. If no config is provided, use the default settings of Prefect.
Per-tool task configuration. Keys are tool names, values are TaskConfig or None (None disables task wrapping for that tool).
event_stream_handler_task_config : TaskConfig | None Default: None
The Prefect task config to use for the event stream handler task. If no config is provided, use the default settings of Prefect.
prefectify_toolset_func : Callable[[AbstractToolset[AgentDepsT], TaskConfig, TaskConfig, dict[str, TaskConfig | None]], AbstractToolset[AgentDepsT]] Default: prefectify_toolset
Optional function to use to prepare toolsets for Prefect by wrapping them in a PrefectWrapperToolset that moves methods that require IO to Prefect tasks.
If not provided, only FunctionToolset and MCPToolset will be prepared for Prefect.
The function takes the toolset, the task config, the tool-specific task config, and the tool-specific task config by name.
@async
def run(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[OutputDataT]
def run(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[RunOutputDataT]
Run the agent with a user prompt in async mode.
This method builds an internal agent graph (using system prompts, tools and result schemas) and then runs the graph to completion. The result of the run is returned.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
agent_run = await agent.run('What is the capital of France?')
print(agent_run.output)
#> The capital of France is Paris.
AgentRunResult[Any] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for Prefect durable execution; passing one raises UserError.
Unsupported by the deprecated PrefectAgent; passing one raises UserError. Use the
PrefectDurability capability, which keeps the run’s deadline when the flow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def compact_history(
message_history: Sequence[_messages.ModelMessage],
*,
focus: str | None = None,
reason: _messages.CompactionReason = 'manual',
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
spec: dict[str, Any] | AgentSpec | None = None,
) -> CompactionRunResult
Compact a message history without continuing the conversation, as a run of this agent’s Prefect flow.
See AbstractAgent.compact_history. Run through this
agent’s own run(), not forwarded to the wrapped agent as WrapperAgent does, so it runs in the wrapper’s run flow.
def run_sync(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[OutputDataT]
def run_sync(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AgentRunResult[RunOutputDataT]
Synchronously run the agent with a user prompt.
This is a convenience method that wraps self.run with loop.run_until_complete(...).
You therefore can’t use this method inside async code or if there’s an active event loop.
This method cannot be used inside a synchronous tool, output function, or other function called during an agent run.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
result_sync = agent.run_sync('What is the capital of Italy?')
print(result_sync.output)
#> The capital of Italy is Rome.
AgentRunResult[Any] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for Prefect durable execution; passing one raises UserError.
Unsupported by the deprecated PrefectAgent; passing one raises UserError. Use the
PrefectDurability capability, which keeps the run’s deadline when the flow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def run_stream(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, OutputDataT]]
def run_stream(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentDepsT, RunOutputDataT]]
Run the agent with a user prompt in async mode, returning a streamed response.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
async with agent.run_stream('What is the capital of the UK?') as response:
print(await response.get_output())
#> The capital of the UK is London.
AsyncGenerator[StreamedRunResult[AgentDepsT, Any]] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for Prefect durable execution; passing one raises UserError.
Unsupported by the deprecated PrefectAgent; passing one raises UserError. Use the
PrefectDurability capability, which keeps the run’s deadline when the flow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler to use for this run. It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
def run_stream_events(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRunEvents[OutputDataT]]
def run_stream_events(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRunEvents[RunOutputDataT]]
Run the agent with a user prompt in async mode and stream events from the run.
This is a convenience method that wraps self.run and
uses the event_stream_handler kwarg to get a stream of events from the run.
Example:
from pydantic_ai import Agent, AgentRunResultEvent, AgentStreamEvent
agent = Agent('openai:gpt-5.2')
async def main():
collected: list[AgentStreamEvent | AgentRunResultEvent] = []
async with agent.run_stream_events('What is the capital of France?') as events:
async for event in events:
collected.append(event)
print(collected)
'''
[
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
FinalResultEvent(tool_name=None, tool_call_id=None),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
PartEndEvent(
index=0, part=TextPart(content='The capital of France is Paris. ')
),
AgentRunResultEvent(
result=AgentRunResult(output='The capital of France is Paris. ')
),
]
'''
Arguments are the same as for self.run,
except that event_stream_handler is now allowed.
AbstractAsyncContextManager[AgentRunEvents[Any]] — An async context manager that yields an AgentRunEvents
AbstractAsyncContextManager[AgentRunEvents[Any]] — handle over AgentStreamEvents ending with a final AgentRunResultEvent carrying the run result.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
Optional dependencies to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for Prefect durable execution; passing one raises UserError.
Unsupported by the deprecated PrefectAgent; passing one raises UserError. Use the
PrefectDurability capability, which keeps the run’s deadline when the flow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
@async
def iter(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: None = None,
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, OutputDataT]]
def iter(
user_prompt: str | Sequence[_messages.UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
conversation: Conversation | None = None,
message_history: Sequence[_messages.ModelMessage] | None = None,
deferred_tool_results: DeferredToolResults | None = None,
conversation_id: str | None = None,
run_id: str | None = None,
model: models.Model | models.KnownModelName | str | None = None,
instructions: _instructions.AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: AgentModelSettings[AgentDepsT] | None = None,
usage_limits: _usage.UsageLimits | None = None,
cancellation_token: CancellationToken | None = None,
timeout: float | None = None,
usage: _usage.RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
retries: int | AgentRetries | None = None,
infer_name: bool = True,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | None = None,
capabilities: Sequence[AgentCapability[AgentDepsT]] | None = None,
workspace: WorkspaceBackend | WorkspaceRef | Literal['new'] | None = None,
compact: bool | CompactionOptions = False,
spec: dict[str, Any] | AgentSpec | None = None,
) -> AbstractAsyncContextManager[AgentRun[AgentDepsT, RunOutputDataT]]
A contextmanager which can be used to iterate over the agent graph’s nodes as they are executed.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
AgentRun object. The AgentRun can be used to async-iterate over the nodes of the graph as they are
executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
stream of events coming from the execution of tools.
The AgentRun also provides methods to access the full message history, new messages, and usage statistics,
and the final result of the run once it has completed.
For more details, see the documentation of AgentRun.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
nodes = []
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
UserPromptNode(
user_prompt='What is the capital of France?',
instructions_functions=[],
system_prompts=(),
system_prompt_functions=[],
system_prompt_dynamic_functions={},
),
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
conversation_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(
cost=Decimal('0.000196'), input_tokens=56, output_tokens=7
),
model_name='gpt-5.2',
model_id='openai:gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
conversation_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
assert agent_run.result is not None
print(agent_run.result.output)
#> The capital of France is Paris.
AsyncGenerator[AgentRun[AgentDepsT, Any]] — The result of the run.
User input to start/continue the conversation.
output_type : OutputSpec[RunOutputDataT] | None Default: None
Custom output type to use for this run, output_type may only be used if the agent has no
output validators since output validators would expect an argument that matches the agent’s output type.
conversation : Conversation | None Default: None
The conversation to continue, in place of passing its message_history, usage and
conversation_id separately. Passing both raises UserError.
History of the conversation so far.
deferred_tool_results : DeferredToolResults | None Default: None
Optional results for deferred tool calls in the message history.
ID of the conversation this run belongs to. Pass 'new' to start a fresh conversation, ignoring any conversation_id already on message_history. If omitted, falls back to the most recent conversation_id on message_history or a freshly generated UUID7, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the run_id so it stays the same when the engine re-executes the run.
Optional ID for this agent run. Unlike conversation_id, never inherited from message_history. Passing an empty string, or a value that already appears on message_history, raises UserError because both break new_messages(); use conversation_id to correlate across turns or deferred-tool resume. If omitted, a fresh UUID7 is generated, except that an agent with a TemporalDurability, DBOSDurability or PrefectDurability capability, run inside a workflow or flow, gets one derived from the workflow or flow run so it stays the same when the engine re-executes the run.
model : models.Model | models.KnownModelName | str | None Default: None
Optional model to use for this run, required if model was not set when creating the agent.
Optional dependencies to use for this run.
instructions : _instructions.AgentInstructions[AgentDepsT] Default: None
Optional additional instructions to use for this run.
model_settings : AgentModelSettings[AgentDepsT] | None Default: None
Optional settings to use for this model’s request.
usage_limits : _usage.UsageLimits | None Default: None
Optional limits on model request count or token usage.
cancellation_token : CancellationToken | None Default: None
Unsupported for Prefect durable execution; passing one raises UserError.
Unsupported by the deprecated PrefectAgent; passing one raises UserError. Use the
PrefectDurability capability, which keeps the run’s deadline when the flow is replayed or recovered.
usage : _usage.RunUsage | None Default: None
Optional usage to start with, useful for resuming a conversation or agents used in tools.
metadata : AgentMetadata[AgentDepsT] | None Default: None
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
RunContext; merged with the agent’s configured metadata.
retries : int | AgentRetries | None Default: None
Override the agent-level retry budgets for this run. Pass an int to override both the
tool-retry and output budgets, or an AgentRetries dict to override
just one (e.g. retries={'tools': 3}). See
Agent.__init__ for semantics of the two enforcement paths.
infer_name : bool Default: True
Whether to try to infer the agent name from the call frame if it’s not set.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | None Default: None
Optional additional toolsets for this run.
capabilities : Sequence[AgentCapability[AgentDepsT]] | None Default: None
Optional additional capabilities for this run, merged with the agent’s configured capabilities.
Optional workspace for this run: a backend or Workspace to use as is, a WorkspaceRef to continue in, or 'new' for a fresh one instead of the one in message_history.
compact : bool | CompactionOptions Default: False
Compact the message history before the run’s first model request: True, or a CompactionOptions dict with a reason and a focus. See requesting compaction.
Optional agent spec to apply for this run.
def override(
*,
name: str | _utils.Unset = _utils.UNSET,
deps: AgentDepsT | _utils.Unset = _utils.UNSET,
model: models.Model | models.KnownModelName | str | _utils.Unset = _utils.UNSET,
toolsets: Sequence[AbstractToolset[AgentDepsT]] | _utils.Unset = _utils.UNSET,
tools: Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | _utils.Unset = _utils.UNSET,
native_tools: Sequence[AgentNativeTool[AgentDepsT]] | _utils.Unset = _utils.UNSET,
instructions: _instructions.AgentInstructions[AgentDepsT] | _utils.Unset = _utils.UNSET,
capabilities: Sequence[AgentCapability[AgentDepsT]] | _utils.Unset = _utils.UNSET,
metadata: AgentMetadata[AgentDepsT] | _utils.Unset = _utils.UNSET,
model_settings: AgentModelSettings[AgentDepsT] | _utils.Unset = _utils.UNSET,
retries: int | AgentRetries | _utils.Unset = _utils.UNSET,
spec: dict[str, Any] | AgentSpec | None = None,
workspace: WorkspaceBackend | Workspace | WorkspaceRef | Literal['new'] | _utils.Unset = _utils.UNSET,
) -> Generator[None]
Context manager to temporarily override agent configuration.
This is particularly useful when testing. You can find an example of this here.
name : str | _utils.Unset Default: _utils.UNSET
The name to use instead of the name passed to the agent constructor and agent run.
The dependencies to use instead of the dependencies passed to the agent run.
model : models.Model | models.KnownModelName | str | _utils.Unset Default: _utils.UNSET
The model to use instead of the model passed to the agent run.
toolsets : Sequence[AbstractToolset[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The toolsets to use instead of the toolsets passed to the agent constructor and agent run.
tools : Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, …]] | _utils.Unset Default: _utils.UNSET
The tools to use instead of the tools registered with the agent.
native_tools : Sequence[AgentNativeTool[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The native tools to use instead of the agent’s configured native tools.
instructions : _instructions.AgentInstructions[AgentDepsT] | _utils.Unset Default: _utils.UNSET
The instructions to use instead of the instructions registered with the agent.
capabilities : Sequence[AgentCapability[AgentDepsT]] | _utils.Unset Default: _utils.UNSET
The capabilities to use instead of the agent’s configured capabilities. When set,
these replace (not merge with) the agent’s existing capabilities. To add to the existing
set, include them explicitly:
agent.override(capabilities=[*agent.root_capability.capabilities, extra]).
On an agent with a durability capability, build the list this way: a list without the bound
durability capability raises a UserError, and inside a durable workflow or flow, the
capabilities the list adds follow the rules for capabilities passed to a run.
The metadata to use instead of the metadata passed to the agent constructor. When set, any
per-run metadata argument is ignored.
model_settings : AgentModelSettings[AgentDepsT] | _utils.Unset Default: _utils.UNSET
The model settings to use instead of the model settings passed to the agent constructor.
When set, any per-run model_settings argument is ignored.
retries : int | AgentRetries | _utils.Unset Default: _utils.UNSET
The retry budgets to use instead of the agent-level configuration. Pass an int to
override both the tool-retry and output budgets, or an AgentRetries
dict to override just one (e.g. retries={'tools': 3}). When set, any per-run retries argument is ignored.
Optional agent spec to apply as overrides.
workspace : WorkspaceBackend | Workspace | WorkspaceRef | Literal[‘new’] | _utils.Unset Default: _utils.UNSET
Workspace for every run in this context, in place of a per-run workspace= argument.
Durable execution for Pydantic AI agents with Hatchet.
Attach HatchetDurability to an agent and run the
agent in a Hatchet durable task: its model requests, MCP communication and tool calls run as child tasks
whose results the durable task’s event log records.
Bases: DurableRunContext[AgentDepsT]
The RunContext used inside the Hatchet tasks a durable agent run spawns.
A task may run on another worker, so only the fields
DurableRunContext serializes cross into it, and reading
any other field raises a UserError explaining how to make it available. agent is re-attached from the
worker’s agent instance, and tracer is resolved from it.
To make another attribute available, create a HatchetRunContext subclass with a custom
serialize_run_context class method that returns a dictionary that includes the attribute, and pass it
as the run_context_type argument to HatchetDurability.
@classmethod
def serialize_run_context(cls, ctx: RunContext[Any]) -> dict[str, Any]
Serialize the run context so a replay of the durable task serializes it identically.
Sets cross as sorted lists, since a set’s order differs between processes, and synthetic capability keys
are replaced by stable_capability_ids.
Where and what a durable agent run publishes to Hatchet’s durable streams.
Pass this, or True for the defaults, as HatchetDurability’s event_stream.
The topic for a run, from the agent name and the workflow run ID of the durable task running it.
Defaults to pydantic-ai.<agent name>.<workflow run ID>, a topic per durable task and agent.
Type: Callable[[str, str], str] Default: _default_topic
The durable stream namespace the topics are in.
Type: str Default: ''
Optional predicate selecting which events to publish; by default every event is published.
The terminal AgentRunResultEvent is always published.
Type: Callable[[AgentStreamEvent], bool] | None Default: None
Bases: TypedDict
Options for the Hatchet tasks that run an agent’s model requests, tool calls, and other operations.
The registration options are fixed when the agent is constructed, as Hatchet registers each task
once, so they can only vary per toolset (see toolset_task_config). The run options are applied
each time a task is spawned, so a tool’s 'hatchet' metadata can also set them.
How many times Hatchet retries a failed task. Defaults to 0.
Type: int
How long one attempt may run before Hatchet fails it. Defaults to 60 seconds.
Type: timedelta
How long a task may wait for a worker before Hatchet fails it. Defaults to 5 minutes.
Type: timedelta
The exponential backoff factor between retries.
Type: float
The maximum backoff between retries.
Type: timedelta
Hatchet rate limits the task consumes, e.g. to cap the requests a model provider gets across workers.
Type: list[RateLimit]
Hatchet concurrency limits for the task.
Type: int | ConcurrencyStrategy | list[ConcurrencyStrategy]
The priority the task’s runs get unless priority is set.
Type: Priority
The priority of each run of the task.
Type: Priority
Whether to run the task on the worker running the durable task, which keeps its local state warm.
Type: bool
Labels the worker running the task should have, e.g. to run a tool on a worker with a GPU.
Type: list[DesiredWorkerLabel]
Extra metadata attached to each run, shown and filterable in the Hatchet dashboard.
Bases: BaseDurabilityCapability[AgentDepsT]
Capability that makes an agent durable by running its model requests and tool calls as Hatchet tasks.
When the agent runs inside a Hatchet durable task, each model request, MCP communication and tool call is spawned as a child task, whose result the durable task’s event log records: a durable task that’s replayed after a crash, an eviction or a retry gets the results back without making the requests again. Outside a durable task, the capability is transparent.
The tasks are registered on hatchet when the capability is attached to an agent. Pass
workflows to the worker
alongside the durable task that runs the agent.
The Hatchet client the capability registers its tasks on.
Type: Hatchet Default: hatchet
The HatchetRunContext subclass used to serialize/deserialize the run context.
Type: type[HatchetRunContext[AgentDepsT]] Default: run_context_type
The Hatchet tasks the capability registered, to pass to hatchet.worker(workflows=...).
A worker that runs the durable task running the agent needs them, or another worker on the same Hatchet tenant does: a child task runs on whichever worker serves it.
Type: list[Standalone[TaskInput, TaskOutput]]
def __init__(
hatchet: Hatchet,
*,
models: Mapping[str, Model] | None = None,
event_stream_handler: EventStreamHandler[AgentDepsT] | None = None,
name: str | None = None,
deps_type: type[AgentDepsT] | None = None,
task_config: HatchetTaskConfig | None = None,
model_task_config: HatchetTaskConfig | None = None,
event_stream_handler_task_config: HatchetTaskConfig | None = None,
toolset_task_config: Mapping[str, HatchetTaskConfig] | None = None,
run_context_type: type[HatchetRunContext[AgentDepsT]] = HatchetRunContext[AgentDepsT],
non_retryable_model_errors: Sequence[type[ModelAPIError]] = _DEFAULT_NON_RETRYABLE_MODEL_ERRORS,
event_stream: bool | HatchetEventStream = False,
) -> None
Create a HatchetDurability capability.
The agent’s model, name, and toolsets are discovered when the capability is attached to an agent.
The Hatchet client to register the agent’s tasks on.
Additional models keyed by ID for runtime model switching. The agent’s primary model is
always registered as 'default'. A Model instance can’t be serialized into a task, so a
run-time model instance has to be registered here and referenced by key; model name strings
cross as written and are built on the worker.
event_stream_handler : EventStreamHandler[AgentDepsT] | None Default: None
Optional event stream handler. Model events are handled live inside the model request tasks, and other events in a task per event.
Unique agent name used in the Hatchet task names. Defaults to the agent’s name.
The type of the agent’s dependencies, used to serialize them into tasks as JSON.
Defaults to the agent’s own deps_type.
task_config : HatchetTaskConfig | None Default: None
Base Hatchet task config for all tasks. Defaults to a 60-second
execution_timeout and no retries.
model_task_config : HatchetTaskConfig | None Default: None
Task config merged on top of the base for model request tasks.
event_stream_handler_task_config : HatchetTaskConfig | None Default: None
Task config merged on top of the base for event stream handler tasks.
Per-toolset task configs keyed by toolset ID, merged on top of the base.
run_context_type : type[HatchetRunContext[AgentDepsT]] Default: HatchetRunContext[AgentDepsT]
The HatchetRunContext subclass used to serialize the run context into tasks.
non_retryable_model_errors : Sequence[type[ModelAPIError]] Default: _DEFAULT_NON_RETRYABLE_MODEL_ERRORS
Model error classes that fail a model task without Hatchet retrying
it, whatever its retries say, subclasses included. The durable task still receives the error
as its own class. Defaults to
ModelRequestRejectedError,
ModelQuotaExceededError and
ModelRequestTimeout; () retries them all.
event_stream : bool | HatchetEventStream Default: False
True, or a HatchetEventStream,
to publish the run’s events to a Hatchet durable stream topic, by default one per durable task and agent, so a
consumer outside the durable task can observe them as they happen with
stream_agent_events().
Model events are published live from the model request task, so tokens stream through.
Orthogonal to event_stream_handler: when both are set, the handler still sees every event.
@async
def wrap_run(
ctx: RunContext[AgentDepsT],
*,
handler: WrapRunHandler,
) -> AgentRunResult[Any]
Make the run replay-safe: durable sleeps for the agent graph’s waits, and message times from a durable clock.
A replayed durable task spawns its child tasks again and Hatchet checks each against the recorded one, input included, so the run must stamp its messages with the times it stamped the first time.
@async
def durable_sleep(seconds: float) -> None
Wait with a durable Hatchet sleep, which survives a replay of the durable task.
@async
def wrap_run_event_stream(
ctx: RunContext[AgentDepsT],
*,
stream: AsyncIterable[AgentStreamEvent],
) -> AsyncIterable[AgentStreamEvent]
Publish the run’s durable-task-side events to its topic.
AsyncIterable[AgentStreamEvent]
def stream_agent_events(
workflow_run_id: str,
*,
output_type: type[OutputDataT] = cast('type[Any]', Any),
cursor: str | None = None,
) -> HatchetAgentRunEvents[OutputDataT]
Subscribe to the events a durable agent run publishes with event_stream set.
This is a durable run_stream_events(): the events
arrive typed and in order, ending with the AgentRunResultEvent
that carries the run’s result, so they can be handed to a UIAdapter. The
topic keeps its messages after the run, so a consumer can subscribe late, or again.
A run that times out or cancels itself ends the iterator like any failed run. A run that fails while the
durable task has retries left publishes no error, as the retry’s run publishes the outcome. If the durable
task catches that error instead, the iterator goes on to the task’s next agent run, if any. A durable task that Hatchet
cancels publishes no terminal event, because Hatchet stops a task it evicts the same way and an evicted task’s
run continues once it’s restored. A consumer that has to notice a cancelled run checks the workflow run’s
status, e.g. with hatchet.runs.aio_get_status(workflow_run_id).
HatchetAgentRunEvents[OutputDataT]
workflow_run_id : str
The workflow run ID of the durable task running the agent.
output_type : type[OutputDataT] Default: cast('type[Any]', Any)
The agent’s output type, so the terminal event’s result is decoded into it.
The cursor of an earlier iterator, to resume right after the last event it read. The new
iterator doesn’t know which events the earlier one yielded, so an event a replayed durable task
published again after that cursor is yielded again.
Bases: Generic[OutputDataT], AsyncIterator[AgentStreamEvent | AgentRunResultEvent[OutputDataT]]
The event iterator returned by HatchetDurability.stream_agent_events().
A durable run_stream_events(): it yields the run’s
AgentStreamEvents in order, ending with the
AgentRunResultEvent that carries the result, while the run itself
executes on a Hatchet worker. A run that fails publishes no result: the iterator then ends early, with the
failure in error. A durable task that runs the agent more than once publishes a terminal event
per run, so this iterator ends at the first; resume from its cursor to read the next run’s events.
The server hangs up a subscription that has been idle, and the iterator subscribes again after the last
message read. A subscription that ends at once without a message, as when the tenant’s durable streams are
turned off, is retried after a wait that doubles from 0.1 up to 5 seconds; after 20 in a row, the iterator
raises a UserError naming the topic.
The cursor of the last message read, to resume a subscription right after it.
The run’s result, once the terminal event has been yielded.
Type: AgentRunResult[OutputDataT] | None
Why the run failed, if the iterator ended without a result because it did.
The durable task’s own result says how it ended, including a failure after the run published its result.
@async
def aclose() -> None
Stop the underlying subscription; reaching the terminal event does this for you.