AG-UI adapter asserts when a model emits reasoning after content
Initial Checks
- I'm using the latest version of Pydantic AI
- I've searched for my issue in the issue tracker before opening this issue
Description
AG-UI adapter asserts when a model emits reasoning after content
Summary
When a model streams reasoning, then content, then reasoning again,
AGUIEventStream.handle_thinking_delta raises AssertionError. The stream
converts it to a RUN_ERROR event and the run terminates, mid-response.
This is reachable from ordinary provider output, not from misuse of the API.
Versions
pydantic-ai-slim2.42.0 and 2.48.0 — reproduces on bothag-ui-protocol0.1.18- Python 3.13
Reproduction
Self-contained; no model or network required.
"""Minimal reproduction: AG-UI adapter asserts on reasoning-after-content."""
import asyncio
from pydantic_ai.messages import PartDeltaEvent
from pydantic_ai.messages import PartEndEvent
from pydantic_ai.messages import PartStartEvent
from pydantic_ai.messages import TextPart
from pydantic_ai.messages import ThinkingPart
from pydantic_ai.messages import ThinkingPartDelta
from pydantic_ai.ui.ag_ui import AGUIEventStream
THINKING = ThinkingPart(content='I should call the cite tool first.')
TEXT = TextPart(content='The answer is 42.')
async def events():
# 1. Reasoning segment.
yield PartStartEvent(index=0, part=THINKING)
yield PartEndEvent(index=0, part=THINKING, next_part_kind='text')
# 2. Content.
yield PartStartEvent(index=1, part=TEXT, previous_part_kind='thinking')
yield PartEndEvent(index=1, part=TEXT, next_part_kind='thinking')
# 3. Reasoning resumes on the *same* part index -- see "Root cause".
yield PartDeltaEvent(index=0, delta=ThinkingPartDelta(content_delta='Wait'))
async def main():
stream = AGUIEventStream()
async for event in stream.transform_stream(events()):
detail = getattr(event, 'message', '')
print(f' {type(event).__name__}{": " + detail if detail else ""}')
if __name__ == '__main__':
asyncio.run(main())Actual output
RunStartedEvent
ReasoningStartEvent
ReasoningMessageStartEvent
ReasoningMessageContentEvent
ReasoningMessageEndEvent
ReasoningEndEvent
TextMessageStartEvent
TextMessageContentEvent
TextMessageEndEvent
RunErrorEvent: handle_thinking_start must be called before handle_thinking_deltaExpected
The second reasoning segment should be emitted as a new reasoning message
(ReasoningStartEvent / ReasoningMessageStartEvent / ...), and the run
should finish with RunFinishedEvent.
Root cause
Two pieces interact.
1. The OpenAI Chat Completions adapter keys thinking deltas on a constant.
pydantic_ai/models/openai.py, in OpenAIStreamedResponse._map_thinking_delta:
for field_name in (custom_field, 'reasoning', 'reasoning_content'):
...
yield from self._parts_manager.handle_thinking_delta(
vendor_part_id=field_name, # <-- constant for the whole response
id=field_name,
content=reasoning,
provider_name=self.provider_name,
)
breakvendor_part_id is the field name, so every reasoning burst in a response maps
to the same part. When reasoning resumes after content, the parts manager
finds the existing ThinkingPart and emits a PartDeltaEvent rather than a
PartStartEvent. That is what step 3 of the reproduction models.
2. The AG-UI stream has already ended that thinking part.
pydantic_ai/ui/ag_ui/_thinking_0_11.py, handle_thinking_end, ends by
clearing the id unconditionally:
yield ReasoningEndEvent(message_id=message_id)
self._reasoning_message_id = Nonepydantic_ai/ui/ag_ui/_event_stream.py accepts the dispatcher's
followed_by_thinking hint and does not use it:
async def handle_thinking_end(
self, part: ThinkingPart, followed_by_thinking: bool = False
) -> AsyncIterator[BaseEvent]:
assert self._reasoning_message_id is not None, '...'
...
async for event in _impl(self, part): # `followed_by_thinking` dropped
yield eventThe text path in the same class does honour its equivalent:
async def handle_text_end(self, part: TextPart, followed_by_text: bool = False):
if not followed_by_text:
yield TextMessageEndEvent(message_id=self.message_id)So once a TextPart follows, _reasoning_message_id is None, and the next
ThinkingPartDelta trips the assertion in handle_thinking_delta
(_event_stream.py, ~line 308).
How we hit it in production
vLLM 0.30 serving Gemma 4 with --reasoning-parser gemma4. That parser has an
explicit state transition for reasoning resuming after content:
(ParserState.CONTENT, "THINK_START"): Transition(
ParserState.REASONING, (EventType.REASONING_START,),
),so reasoning-after-content is expected output for the model, not an anomaly. A captured run produced, in delta order:
reasoning x 598 -> content x 294 -> reasoning x 1The model finished its answer and opened a second thought channel (it had planned to call a tool it skipped). The client aborted one token into that second segment.
This is not provider-specific: any model that thinks again before a follow-up tool call produces the same shape.
Suggested fixes
Any one of these would resolve it; the first is the smallest.
- Have
handle_thinking_deltastart a new reasoning message when_reasoning_message_idisNone, instead of asserting._thinking_0_11'shandle_thinking_deltaalready lazily emitsReasoningStartEventwhen_reasoning_startedis false, so the structure for this is present. - Honour
followed_by_thinkingin the AG-UIhandle_thinking_end, the way the text path honoursfollowed_by_text. - Give OpenAI Chat thinking deltas a
vendor_part_idthat changes when reasoning resumes after another part kind, so a newThinkingPart(and therefore aPartStartEvent) is started.
Separately: an assert is a weak guard for a condition reachable from provider
output, and it is compiled out under python -O, where the failure would
become a confusing None message id rather than an error.
Minimal, Reproducible Example
"""Minimal reproduction: AG-UI adapter asserts on reasoning-after-content.
A provider that emits reasoning, then content, then reasoning again produces a
ThinkingPartDelta for a ThinkingPart the AG-UI event stream has already ended.
"""
import asyncio
from pydantic_ai.messages import PartDeltaEvent
from pydantic_ai.messages import PartEndEvent
from pydantic_ai.messages import PartStartEvent
from pydantic_ai.messages import TextPart
from pydantic_ai.messages import ThinkingPart
from pydantic_ai.messages import ThinkingPartDelta
from pydantic_ai.ui.ag_ui import AGUIEventStream
THINKING = ThinkingPart(content='I should call the cite tool first.')
TEXT = TextPart(content='The answer is 42.')
async def events():
# 1. Reasoning segment.
yield PartStartEvent(index=0, part=THINKING)
yield PartEndEvent(index=0, part=THINKING, next_part_kind='text')
# 2. Content.
yield PartStartEvent(index=1, part=TEXT, previous_part_kind='thinking')
yield PartEndEvent(index=1, part=TEXT, next_part_kind='thinking')
# 3. Reasoning resumes. The OpenAI Chat adapter keys thinking deltas on a
# constant vendor_part_id ('reasoning_content'), so the second burst
# reuses index 0 and arrives as a delta, not a new part.
yield PartDeltaEvent(index=0, delta=ThinkingPartDelta(content_delta='Wait'))
async def main():
stream = AGUIEventStream()
async for event in stream.transform_stream(events()):
detail = getattr(event, 'message', '')
print(f' {type(event).__name__}{": " + detail if detail else ""}')
if __name__ == '__main__':
asyncio.run(main())Logfire Trace
No response
Python, Pydantic AI & LLM client version
- Python: 3.13.15
- Pydantic AI: 2.49.0
- LLM provider SDK: vllm 0.30
Source: pydantic/pydantic-ai