Repository navigation
Studio: keep the prompt cache across long tool chats and follow-up turns - #13456
Conversation
On hybrid GGUF models (Qwen3.5/3.6/3.8) llama-server can only reuse its cache up to a context checkpoint before the first token where a new prompt differs from what it already processed. Four places made the follow-up prompt differ from what the model saw: - The final answer pass after the tool budget sent no tools, so the system prompt changed and the whole conversation was re-processed. It now sends the same catalogue with tool_choice none. - Failed tool results carried TOOL_ERROR_NUDGE for the model but were replayed bare. Replayed tool messages now get it back, idempotently. - Feedback folded into a result after tool_end (the budget notice) was never replayed. The loop now reports it as a tool_model_note event; the frontend keeps it on the card provenance and sends it back in extra_content, without showing it. - The GGUF loop never set round_id, so a parallel batch replayed as separate assistant/tool pairs. It now tags decisions like the safetensors loop does.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
- Re-append the error nudge and folded feedback before any frontend envelope, so a replayed image result still parses and its base64 never reaches the prompt as text. - Seed the GGUF and safetensors branch snapshots from the restored conversation; both are matched by identity, so the unrestored copies read as evicted and duplicated. - Keep tool_model_note on recovered cards after a reload, and off provider streams. - Count tokens on the restored history, as the completion path sends it.
A history with no reasoning in it has nothing for preserve_thinking=false to drop except the empty think block each earlier answer was generated behind, so every follow-up of a thinking-off chat diverged from llama-server's cache at the previous answer and a hybrid model re-processed it. Send preserve_thinking=true for such a history, only where the loaded template's own /apply-template render shows that this reproduces the generated prompt exactly; any reasoning in the history keeps the user's setting.
…it everywhere - Only a thinking-off request with at least one earlier answer and no reasoning, inline or in reasoning_content, gets preserve_thinking=true; a thinking-on run keeps the setting. - Admission and /count-tokens resolve the same flag generation renders with. - The count route restores replayed results off the event loop. - A model note delivered twice by a reconnect is kept once.
search_knowledge_base and search_conversation append a __RAG_SOURCES__ map for the card's citations. The live loop strips it before the model sees the result, but the client replays the raw result, so every later turn showed the model a JSON map that repeats each chunk and diverged from llama-server's cache at that result. Strip it on replay too, for those tools only.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6a4a3ed27d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # `in`: restored output may carry feedback after the nudge. | ||
| nudge = ( | ||
| TOOL_ERROR_NUDGE if is_tool_error(content) and TOOL_ERROR_NUDGE not in content else "" | ||
| ) |
There was a problem hiding this comment.
Restrict replay restoration to Studio-owned tool results
For an OpenAI-compatible caller that explicitly enables the Studio tool loop while carrying its own earlier tool history, every result beginning with strings such as Error: or Exit code is treated as if it came from Studio and silently gains TOOL_ERROR_NUDGE. That result was never shown to the model with this suffix, so this changes the caller's supplied conversation and can spur an unintended retry. Gate this restoration on Studio-owned history/provenance rather than applying it to every role-tool message.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Restoration only runs where Studio's own loop or Studio-owned history is in play. Client tool history without the studio_tool_history marker is routed to the llama-server passthrough, which forwards it verbatim (the count route skips restoration there too). The remaining case is a caller that explicitly opts into the Studio tool loop with enable_tools while carrying foreign tool results; under that loop every failed result is sent with the same nudge, so replaying it consistently is the intended behaviour.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6e70605851
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # `in`: restored output may carry feedback after the nudge. | ||
| nudge = ( | ||
| TOOL_ERROR_NUDGE if is_tool_error(content) and TOOL_ERROR_NUDGE not in content else "" | ||
| ) |
There was a problem hiding this comment.
Distinguish raw nudge text from restored feedback
When a failed tool's raw output already contains the exact TOOL_ERROR_NUDGE text—for example, a terminal command prints source or a failure log containing that message—the live ToolCallCompletion.model_message() still appends another copy unconditionally, but this substring check appends none during replay. The model therefore originally saw two copies while the next turn contains only the tool-produced copy, defeating the exact replay and prompt-cache guarantee for that result; idempotency needs provenance rather than treating any occurrence in raw output as proof that restoration already ran.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this. It needs a failed tool whose own output already contains the exact nudge sentence, which only happens when a command prints Studio's source; the cost there is one cache miss on that turn, not a wrong answer.
…model notes on arrival
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Long tool-using chats on hybrid GGUF models (Qwen3.5 / 3.6 / 3.8, Gated DeltaNet) were slow to start every follow-up. After a large agentic turn, "Show me the HTML inline here" or "What is 2+2?" could sit for a minute or more before the first token.
Why
llama-server reuses its cache only up to the first token where the new prompt differs from what it already processed. A hybrid model cannot rewind its recurrent state to an arbitrary position, so it has to restore a context checkpoint from before that token, and checkpoints are only taken while a prompt is processed. A small difference early in the history therefore means re-processing everything after it.
Studio sent the model something different from what the next request replays in four places:
tools. Qwen templates render the tool catalogue at the top of the system prompt, so this prompt shared about 41 tokens with the cache. llama-server picked an empty slot and re-processed the whole conversation, and that state was useless for the next turn, which has tools again.ToolCallCompletion.model_messageappendsTOOL_ERROR_NUDGEto a failed result, but the frontend stores and replays the baretool_endresult. The next turn diverged at the first failed tool call ("Exit code 1", "Error: ..."), which in a "write and fix the bugs" task is usually early.tool_end. The budget notice (and deferred no-op notices) are appended to the last tool message after its card closed, so they were never replayed either.round_idin the tool provenance (the safetensors loop does), so the frontend replayed a two-call batch as two separate assistant/tool pairs instead of one assistant message with both calls.<think></think>block, but withpreserve_thinking=false(the default for Qwen3.6, and for Qwen3.8 when the toggle is off) the template drops that block from earlier answers. Every follow-up then diverged at the previous answer and re-processed it, so a long answer (code, a story) was read again on every turn.search_knowledge_baseandsearch_conversation(the recall tool a compacted chat uses) append a__RAG_SOURCES__citation map. The loop strips it before the model sees the result, but the client replays the raw result, so every later turn showed the model a JSON map that repeats each chunk and diverged from the cache at that result.Changes
llama_cpp.py: the final pass sends the same tool catalogue the last tool round rendered, withtool_choice: "none". The bundled llama.cpp renders tools regardless oftool_choice, and withnoneit installs no tool grammar and parses no calls, so nothing new can execute. Every token count and refit on the final pass now prices the same catalogue it sends.tool_loop_controller.py:restore_replayed_tool_resultsrebuilds replayedrole="tool"messages as the model saw them: it re-appendsTOOL_ERROR_NUDGEto failed results and re-appends any folded feedback that comes back inextra_content.studio_model_suffix. It is idempotent and applied in_openai_messages_for_gguf_chatand at the start of the GGUF, safetensors and external tool loops.llama_cpp.py/routes/inference.py: when feedback is folded into a result after itstool_end, the loop emits atool_model_noteevent with the card id and the exact suffix. The GGUF route forwards it liketool_output.Frontend:
tool_model_noteis stored on the card's provenance and sent back asextra_contenton that tool result. Nothing about the card is rendered differently.llama_cpp.py: GGUF tool decisions carryround_id, the same as the safetensors loop, so a parallel batch replays as one assistant message.Restored text goes before any frontend envelope (image / file / UI), the same place the live loop puts it, so a replayed image result still parses. The GGUF and safetensors branch snapshots are seeded from the restored list, since both are matched by identity.
/count-tokenscounts the restored history. A reload or reconnect during a run keeps the note on the recovered card, andtool_model_noteis stripped from provider streams like the other control frames.llama_cpp.py: a thinking-off request whose history has at least one answer and no reasoning (inreasoning_contentor inline) is rendered withpreserve_thinking=true, which only keeps the empty think block each answer was generated behind. It applies only when the loaded template's own/apply-templaterender proves this reproduces the generated prompt exactly (probed once per server); any other template, any thinking-on request and any history with real reasoning keeps the user's setting. Admission and/count-tokensprice the same flag.tool_loop_controller.py: replayedsearch_knowledge_base/search_conversationresults drop the__RAG_SOURCES__map the same way the live loop does. Other tools are untouched.studio_tool_loop.py: the external provider loop handssearch_conversationthe restored history as its branch, as the GGUF and safetensors loops do, so an archived turn carrying a restored nudge is not mistaken for an abandoned sibling.routes/inference.py:/v1/messages/count_tokensresolvespreserve_thinkingthe same way generation does, so that count matches the prompt/v1/messagesrenders.Frontend: a
tool_model_noteis published as soon as it is applied, so stopping the run before the next chunk still saves it on the card.Older chats without the new provenance replay exactly as before, except that failed results now get the nudge back, which is what the model saw when they ran.
Measured
Colab RTX PRO 6000,
unsloth/Qwen3.8-27B-GGUFUD-Q4_K_XL, the default launch (--parallel 4 --kv-unified --ctx-checkpoints 15, MTP draft). Chat settings: Search + Code, Thinking Extra High, Preserve thinking, Run automatically, no seed. Prompts sent through the real chat UI: "Create a Flappy Bird game in HTML then Rust then Python and fix bugs in them", "Show me the HTML inline here", "What is 2+2?". Numbers come from llama-server's own per-request log, withLLAMA_SERVER_SLOTS_DEBUG=1to print the tokens at each mismatch.rustcresult missing its nudge (token 31,639)Both runs are sampled, so the turns differ in length (about 51K and 50K tokens of context at turn 2).
The final pass in isolation, on a bare llama-server (the bundled build, Studio's chat flags, same budget-exhausted conversation, primed with the last tool round, 6 samples each, up to 10,000 tokens):
tool_choice: "none"(after)A second run with 8 samples each, up to 3,000 tokens, gave the same picture (895 vs 194 tokens, 0 / 8 tool markup on both sides).
Multi-turn chats through the real UI
Local B200, the same
unsloth/Qwen3.8-27B-GGUFUD-Q4_K_XL, Studio's default launch, every turn sent through the chat UI with "Run automatically". Base is the merge base, head is this branch, same bundled llama.cpp. Tokens re-processed is the sum over every llama-server request of the chat, from its own per-request log; avoidable is what was re-processed beyond the tokens that were genuinely new. Verifiable answers are the turns with a checkable answer (sums, counts, the exception name,17*23, the robot's name after compaction).max_seq_length2048, so the chat compacts at turn 4, 2 runs eachSeveral compactions in one chat
Colab RTX PRO 6000, same model, base and head side by side on one VM, every turn through the UI. Chats of 10 to 16 turns at
max_seq_length2048 (4096 for the tool chat), so they compact four to eleven times. "Clean" turns re-processed only their new tokens.On head, every turn that did not compact re-processed only its new tokens, apart from one tokenization drift inside a long story answer. A turn that compacts re-processes the compacted prompt, since the carried-forward instructions in the system prompt change. Two more re-reads remain, both the same on base: the turn after the first compaction (
search_conversationjoins the catalogue), and the turn after a compaction whose forced recall was injected as a tool call, which the client does not replay. With preserve thinking off and thinking on, every turn still drops the previous reasoning by design. At 2048 the window is small enough that most story turns compact, which is why the totals stay high on both sides.The final-answer pass was also checked for accuracy on its own (bare llama-server, three budget-exhausted conversations whose tool results hold the answer, 6 samples each): correct 18/18 without tools and 18/18 with the catalogue and
tool_choice: "none", no tool markup on either side, and 116 to 161 tokens re-processed instead of 227 to 357.Not covered here
search_conversationjoins the catalogue once the thread has an archive. After that, turns reuse the cache again (measured above). Offering the tool on the reset turn itself changes what the model is shown there, so it is left as is." " + " for"where the tokenizer, reading the same text back, produces one" for"token. The text is identical, but a hybrid model can only roll back to the checkpoint at the start of the generation. That needs a llama-server change (for example checkpoints during generation or text-level prefix matching) and is left for a follow-up.Tests
tests/test_tool_error_nudge_replay.py: a failed result round-trips throughtool_endand replay into exactly whatmodel_messagesent; idempotency; folded suffix ordering andextra_contentcleanup; restored text lands before an image envelope; a provider cannot sendtool_model_note; a replayed retrieval result equals whatstrip_result_for_modelgave the model, and other tools keep the marker text.tests/test_llama_cpp_tool_loop.py: the final pass keeps the catalogue withtool_choice: "none"; a replayed failed result carries the nudge in the payload; a parallel batch shares oneround_id; the budget notice is reported astool_model_noteand restores to the exact content the final pass sent. A tool is handed the replayed failed result once on the live branch, not twice. Five existing tests that asserted a tool-less final pass now asserttool_choice: "none".tests/test_preserve_thinking_replay.py: the flag flips only for a thinking-off follow-up whose history has no reasoning (structured or inline); the probe reads the template's own render once, refuses a template that renders alike either way, and keeps the setting when llama-server cannot answer.tests/test_studio_tool_loop.py: the provider loop's searched branch carries the restored failed result.tests/test_anthropic_messages.py: the/v1/messages/count_tokensroute prices the resolvedpreserve_thinking. Both fail without their fix.frontend/tests/tool-model-suffix.test.ts: note targeting with reusedcall_0ids, suffix accumulation (a note delivered twice is kept once),extra_contentonly when noted, and the adapter yields as soon as a note lands.generation-tool-recovery.test.ts: a recovered run keeps the note on its card.test_chat_generation_supervisor.py, fail the same way on main). Frontend:npm run typecheckand the fullnpm test(11,767 tests) pass. After the second commit, 26 affected backend test files: failing test IDs identical on base and head (16 each, all pre-existing). For the thinking-off change, the 26 reasoning, template and passthrough test files pass in full with and without it (2,925 each), and the admission and count-tokens files fail the same 3 pre-existing tests on base and head. For the source-map change, 14 replay, recall, citation and RAG retrieval test files fail the same pre-existing test with and without it (561 passed with it, the new test included).