feat(fallback): support fallback model handling for streaming cases

AG
3d ago
+929-99

Overview

Extends FallbackModel.request_stream() so response-handler fallback works for streaming responses. When a streamed candidate is rejected, the stream emits a generic ModelResponseResetEvent before continuing with the next model.

This keeps streaming live, without buffering rejected candidates, while giving higher layers a first-class boundary so they can avoid committing to stale output.

Architecture

_FallbackStreamedResponse remains, but its role changes from "hide fallback as one seamless response" to "coordinate candidate streams and label discarded boundaries".

agent.run_stream()
└─ ModelRequestNode.stream()
   └─ FallbackModel.request_stream()
      ├─ create AsyncExitStack
      ├─ create _FallbackStreamedResponse
      ├─ response.open_next_stream()
      │  ├─ prepare candidate model
      │  ├─ prepare messages
      │  └─ enter candidate stream into AsyncExitStack
      └─ yield _FallbackStreamedResponse

During iteration:

_FallbackStreamedResponse.__aiter__()
└─ _get_event_iterator()
   ├─ current_stream = candidate stream
   ├─ async for event in current_stream._get_event_iterator()
   │  └─ yield raw inner event live
   ├─ response = current_stream.get()
   ├─ if response handler rejects:
   │  ├─ yield ModelResponseResetEvent(response=rejected_response)
   │  ├─ open_next_stream()
   │  └─ continue with next candidate
   └─ else:
      ├─ accept current model
      └─ return

So a reject to accept stream is explicitly labeled:

model 1:
PartStartEvent(...)
FinalResultEvent(...)
PartEndEvent(...)
ModelResponseResetEvent(response=model_1_response)

model 2:
PartStartEvent(...)
FinalResultEvent(...)
PartDeltaEvent(...)
PartEndEvent(...)

Design Notes

  • ModelResponseResetEvent is generic, not fallback-specific. It represents "discard the streamed response parts before this point", which can also support future mid-stream retry wrappers.
  • FinalResultEvent is unchanged. Reset events cause the agent stream loop to clear any previously latched FinalResultEvent and re-arm for the accepted model.
  • The wrapper iterates inner raw stream events via _get_event_iterator() so PartEndEvent and FinalResultEvent transformer chains are not applied twice.
  • Candidate streams are managed through an AsyncExitStack, so early stream exits release active inner streams deterministically.
  • stream_text() resets its accumulator on ModelResponseResetEvent, avoiding silent concatenation of rejected and accepted text.

UI Behavior

UI adapters currently ignore ModelResponseResetEvent safely via their existing default event handling. Active UI false-start discard, such as AG-UI starting a fresh message id or Vercel starting a fresh step on reset, is intentionally left as a follow-up.

Tests

Added coverage for:

  • raw event sequences for accepted and rejected streaming fallback candidates
  • no duplicate PartEndEvent / FinalResultEvent
  • response-handler rejection followed by accepted fallback stream
  • mid-stream fallbackable exception followed by accepted fallback stream
  • stream_text() accumulator reset after rejected response

Local checks:

  • uv run pytest tests/models/test_fallback.py -q
  • uv run pytest tests/test_streaming.py -q
  • uv run pytest tests/test_ui.py::test_run_stream_text_and_thinking -q
  • PYRIGHT_PYTHON_IGNORE_WARNINGS=1 uv run pyright pydantic_ai_slim/pydantic_ai/messages.py pydantic_ai_slim/pydantic_ai/models/fallback.py pydantic_ai_slim/pydantic_ai/models/__init__.py pydantic_ai_slim/pydantic_ai/agent/abstract.py pydantic_ai_slim/pydantic_ai/result.py

PR Iterations

v0 Description

The original PR version extended FallbackModel.request_stream() by adding _FallbackStreamedResponse, a wrapper that attempted to make response-handler fallback transparent for streaming requests.

In that version:

  • FallbackModel.request_stream() yielded _FallbackStreamedResponse only when fallback_on included response handlers.
  • The wrapper opened each candidate model stream in order, forwarded events live, assembled the response, and ran the response handler after the candidate stream completed.
  • If the handler rejected candidate N, the wrapper reset its local parts state, opened candidate N+1, and continued yielding events through the same outer stream.
  • Exception-only streaming fallback kept the legacy single-yield path.
  • The documented UX caveat was that consumers might see a rejected model's streamed events before the accepted model's events.

Reviewer feedback identified that this "transparent wrapper" architecture hid a real stream boundary:

  • It iterated the inner stream through inner_sr.__aiter__() and then applied the outer StreamedResponse.__aiter__() transformers again, duplicating additive events such as PartEndEvent and FinalResultEvent.
  • It rebased the outer parts manager between candidates, allowing part-end state from a rejected model to cross into the accepted model's event sequence.
  • It opened inner streams inside the event iterator, tying cleanup to generator finalization instead of the request_stream() context manager.
  • Most importantly, it gave agent/result/UI layers no signal that a previously emitted FinalResultEvent belonged to a rejected model.

The current iteration keeps the no-buffering streaming behavior, but replaces the hidden boundary with an explicit ModelResponseResetEvent that higher layers can consume.