Give `AgentRunError` the failed run's `conversation`, and add `capture_run_conversation()`, so a failed turn can be stored

Merged
DO
17d ago
+782-100

Part of #11846, the half about keeping a failed run so it can be stored, not the wrap-up design. Store-backed server-held UI history (#11031) needs it, so a client can see what a failed turn did.

What

  • AgentRunError.conversation. A run that hit a usage limit, a model error or a cancellation can now be stored: await store.save(error.conversation) appends the failed turn to a ConversationStore.
    • It's the run's conversation as far as it got, including a response or request cut short (state='interrupted').
    • It's built the same way AgentRunResult.conversation is, so it carries the revision and knows which messages are new. So the save is checked for conflicts, and appends just what the run added.
    • Before this, only RunCancelled carried its messages, and nothing carried the conversation.
  • A nested run's error carries the outer run's conversation. That's the one its caller can store, matching how a nested RunCancelled is already stamped again.
  • capture_run_conversation() works like capture_run_messages(), but yields a CapturedConversation whose .conversation covers any exception, including one raised by a tool's own code, which can't carry an attribute of ours. It's exported from pydantic_ai and pydantic_ai.agent.
  • Refactor: AgentRunResult.conversation's logic moves to a module-level conversation_from_state, shared with the failed-run path. Its behavior is unchanged.

Scope

  • Plain Agent users see no change in behavior. Errors gain an attribute, built once when the error passes the run's edge. The attaching lives in a small context manager rather than more branches in _PreparedAgentRun.open, which is already over the complexity limit.
  • Realtime sessions aren't wired. Their errors' conversation is None, as documented.

Tests

tests/test_conversation_store.py:

  • Usage limit: a run on a loaded conversation that hits its usage limit saves just the new turn (the prompt, the tool call and its return), and reloads in full.
  • Tool exception: a tool that raises leaves a capture whose conversation stores the prompt, the call and the cut-short request.
  • Cancellation: a cancelled run's conversation matches RunCancelled.all_messages().
  • Nested run: a nested run's usage-limit error reaches the outer caller carrying the outer conversation.

Undoing each wiring point fails a test: attaching on errors, on cancellation, the capture registration, and outer-wins stamping. The new docstring example runs and prints what it documents.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.

๐Ÿค– Generated with Claude Code


Summary by cubic

AgentRunError now carries the failed run's conversation, so a turn that hit a usage limit, model error, or cancellation can still be stored with store.save(error.conversation).

  • conversation is built like AgentRunResult.conversation, so a save appends just what the run added; a resumed run that fails before adding a message keeps its conversation's pending tool calls (as a copy, so the original isn't mutated), while one that fails after running approved calls leaves none waiting.
  • A nested run's error carries the outer run's conversation, since that's the one its caller can store. A nested run's RunCancelled keeps its own conversation, available as the outer error's cause. For batched runs, each run gets its own copy of the error โ€” when a batch submission fails, and when a run joins another run's shared check โ€” so one failed run's conversation isn't another's; an error that can't be copied is shared instead, so the other requests don't wait forever.
  • New capture_run_conversation() captures the same conversation for any exception, including a tool's own or a FallbackExceptionGroup; nested contexts capture the innermost run, and it's exported from pydantic_ai and pydantic_ai.agent.
  • CapturedConversation.conversation is built on first read and cached once the run ends: a read during the run returns a fresh snapshot, while a saved conversation keeps its new revision on later reads.
  • The conversation-building logic moves to a private _run_conversation module shared with the success path; behavior is unchanged for plain Agent users, and conversation is None for realtime errors and for an AgentRunError caught inside an iter or run_stream block. RunCancelled now carries it too, including on an externally cancelled event stream.
  • Any AgentRunError keeps its conversation when pickled, as durable engines like DBOS do.
  • Docs now note that conversation=error.conversation carries the conversation's usage forward, so limits check the total of both runs, that a Temporal client gets a failed workflow run's error without its conversation so the workflow saves it inside the workflow, and that DBOS records a failed workflow run's conversation with its error.