Keep native tool returns ahead of function tool calls when `AGUIAdapter` loads messages
- Closes #12151
An AG-UI AssistantMessage holds all of a response's tool calls, and the ToolMessages with their results come after it. That is how dump_messages writes a response and how a frontend stores one from the event stream. On load, a native tool return was appended at the end of the response, so [NativeToolCallPart, NativeToolReturnPart, ToolCallPart] came back as [NativeToolCallPart, ToolCallPart, NativeToolReturnPart]. Anthropic then rejects the next request. Live with anthropic:claude-sonnet-4-5 and a defer_loading tool: history passed straight through works, and the round-tripped history fails with 400 tool_use ids were found without tool_result blocks immediately after. With this change both work.
AGUIAdapter.load_messages now moves each native tool return ahead of any function tool calls directly before it in the response. Native parts keep the order they arrived in, so a server tool called from inside another one (Anthropic web fetch run by code execution, [cA, cB, rB, rA]) still loads as before. The fix is in the AG-UI loader because that is where the order is lost, and frontend-stored histories only reach the server through it. Changing only the dump would leave those histories broken. Changing the Anthropic mapping would hide a lossy round trip.
Reviewer note: a response with a function call between a native call and its return, [native call, function call, native return], now loads with the return before the function call. Pydantic AI's Google mapping can build that shape: it adds file search returns from grounding metadata at the end of the response.
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.
Summary by cubic
Fixes the ordering of native tool returns when AGUIAdapter loads messages, so Anthropic no longer rejects round-tripped histories with tool_use/tool_result ordering errors (issue #12151).
- Native tool returns now load directly after their native calls, ahead of trailing function tool calls.
- Native parts keep their original relative order, preserving nested server-tool call sequences (e.g. a web fetch run by code execution).
- Only the loader changes; frontend-stored histories round-trip correctly without affecting the dump format or Anthropic mapping.
Migration
None required. No breaking changes.