Skip to content

pydantic_ai.in_flight

Tracking work that outlives the step that started it, through RunContext.in_flight.

See Work that outlives a step.

InFlightWorkSnapshot

The state of a piece of in-flight work at the time an InFlightWorkEvent was emitted.

Attributes

id

The work’s ID, unique among the run’s live work.

Type: str

kind

The kind of work, such as 'background_tool'.

Type: str

name

A name for the work, for display.

Type: str

on_end

What happens to the work when the run ends.

Type: InFlightOnEnd

durable

Whether a durable execution engine records the work’s result on its own.

Type: bool

state

Where the work was in its life.

Type: InFlightWorkState

InFlightWorkEvent

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.

Attributes

phase

What happened.

Type: InFlightWorkPhase

work

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, …]

live

How many pieces of work were live afterwards, of any on_end.

Type: int

InFlightWork

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.

Attributes

id

The work’s ID, unique among the run’s live work: usually the tool call or task ID it belongs to.

Default: id

kind

The kind of work, such as 'background_tool', to tell different producers’ work apart.

Default: kind

name

A name for the work, for display.

Default: name

durable

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

on_end

What happens to the work when the run ends, fixed when it was started or registered.

Type: InFlightOnEnd

state

Where the work is in its life.

Type: InFlightWorkState

Methods

wait

@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.

Returns

None

result

@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.

Returns

T

Raises
  • BaseException — The error the work failed with.
  • asyncio.CancelledError — If the work was cancelled, as awaiting a cancelled task does.
cancel
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.

Returns

None

InFlightRegistry

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 you settle() 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.

Methods

__init__
def __init__(event_stream_buffer: list[AgentStreamEvent]) -> None

Created by the run; don’t create one yourself.

Returns

None

start
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.

Returns

InFlightWork[T] — A handle on the work.

Parameters

fn : Callable[[], Awaitable[T]]

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.

Raises
  • UserError — If the run has ended, live work already has this id, on_end is 'detach', or this isn’t called from the event loop running the agent.
register
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.

Returns

InFlightWork[None] — A handle on the work.

Parameters

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.

on_end : InFlightOnEnd Default: 'detach'

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.

cancel : Callable[[], None] | None Default: None

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.

Raises
  • UserError — If the run has ended, live work already has this id, or this isn’t called from the event loop running the agent.
settle
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.

Returns

None

Parameters

work : InFlightWork[None]

The handle register() returned.

error : BaseException | None Default: None

The error the work failed with, if it failed.

Raises
  • UserError — If work was started with start(), which settles it when its coroutine finishes, or this isn’t called from the event loop running the agent, unless the run has ended and work is 'detach' work. From another thread, schedule the call on that loop: capture it with asyncio.get_running_loop() where you registered the work, and call loop.call_soon_threadsafe(ctx.in_flight.settle, work).
live
def live(*, kind: str | None = None) -> tuple[InFlightWork[Any], ...]

The work that hasn’t settled yet, of every on_end, oldest first.

Returns

tuple[InFlightWork[Any], …]

Parameters

kind : str | None Default: None

Only list work of this kind.

Raises
  • UserError — If this isn’t called from the event loop running the agent, which changes the live work.
wait_idle

@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.

Returns

None

Parameters

kind : str | None Default: None

Only wait for work of this kind.

Raises
  • UserError — If this isn’t called from the event loop running the agent.

external_waits_apply_on_end

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.

Returns

Generator[None]

durable_wait_scope

@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.

Returns

AsyncGenerator[None]

InFlightOnEnd

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 with DeferredToolRequests or a PendingModelResponse, 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']

InFlightWorkState

Where a piece of in-flight work is in its life.

Type: TypeAlias Default: Literal['running', 'succeeded', 'failed', 'cancelled']

InFlightWorkPhase

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']