fix(ai): replay each in-flight tool round as its own message pair
Fixes part 1 of #4121.
Problem
When a chat turn needs more than one tool round, Assistant::Responder#respond collects every
round's results into one flat in_flight_function_results array. The providers that rebuild the
in-flight history on each follow-up call then emit all of those results as a single tool-call
message:
Provider::Openai#build_generic_messages(Chat Completions path, e.g. custom
OpenAI-compatible providers such as llama.cpp, Ollama or vLLM) emits one
assistant{tool_calls: [all rounds]}followed by everytoolmessage.Provider::Anthropic::MessageFormatter#buildemits one assistanttool_useturn with every
round's blocks, followed by one usertool_resultturn.
So from the third call of a turn on, each request rewrites the previous one instead of extending it:
call 2: system, user, assistant{tool_calls: [A]}, tool(A)
call 3: system, user, assistant{tool_calls: [A, B]}, tool(A), tool(B) <- diverges after round 1's call
The prompt diverges right after round 1's tool call, so any prefix cache (llama.cpp slot cache,
vLLM prefix caching, hosted prompt caching) has to re-process everything after it on every round.
The model also sees sequential, dependent calls presented as one parallel batch.
Change
Responder#respondtags each in-flight result with the round that produced it
(result.merge(round: iteration)). The Responses-endpoint path still receives only the current
round's untagged results, as before.build_generic_messagesandMessageFormatter#buildgroup consecutive results by:round
(chunk_while) and emit one tool-call message plus that round's results per round, in order:
call 3: system, user, assistant{tool_calls: [A]}, tool(A), assistant{tool_calls: [B]}, tool(B)
Results without a :round key form a single group, so single-round turns and any caller passing
plain results get exactly the payload they got before. The :round key is only read for grouping
and is never sent to the provider. #3727's conventions are unchanged (function.arguments stays a
JSON string via ToolCall::Function.serialize_arguments, no name on tool messages, content: ""
on the assistant message), and #3979's extra_content stays on its own call within its round.
I went with a tag on each result rather than passing an array of rounds because it keeps
function_results a flat array for every provider and the Responses path. Happy to switch to an
explicit [[round 1 results], [round 2 results]] shape if you prefer.
Validation
Tests:
test/models/assistant_test.rb: the existing multi-round test now also asserts that each
follow-up call'sfunction_resultscarry rounds[],[1],[1, 2, 2].test/models/provider/openai_test.rb: new test that builds the round-2 and round-3 requests and
asserts the round-3messagesstart with exactly the round-2messages(append-only), that
each round gets its own assistant/tool pair (round 2 has two parallel calls), that
extra_contentstays on the right call, and that noroundkey reaches the payload.test/models/provider/anthropic/message_formatter_test.rb: the same append-only and per-round
pairing checks in Anthropic'stool_use/tool_resultshape.
Locally I ran ruby -c and rubocop (the lockfile's versions) on the touched files, with no
offenses. I couldn't run the full Rails suite locally, so I'm relying on CI for that.
On a self-hosted instance (llama.cpp llama-server, CPU-only, Qwen3.6-based model, custom
provider with the Responses endpoint off), the same logic was applied as a local patch to
v0.7.5-hotfix.2. One chat turn with two tool rounds plus the final answer, read from sure's usage
logs and llama.cpp's prompt eval time:
| call | prompt tokens | re-processed | reused |
|---|---|---|---|
| 1 | 14,743 | 14,743 (cold) | 0 |
| 2 | 24,544 | 9,805 | 14,739 |
| 3 | 34,357 | 9,715 | 24,642 |
Call 3 now re-processes only its new tool result: it reuses all 24,642 tokens of call 2's prompt
plus its output. Before the fix, the equivalent call reused only ~14.7k and re-processed ~19.6k
(numbers in #4121), which took 8-9 minutes at ~40 tok/s on this host and was the main cause of chat
timeouts.
A correction to the issue: it says reuse stopped at the end of the first user message. Tracing it
further with llama.cpp's debug logging showed the prompt actually diverges just after round 1's tool
call, as described above. The models I measured (Qwen3.6-35B-A3B and two fine-tunes of it, not three
unrelated models) are hybrids with recurrent layers. llama.cpp can't trim their cache to an
arbitrary token, so it rolls back to its last checkpoint, at the end of the first prompt. On a
pure-attention model, reuse would extend through round 1's tool call, but everything from round 1's
results onward would still be re-processed on every call.
Follow-up (not in this PR)
Part 2 of #4121: when a finished multi-round turn is replayed as history,
Responder#openai_messages_payload (and MessageFormatter#assistant_history_blocks for Anthropic)
still emits one assistant message with the final answer and every tool call, followed by all
results. That merges the rounds again and puts the answer before the results it was based on.
Fixing that needs each persisted ToolCall to know its round, and none of the existing
tool_calls columns can hold that without a migration: provider_id and provider_call_id are
per-call ids on every parser, extra_content is copied verbatim onto outgoing tool calls (so a
round stored there would leak to the provider), and calls are inserted row by row, so
created_at doesn't mark round boundaries. A nullable column (round index or the provider
response id) would do; existing rows without it would replay as one group, as they do today.
This change was written with Claude Code (Claude Opus 5.5). I tested it on my own instance as
described above.
š¤ Generated with Claude Code
https://claude.ai/code/session_01AHxryC6omNqVuGdqahKJ8U
Summary by CodeRabbit
- Bug Fixes
- Multi-step tool interactions now preserve each round of tool calls and results when continuing a conversation, helping providers process results in the correct order and match them to the corresponding calls.
- Follow-up requests retain earlier tool interactions as separate exchanges, so later rounds can be processed without combining results from different rounds. Internal round details are not included in provider requests.