Skip to content

Studio: keep the prompt cache across long tool chats and follow-up turns - #13456

Merged
danielhanchen merged 10 commits into
mainfrom
studio-prompt-cache-followups
Oct 13, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
studio-prompt-cache-followups

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

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:

  1. Final answer pass after the tool budget. When the 25-call budget runs out, the final pass sent no 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.
  2. Failed tool results. ToolCallCompletion.model_message appends TOOL_ERROR_NUDGE to a failed result, but the frontend stores and replays the bare tool_end result. 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.
  3. Feedback folded into a result after 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.
  4. Parallel tool calls. The GGUF loop never set round_id in 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.
  5. Thinking-off chats. With thinking off, each answer is generated behind an empty <think></think> block, but with preserve_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.
  6. Retrieval results. search_knowledge_base and search_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, with tool_choice: "none". The bundled llama.cpp renders tools regardless of tool_choice, and with none it 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_results rebuilds replayed role="tool" messages as the model saw them: it re-appends TOOL_ERROR_NUDGE to failed results and re-appends any folded feedback that comes back in extra_content.studio_model_suffix. It is idempotent and applied in _openai_messages_for_gguf_chat and 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 its tool_end, the loop emits a tool_model_note event with the card id and the exact suffix. The GGUF route forwards it like tool_output.

  • Frontend: tool_model_note is stored on the card's provenance and sent back as extra_content on that tool result. Nothing about the card is rendered differently.

  • llama_cpp.py: GGUF tool decisions carry round_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-tokens counts the restored history. A reload or reconnect during a run keeps the note on the recovered card, and tool_model_note is 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 (in reasoning_content or inline) is rendered with preserve_thinking=true, which only keeps the empty think block each answer was generated behind. It applies only when the loaded template's own /apply-template render 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-tokens price the same flag.

  • tool_loop_controller.py: replayed search_knowledge_base / search_conversation results drop the __RAG_SOURCES__ map the same way the live loop does. Other tools are untouched.

  • studio_tool_loop.py: the external provider loop hands search_conversation the 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_tokens resolves preserve_thinking the same way generation does, so that count matches the prompt /v1/messages renders.

  • Frontend: a tool_model_note is 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-GGUF UD-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, with LLAMA_SERVER_SLOTS_DEBUG=1 to print the tokens at each mismatch.

Request Before: tokens re-processed After: tokens re-processed
Final answer after the tool budget 47,998 of 47,998 (15.2 s, new slot) 98 of 23,683 (0.18 s, same slot)
Turn 2, first request: first mismatching token a failed rustc result missing its nudge (token 31,639) none in the replayed history: 11 failed results, the budget notice and a two-call batch all matched
Turn 3 19 19

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):

Final pass Prompt tokens processed (median) Reused from cache Prompt time (median) Tool markup in the answer Tool calls returned
Without tools (before) 895 0 510 ms 0 / 6 0 / 6
Same tools, tool_choice: "none" (after) 194 1,784 255 ms 0 / 6 0 / 6

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-GGUF UD-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).

Chat (turns) Base: re-processed / avoidable Head: re-processed / avoidable Verifiable answers base / head
Search + Code, thinking on, preserve thinking on (5, includes two failed tool calls), 2 runs each 2,598 / 1,046 1,886 / 600 (one run 4, the other hit the reasoning-only retry noted below) 10/10 / 10/10
Search + Code, thinking off (5), 2 runs each 3,048 / 1,772 1,328 / 2 10/10 / 10/10
Plain chat, thinking off (8: four 300-word story parts, then four short questions), 2 runs each 2,458 / 2,004 229 / 2 8/8 / 8/8
Same 8 turns at max_seq_length 2048, so the chat compacts at turn 4, 2 runs each 3,816 2,752 8/8 / 8/8
Search + Code, thinking on, preserve thinking off (5), 2 runs each 2,947 / 2,260 2,168 / 1,760 10/10 / 10/10

Several 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_length 2048 (4096 for the tool chat), so they compact four to eleven times. "Clean" turns re-processed only their new tokens.

Chat Base: re-processed / clean turns / answers Head: re-processed / clean turns / answers
Thinking off, 16 turns (300-word story parts plus checkable questions), run 1 8,082 / 2 of 16 / 6/6 6,711 / 8 of 16 / 6/6
Same, run 2 9,230 / 1 of 16 / 5/6 5,655 / 9 of 16 / 6/6
Thinking on, preserve on, 14 turns 4,227 / 6 of 14 / 5/5 3,657 / 8 of 14 / 5/5
Thinking on, preserve off, 14 turns 4,484 / 0 of 14 / 5/5 4,002 / 0 of 14 / 5/5
Python tools, thinking off, 10 turns at 4096 14,809 / 1 of 10 / 10/10 14,152 / 3 of 10 / 10/10

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_conversation joins 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

  • With thinking on and preserve thinking off, each follow-up still re-processes the previous turn: the template drops that turn's reasoning by design, which is what the setting asks for.
  • A compaction reset re-processes the compacted prompt (measured above for several compactions per chat), and so does the next turn, because search_conversation joins 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.
  • In the "after" run, turn 2 still re-processed the previous answer (27K generated tokens of code, 9.7 s). The only mismatch was a tokenization difference inside that generated text: the model sampled " " + " 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.
  • The safetensors loop folds the budget notice into the last result directly, and the external provider loop appends it as a user turn. Neither reports it for replay yet; the local llama-server path is where the cache cost shows up.

Tests

  • tests/test_tool_error_nudge_replay.py: a failed result round-trips through tool_end and replay into exactly what model_message sent; idempotency; folded suffix ordering and extra_content cleanup; restored text lands before an image envelope; a provider cannot send tool_model_note; a replayed retrieval result equals what strip_result_for_model gave the model, and other tools keep the marker text.
  • tests/test_llama_cpp_tool_loop.py: the final pass keeps the catalogue with tool_choice: "none"; a replayed failed result carries the nudge in the payload; a parallel batch shares one round_id; the budget notice is reported as tool_model_note and 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 assert tool_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_tokens route prices the resolved preserve_thinking. Both fail without their fix.
  • frontend/tests/tool-model-suffix.test.ts: note targeting with reused call_0 ids, suffix accumulation (a note delivered twice is kept once), extra_content only 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.
  • Backend: ran the 66 test files touching the tool loops on base and head; the failing test IDs are identical apart from the five updated tests, which pass now (the shared failures, mostly test_chat_generation_supervisor.py, fail the same way on main). Frontend: npm run typecheck and the full npm 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).

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-13T12:47:36.077792Z 8e1d6d9 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen self-assigned this Oct 12, 2026
pre-commit-ci Bot and others added 2 commits October 12, 2026 17:52
- 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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +883 to +886
# `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 ""
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +883 to +886
# `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 ""
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: a1727d5049

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@danielhanchen
danielhanchen merged commit fd30659 into main Oct 13, 2026
@danielhanchen
danielhanchen deleted the studio-prompt-cache-followups branch October 13, 2026 13:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant