pydantic_ai.in_flight
Tracking work that outlives the step that started it, through RunContext.in_flight.
See Work that outlives a step.
The state of a piece of in-flight work at the time an InFlightWorkEvent was emitted.
The work’s ID, unique among the run’s live work.
Type: str
The kind of work, such as 'background_tool'.
Type: str
A name for the work, for display.
Type: str
What happens to the work when the run ends.
Type: InFlightOnEnd
Whether a durable execution engine records the work’s result on its own.
Type: bool
Where the work was in its life.
Type: InFlightWorkState
Bases: CapabilityEvent
Reports in-flight work starting and settling, and the run waiting for it before it ends.
A UI can show that the agent is still working from live, without knowing which capability started the
work. Emitted by the run itself, so its capability_id is None.
What happened.
Type: InFlightWorkPhase
The work it happened to: the piece that started or settled, or the 'drain' work the run waits for.
For 'draining', the work the run starts waiting for; for 'drained', all the work it waited for, including
draining work started while it waited.
Type: tuple[InFlightWorkSnapshot, …]
How many pieces of work were live afterwards, of any on_end.
Type: int
Bases: Generic[T]
A handle on a piece of work that outlives the step that started it.
Returned by InFlightRegistry.start() and
InFlightRegistry.register(); don’t create one yourself.
The work’s ID, unique among the run’s live work: usually the tool call or task ID it belongs to.
Default: id
The kind of work, such as 'background_tool', to tell different producers’ work apart.
Default: kind
A name for the work, for display.
Default: name
Whether a durable execution engine records the work’s result on its own, as an activity, step or task.
Recorded on the handle and in events; the run doesn’t act on it yet.
Default: durable
What happens to the work when the run ends, fixed when it was started or registered.
Type: InFlightOnEnd
Where the work is in its life.
Type: InFlightWorkState
@async
def wait() -> None
Wait until the work has settled: finished, failed or been cancelled. Never raises the work’s error.
Work started with start() that waits for itself never
returns.
@async
def result() -> T
Wait until the work has settled, and return its result.
Work that was registered has no result, so this
returns None for it.
T
BaseException— The error the work failed with.asyncio.CancelledError— If the work was cancelled, as awaiting a cancelled task does.
def cancel() -> None
Cancel the work, if it’s still running.
Work run by start() has its task cancelled, and
settles once the task has stopped. Registered work has the cancel callback it was registered with
called, and settles as cancelled right away, even if the callback raises.
The run’s registry of work that outlives the step that started it, available as ctx.in_flight.
Work goes in either way:
start()runs a coroutine as a task the run owns.register()tracks work something else runs, like a process, until yousettle()it. By default the run only lists that work, since it usually outlives the run.
Each run has its own registry, which a run started from inside it doesn’t share. Call its methods from the event loop running the agent, such as from an async tool or a capability hook.
def __init__(event_stream_buffer: list[AgentStreamEvent]) -> None
Created by the run; don’t create one yourself.
def start(
fn: Callable[[], Awaitable[T]],
/,
*,
kind: str,
name: str,
id: str,
on_end: Literal['drain', 'cancel'] = 'drain',
durable: bool = False,
) -> InFlightWork[T]
Run fn() as a task the run owns, and track it.
fn delivers its own results, usually by calling ctx.enqueue().
An error fn raises ends the run once the step that’s running when it fails has finished, or while the
run waits for the work to end, so catch the errors the model should hear about and enqueue them instead.
The run’s node error hooks don’t see the error, and an error raised after the run’s last step is not
raised at all. If several pieces of work fail, only the first error is raised.
When the run ends, it cancels the work it doesn’t wait for and waits for it to stop, which nothing,
not even the run’s timeout=, cuts short: fn must let cancellation stop it, or the run never returns.
InFlightWork[T] — A handle on the work.
The work to run, called with no arguments.
kind : str
The kind of work, such as 'background_tool', to tell different producers’ work apart.
name : str
A name for the work, for display.
id : str
The work’s ID, unique among the run’s live work. Make it deterministic, such as the ID of the tool call that starts the work, so the same work gets the same ID when a run is replayed.
on_end : Literal[‘drain’, ‘cancel’] Default: 'drain'
What happens to the work when the run ends: 'drain' waits for it, 'cancel' cancels it.
Work that should outlive the run isn’t the run’s to own: run it yourself and
register() it, which detaches it by default.
durable : bool Default: False
Whether a durable execution engine records the work’s result on its own, as an activity, step or task. The run doesn’t act on it yet.
UserError— If the run has ended, live work already has thisid,on_endis'detach', or this isn’t called from the event loop running the agent.
def register(
*,
kind: str,
name: str,
id: str,
on_end: InFlightOnEnd = 'detach',
durable: bool = False,
cancel: Callable[[], None] | None = None,
) -> InFlightWork[None]
Track work that something else runs, such as a process or a task another object owns.
Call settle() when it has finished. The work delivers
its own results, as with start(), but an error it
settles with doesn’t end the run.
Work that something else owns usually lives in a resource that outlives the run, so by default the run
only lists it. Pass on_end='drain' when its result belongs to this run, or on_end='cancel' when it’s
worthless once the run is over.
InFlightWork[None] — A handle on the work.
kind : str
The kind of work, such as 'shell_job', to tell different producers’ work apart.
name : str
A name for the work, for display.
id : str
The work’s ID, unique among the run’s live work. Make it deterministic, such as the ID of the tool call that starts the work.
What happens to the work when the run ends: by default nothing, as it’s 'detach'. See
InFlightOnEnd.
durable : bool Default: False
Whether a durable execution engine records the work’s result on its own, as an activity, step or task. The run doesn’t act on it yet.
Stops the work, when the run or a call to
InFlightWork.cancel() cancels it. Without one,
cancelling the work only stops tracking it. If it raises when the run cancels the work, the run
still cancels its other work, then raises the error, unless the run is failing or being cancelled
anyway, in which case the caller gets that instead.
UserError— If the run has ended, live work already has thisid, or this isn’t called from the event loop running the agent.
def settle(work: InFlightWork[None], *, error: BaseException | None = None) -> None
Record that registered work has finished.
Settling work that has already settled, for example because it was cancelled, does nothing. Once the run
has ended, only 'detach' work is left, and it can be settled from anywhere, like a later run’s event loop.
work : InFlightWork[None]
The handle register() returned.
error : BaseException | None Default: None
The error the work failed with, if it failed.
UserError— Ifworkwas started withstart(), which settles it when its coroutine finishes, or this isn’t called from the event loop running the agent, unless the run has ended andworkis'detach'work. From another thread, schedule the call on that loop: capture it withasyncio.get_running_loop()where you registered the work, and callloop.call_soon_threadsafe(ctx.in_flight.settle, work).
def live(*, kind: str | None = None) -> tuple[InFlightWork[Any], ...]
The work that hasn’t settled yet, of every on_end, oldest first.
Only list work of this kind.
UserError— If this isn’t called from the event loop running the agent, which changes the live work.
@async
def wait_idle(*, kind: str | None = None) -> None
Wait until all live work, except 'detach' work, has settled. Never raises the work’s errors.
Called from work started with start() that this would
wait for, it waits for itself and never returns: pass a kind that excludes it.
Only wait for work of this kind.
UserError— If this isn’t called from the event loop running the agent.
def external_waits_apply_on_end(registry: InFlightRegistry | None) -> Generator[None]
Make a durable wait for an external event inside apply the on_end of registry’s work.
@async
def durable_wait_scope() -> AsyncGenerator[None]
Apply the on_end of the waiting run’s work around a wait for an external event that a durable engine records.
What happens to live work when the run ends.
'drain': for work whose result belongs to this run. The run waits for it: when the run ends with output, until content has been queued or all draining work has finished, so the model gets another turn on what was queued; when the run pauses withDeferredToolRequestsor aPendingModelResponse, until all of it has.'cancel': for best-effort work that is worthless once the run is over. The run cancels it when it ends.'detach': for work that lives in a resource that outlives the run, like a shell job, a process in a workspace that is kept, or a task an application-owned object runs. The run lists it while it lives, but never waits for it or cancels it.
A run that ends with an error, is cancelled, times out or hits a usage limit cancels all work except 'detach'
work.
A durable run that waits for an external event the engine records, such as an answer to a
HandleDeferredToolCalls handler that takes a resume token,
applies on_end at the wait as well. It cancels 'cancel' work before it waits. It keeps 'drain' work running
through the wait, and only goes on once that work has finished too. It leaves 'detach' work alone.
Type: TypeAlias Default: Literal['drain', 'cancel', 'detach']
Where a piece of in-flight work is in its life.
Type: TypeAlias Default: Literal['running', 'succeeded', 'failed', 'cancelled']
What an InFlightWorkEvent reports.
'started': a piece of work was started or registered.'settled': a piece of work finished, failed or was cancelled.'draining': the run is about to end and is waiting for its'drain'work.'drained': the run stopped waiting.
Type: TypeAlias Default: Literal['started', 'settled', 'draining', 'drained']