Skip to content

fix(llm): send thinking blocks back with their tool turn on the Claude provider - #5072

Merged
kovtcharov-amd merged 10 commits into
mainfrom
fix/claude-preserve-thinking
Oct 26, 2026
Merged

kovtcharov-amd merged 10 commits into
mainfrom
fix/claude-preserve-thinking

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

With thinking enabled, a Claude tool loop in GAIA re-derived its plan on every call. The provider threw away each turn's thinking blocks, so the model never saw its own earlier reasoning and spent output tokens and time working it out again. Now each tool turn goes back exactly as Claude produced it. Thinking is left out only when the earlier conversation has changed, because Anthropic rejects a stale thinking block.

Stacked on #5071. Merge that one first.

This changes what the model sees, but only on the Claude provider. The default local-model flagship eval doesn't exercise it, so the eval that matters is a Claude-backed run.

Test plan

  • python -m pytest tests/unit/test_claude_provider.py: covers thinking captured on create and stream with signatures, re-sent on the matching tool turn, redacted_thinking round-trip, interleaved order, unsigned blocks not replayed, and edited history, a changed tool set or a changed system prompt never sending stale blocks
  • python util/lint.py --all
  • Run a Claude-backed gaia eval agent and compare it with the same run on main: output tokens per call should drop, with no new failures
  • With a real ANTHROPIC_API_KEY, a two-step tool loop with thinking on is accepted, with no 400

Every call to Claude re-billed the whole conversation as fresh input, so
an agent loop paid full price for its growing history on each step. Only
the tool schemas and system prompt were cached. Now each call caches its
history and the next call reads it back.

- A rolling cache_control breakpoint goes on the last block of the newest
  message that can carry one. String content becomes one text block;
  thinking blocks and empty text are skipped, and nothing is marked when
  no block qualifies. tool_result blocks can carry it.
- _build_params is shared by the create and stream paths, so both get it.
- The caller's messages are copied, never edited, so markers can't pile
  up across calls.
- A request over Anthropic's limit of 4 breakpoints fails with an
  actionable ValueError. The provider places at most 3 itself.
- The live integration test confirms call 2 reads call 1's history from
  cache. It skips without a real ANTHROPIC_API_KEY and is listed in the
  lane allowlist, since no test lane carries a billed key.
…e provider

With thinking enabled, a Claude tool loop re-derived its plan on every
call. The provider dropped each turn's thinking blocks and signatures,
and the agent's history keeps only text and tool calls, so the model
never saw its own earlier reasoning. Now each tool turn goes back exactly
as Claude produced it.

- Each tool turn that carries thinking is kept inside the provider, with
  thinking and redacted_thinking blocks and their signatures unchanged.
  The stream path rebuilds the blocks from thinking_delta and
  signature_delta events. The agent's message format does not change.
- On the next request a kept turn is matched on its tool_use ids and
  re-sent verbatim, interleaved order included.
- Anthropic rejects a thinking block once the system prompt, tools or
  earlier messages change. The provider applies the same check: it digests
  everything sent before the turn (cache markers excluded) and re-sends
  the blocks only when that digest and the turn's text and tool calls are
  unchanged. Otherwise the turn goes back as it is now, without the stale
  blocks, and a debug log says why. One edit voids every later turn, as
  the API does.
- Thinking blocks are left out of the digest, because the API chains each
  block to the one before it. Dropping the oldest turns' thinking first
  therefore stays valid, so a bounded store of 256 turns sheds its oldest
  without voiding the rest.
- Unsigned blocks (a cut-off stream) and turns holding other block types
  are not kept. Thinking blocks never take the rolling cache breakpoint.
@github-actions github-actions Bot added llm LLM backend changes tests Test changes performance Performance-critical changes labels Oct 13, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

Holding this one. Replaying thinking for tool turns only, and not for the plain-answer turns between them, leaves a gap in the thinking chain. Claude Opus 5.5, Sonnet 5.5 and Fable 5.1 reject that gap with a 400, so the second question in any conversation would fail on those models, and today it works. It is also stacked on #5071, so it can't land on main until that one merges.

Next step: only replay the newest unbroken run of kept turns (sketch below), add a test for a conversation with two questions, then retarget to main once #5071 is in.

🔍 Technical details
  • The gap. _remember_turn keeps only tool turns. A final answer's thinking (adaptive thinking is on by default on claude-sonnet-5 and later) is never stored, so the history ask → T1(tool) → A1(answer) → ask → T2(tool) goes out as thinking [sig-T1], [], [sig-T2]. I reproduced this against the PR head with the test helpers. The kept blocks must be a contiguous window of the original sequence (dropping from the front or back is fine, dropping from the middle is not). The models that run the preserved-thinking check fail the block after the gap (predecessor_missing). On main nothing is replayed, so nothing breaks. The same gap opens when a turn in the middle isn't stored (an unsigned stream, an unreplayable block, or invalid streamed JSON).
  • Possible fix. In _replay_thinking, walk the assistant turns from newest to oldest. Restore while _with_original_blocks succeeds, and stop at the first assistant turn that can't be restored, sending every older turn without its thinking. The current tool loop, which is where the token savings come from, still gets its thinking back, and the history only ever drops from the front.
  • Checked and fine. The request shape matches the contract in every test: thinking, then text, then tool_use, with interleaved order kept and signatures and redacted_thinking.data unchanged. signature_delta is accumulated on the stream path, a turn without thinking is sent as before, cache markers are kept off thinking blocks, and the caller's messages are never mutated. The 101 tests in tests/unit/test_claude_provider.py pass, and black and isort are clean.
  • Eval. On today's default (claude-sonnet-5), dropping thinking is accepted, so this changes what the model sees on a path that already works. That makes it eval-gated in principle, but the flagship eval runs local models and doesn't exercise this provider. Only the Claude-backed run in the test plan would cover it.
  • CI. The pr-review failure is the review bot hitting its weekly quota. It never ran.

Base automatically changed from fix/claude-history-cache to main October 13, 2026 23:44
# Conflicts:
#	src/gaia/llm/providers/claude.py
…de provider

Only tool turns' thinking was stored, so a second question went out with thinking on turns [T1], [], [T2]. Claude Opus 5.5, Sonnet 5.5, Fable 5.1 and Haiku 5.5 reject that gap with a 400, because kept thinking must be an unbroken run of the original sequence.

Any assistant turn whose thinking can't be restored (a final answer, a cut-off stream, an edited turn) now ends the run, and every older turn goes back with only its thinking removed. Once a turn's thinking has been dropped it is never sent again.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

Fixed the thinking gap. A second question in a conversation no longer sends thinking with a hole in the middle, so Opus 5.5, Sonnet 5.5 and Fable 5.1 won't 400 on it. The branch is merged up with main. Still held: this changes what the model sees on the Claude provider, and only a Claude-backed run covers it.

🔍 Technical details
  • Rule followed. The preserved-thinking docs say the kept blocks must be an unbroken run of the original sequence. Dropping from the front, from the back, or all of them is fine. A block that was dropped must stay dropped.
  • Fix. _replay_thinking now walks the assistant turns from newest to oldest. Any turn whose thinking can't be restored ends the run: a final answer, a cut-off or unsigned stream, invalid streamed JSON, or an edited turn. Older turns go back with only their thinking blocks removed, so their other blocks stay byte-identical to earlier requests. A turn left out never comes back, because the turn that broke the run stays unrestorable. Thinking the caller supplied is left alone.
  • Merge. No real conflict. main's claude.py was identical to this PR's fix(llm): cache the conversation history on the Claude provider #5071 base commit, so the PR side was taken as is.
  • Caching. The rolling marker still lands on the last non-thinking block, and no thinking block ever carries cache_control. A three-turn loop with every turn's thinking replayed carries exactly 3 breakpoints.
  • Tests. New tests check the outgoing request for four cases: a gap in the middle ([], [], [T2]), a dropped turn that is never put back, a cut-off stream turn, and an all-tool-turn loop (create and stream). With thinking off, the request matches one from a provider with no replay store. The three gap tests fail on the previous head. tests/unit/test_claude_provider.py passes (107), and black and isort are clean.
  • Open. A tool turn that Claude answered with no thinking also ends the run. That is valid but conservative. The live tests/integration/test_claude_history_cache.py wasn't run because no real key was available.

@kovtcharov-amd kovtcharov-amd added the ready_for_ci Run CI workflows on draft PR without requesting review label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

On the Claude provider, a tool turn now goes back to the API with the thinking Claude produced for it, so a tool loop with thinking on no longer works out its plan again on every call. Replay is careful: anything the API might reject is left out, never sent. That covers an edited turn, a changed system prompt, tool set or earlier message, a gap in the run of turns, and a stream cut off before its signature arrived. If a check misses, the cost is a lost optimisation, not a 400. Nothing blocks the merge. One small hardening is suggested below.

The real test for this change is the Claude-backed eval and live-API items in the test plan. Mocked unit tests can't show that Anthropic accepts the replayed blocks, so tick those two items before merging.

Real-world evidence

N/A: no CLI, API or MCP surface changed; this is internal to the Claude provider. The verdict rests on static review and the PR's unit tests, which pass in CI. Real Claude acceptance (no 400 on a two-step thinking loop) is still unverified.

🔍 Technical details

Issues

🟢 The replay check doesn't include the model (src/gaia/llm/providers/claude.py, _replay_thinking). The prefix digest covers only the system prompt and tools. If a caller switches model partway through a loop, thinking signed by one model goes back on a request to another. I haven't confirmed whether Anthropic rejects that. Adding the model to the digest is cheap insurance, and it matches the PR's rule of leaving thinking out when unsure. It means passing the resolved model into _replay_thinking:

        digest = hashlib.sha256(
            _canonical({"model": model, "system": system, "tools": tools})
        )

🟢 Losing an earlier turn's stored blocks can unnecessarily drop a later turn's thinking. The digest folds in each restored turn as Claude produced it, including sanitized tool names and blocks in their original order. Suppose the store evicts T1, or T1 stops matching. T1 then goes into the digest as GAIA rebuilds it from history, with GAIA tool names and text before calls. Whenever those two forms differ (interleaved text, or MCP-style names with .), T2's stored prefix no longer matches, and T2's thinking is dropped even though the API would accept it. The failure is safe, so this is optional. A comment noting it would help whoever later wonders why an eval run shows fewer replays.

Strengths

  • The safety direction is right throughout. Every failed check falls back to sending the turn as before, with a debug log naming the reason, and thinking is stripped without altering the rest of the turn. That keeps the rolling cache prefix byte-stable.
  • Gaps are handled correctly: the newest unbroken run of turns keeps its thinking, and older turns are stripped. test_a_dropped_turn_is_never_put_back pins the case most likely to regress.
  • The tests are thorough and realistic. They cover streaming with signature_delta, redacted thinking, interleaved order, five ways history can be edited, eviction, and a thinking-off run that is byte-identical to a provider with no replay. They also check that the caller's message list is never mutated.

Switching model partway through a Claude tool loop sent thinking signed by
one model on a request to another. The replay digest now includes the
resolved model, so such a turn goes back without its thinking. A non-Claude
model id that resolves to the same Claude model is not a switch.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

Both review suggestions are in: thinking is now tied to the model that produced it, so switching models mid-loop never sends one model's thinking to another. The branch is current with main, CI is green, and the provider tests pass locally (110). Two test-plan items are still open before merge: the Claude-backed eval and a live two-step thinking loop with a real key.

🔍 Technical details
  • Model in the digest: _replay_thinking seeds it with {"model", "system", "tools"}. Tests: test_a_switched_model_does_not_send_another_models_thinking and test_the_same_resolved_model_still_sends_thinking.
  • Eviction losing a later turn's thinking: noted in the _replay_thinking docstring. It is the safe direction, losing only the optimisation.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 26, 2026
Merged via the queue into main with commit afd6941 Oct 26, 2026
42 of 43 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/claude-preserve-thinking branch October 26, 2026 09:54
@kovtcharov-amd kovtcharov-amd mentioned this pull request Oct 26, 2026
5 of 9 tasks
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 26, 2026
## Why this matters

v0.25.2 is a bug-fix release on top of v0.25.1: setup and install no
longer stop at the first failed step, shell and file access handle
Windows paths and text encodings, the Agent UI and desktop app stop
showing misleading states, and document search, email and skills each
lose a handful of rough edges. 55 commits since v0.25.1; notes are in
`docs/releases/v0.25.2.mdx` and credit 15 outside contributors.

## Test plan

- [x] `python util/validate_release_notes.py docs/releases/v0.25.2.mdx
--tag v0.25.2` passes
- [x] `mintlify validate` (from `docs/`) passes
- [x] `python util/check_doc_links.py --internal-only`, `python
util/check_doc_versions.py` and `node
installer/version/bump-ui-version.mjs --check` pass
- [x] `python util/check_component_core_api.py --release-version 0.25.2`
passes
- [x] `pytest tests/unit/test_docs_json_release.py
tests/unit/test_check_component_core_api.py
tests/unit/test_release_tag.py
tests/unit/test_hub_core_version_gate.py`: 156 passed
- [ ] CI green on the merge commit
- [ ] `release_train_dryrun.yml` passes on that commit before the RC tag

## Evals to re-run on the RC tag

LLM-affecting PRs merged without per-PR evals; run these on
`v0.25.2-rc1`:

- `gaia_shell` and shell/safety (amd#5794, amd#5751, amd#5768)
- `gaia_honesty` (amd#5753)
- `gaia_skills_tasks` and `gaia_skills_lifecycle` (amd#5422, amd#5755)
- `rag_retrieval` and `rag_quality` (amd#5742, amd#5754, amd#5761, amd#5817, amd#5812)
- email scenarios (amd#5767, amd#5811)
- `tool_selection` and `error_recovery` (amd#5732)
- Claude provider thinking replay (amd#5072)
- memory categories (amd#5818 merged; amd#5756 has not)

## Release checklist

- [ ] Freeze main, wait for green CI on the exact commit, pass
`release_train_dryrun.yml`, then push `v0.25.2-rc1`
- [ ] Extend the changelog if main gains commits before the tag
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm LLM backend changes performance Performance-critical changes ready_for_ci Run CI workflows on draft PR without requesting review tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant