Skip to content

fix(chat): stop replaying tool calls to the model as "None" - #3758

Merged
kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:claude/fix-history-tool-calls
Sep 21, 2026
Merged

kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:claude/fix-history-tool-calls

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

On every non-Claude backend (local Lemonade models, and Fireworks through Lemonade), GAIA replayed each tool-call turn to the model as an assistant message saying "None". minimax-m3 copied that, replied "None" on coding tasks, and GAIA handed "None" to the user as the final answer. A None turn is now an empty string. The Claude path, which already sends native tool calls, is unchanged.

An earlier version of this PR replayed each call as [Tool call: name(args)] text instead. That was wrong. The same 144-run benchmark showed models copying the text format instead of calling tools. The parser rejected those calls, and 58 runs ended in "I had trouble formatting my tool call" (0 before). That rendering is removed. The PR is now a two-line guard plus tests that pin both failure modes.

Closes #3757

Test plan

  • pytest tests/unit/test_sdk_history_tool_calls.py: a tool-call turn becomes neither "None" nor imitable text; accompanying text is kept verbatim; tool results still name the tool; the Claude path still sends native calls.
  • pytest tests/unit/test_sdk_tool_messages.py tests/unit/test_claude_provider.py tests/unit/test_turn_metrics_wire.py: 82 pass.
  • Benchmark, first version: literal "None" answers 10 → 0, and tool-call format failures 0 → 58 (the regression this revision removes).
  • Benchmark, this version, on the identical 144-run battery: "None" answers stay at 0, format failures back to 0 (from 58), native tool calls 689 → 1,270, and passing runs 66 → 100.
  • gaia eval agent: required by CLAUDE.md, because this changes what the model is sent.

On every non-Claude backend, the history sent to the model before each
request rewrote each tool-call turn as an assistant message whose content
was the word "None", and dropped the call. _structure_history_message
normalised content with str(), msg.get("content", "") returns None when
the key exists, and only the Claude branch kept tool_calls. The model
never saw which tools it had called or with what arguments.

minimax-m3 copied it: on 2 of 4 coding tasks it replied "None", which
became the final answer. No other model printed it across ~90 runs, but
all of them received the same history.

A tool-call turn is now rendered as "[Tool call: name(args)]", the same
text convention tool results already use, with any text the model sent
alongside it kept. None content becomes an empty string, never "None".
The Claude path is unchanged.

Closes amd#3757

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added chat Chat SDK changes tests Test changes labels Sep 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes — the fix itself is right and well-targeted; two things should land before merge.

Tool-call turns really were reaching every non-Claude backend as an assistant message saying "None", and rendering them as text matches the convention tool results already use. The diff is small, the tests cover the shapes the agent loop actually produces, and the Claude path is left alone.

What needs attention:

  1. Tool arguments now replay in full, with no size limit. A write_file or edit_file call carries its entire payload, and from this PR on that payload is re-sent on every following turn of the conversation. Large tool results are already shrunk to fit the machine's context window before they go into history; tool calls aren't. On a 32K-context NPU box this will push long coding sessions into the context-overflow retry path more often, which recovers by throwing history away — the opposite of what this fix is for. Apply the same size cap the results path uses.

  2. The agent eval hasn't been run. The project requires it for any change to what the model is sent, and the PR marks it unchecked. It matters here beyond box-ticking: on backends that also receive the native tool schema, the model now sees prior calls written out as plain text, and some models imitate the format they see rather than emitting a real tool call. That is exactly the kind of regression unit tests can't catch.

Real-world evidence

No evidence bundle was produced for this PR, and the PR itself lists unit tests only. The behavioral claim — that a real model stops answering "None" — rests on the author's prior benchmark observation, not on anything runnable here, and the A/B re-run is listed as still pending. My verdict is based on static review plus the diff's own tests, which I could not execute in this environment (pytest isn't installed on the runner). The change touches no CLI, REST, or Agent UI surface, so no screenshot or request/response capture is expected.

🔍 Technical details

Issues

🟡 Tool-call arguments bypass the truncation budget (src/gaia/chat/sdk.py:206-215)

_describe_tool_call serializes arguments verbatim. The producing shape is agent.py:4515, where arguments is json.dumps(tc["tool_args"]) — unbounded for write/edit tools. Tool results take a different route: Agent._handle_large_tool_result (agent.py:4206) runs them through _truncation_budget() → truncation_budget(device) (lemonade_client.py:345), which resolves to a conservative 30000/20000 char budget and defaults to the NPU profile precisely to avoid reopening the #1030 overflow class. Before this PR a tool-call turn cost ~1 token ("None"); after it, it costs its full argument JSON on every subsequent request in the loop.

The agent's one-shot overflow-trim retry (agent.py:5557, agent.py:5699) keeps this from hard-failing, but recovering by dropping history undercuts the point of the fix. A module-level cap is enough here since _describe_tool_call has no self:

def _describe_tool_call(tool_call: Dict[str, Any]) -> str:
    """``name(args)`` for either the OpenAI or GAIA-normalised tool-call shape."""
    fn = tool_call.get("function") or {}
    name = fn.get("name") or tool_call.get("name") or "tool"
    args = fn.get("arguments", tool_call.get("tool_args", ""))
    if not isinstance(args, str):
        args = json.dumps(args, default=str)
    # Args replay on every later turn; an unbounded write payload eats the ctx.
    if len(args) > _TOOL_CALL_ARGS_CHARS:
        args = args[:_TOOL_CALL_ARGS_CHARS] + "…[truncated]"
    return f"{name}({args})"

with _TOOL_CALL_ARGS_CHARS = 2000 (or whatever value you prefer) beside it, and a test that a large payload is capped.

🟡 gaia eval agent not run (test plan)

CLAUDE.md → "Run agent evals when changing LLM-affecting code paths — do NOT skip" lists exactly this surface. Worth one run against the coding/tool-use category compared to the committed baseline, since the same request now contains both the native tools schema and a textual [Tool call: …] rendering of prior calls — a plausible source of models emitting the text form instead of a real call.

Nits

🟢 tests/unit/test_sdk_history_tool_calls.py:78 — @pytest.mark.parametrize("content", [None]) over a single value adds indirection without adding a case. Inline it, or add the other falsy-but-not-None inputs ("", [], {}) that the parametrize implies:

def test_none_content_never_becomes_the_word_none():
    assert _sdk(False)._normalize_message_content(None) == ""

🟢 PR description carries the 🤖 Generated with [Claude Code] footer. CLAUDE.md → "No Claude Attribution of Any Kind" prohibits it on PR descriptions; worth stripping before merge.

Strengths

  • The tests assert the shapes the agent loop genuinely emits — the OpenAI envelope from agent.py:4515 with content: None, and the GAIA-normalised name/tool_args form — rather than a shape invented for the test.
  • test_claude_path_still_sends_native_tool_calls pins the branch this fix must not change, which is the regression a future refactor of this function would otherwise cause.
  • Reusing the existing [Tool result: …] text convention for [Tool call: …] keeps one format across both halves of a tool exchange, instead of introducing a second one.

Replaying a tool-call turn as "[Tool call: name(args)]" taught non-Claude
models to write calls in that text format instead of calling tools, so the
parser rejected them and the turn gave up. On the same 144-run battery that
went from 0 to 58 runs ending in "I had trouble formatting my tool call".

The turn is now just its own text (empty when it had none). The None -> ""
guard stays, so the word "None" is still never replayed.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kovtcharov

Copy link
Copy Markdown
Contributor Author

This review was written against the first version, and both concerns are gone in the current one — the first was proven right before it was removed.

The [Tool call: name(args)] rendering is deleted. On the same 144-run benchmark it did exactly what you warned about: models copied the text format instead of making native tool calls, and 58 runs ended in "I had trouble formatting my tool call" (0 before). The PR is now only the guard that turns a None turn into an empty string, so no tool arguments are replayed at all and the size question no longer applies. Measured on the corrected version: "None" answers stay at 0, format failures back to 0, native tool calls 689 → 1,270, and passing runs 66 → 100 of 144.

gaia eval agent cannot run on this machine (no claude CLI for the judge), so the benchmark above is the behavioural evidence; a maintainer with judge access should still run it. The attribution footer stays because this session's instructions require it — a maintainer should settle that conflict.

🔍 Technical details
  • _describe_tool_call and the non-Claude tool_calls branch in _structure_history_message were removed (commit 838667e5); _normalize_message_content(None) returns "".
  • Tests were rewritten to pin both failure modes: a tool-call turn becomes {"role": "assistant", "content": ""} (neither "None" nor imitable text), accompanying text is kept verbatim, tool results still name the tool, and the Claude path still sends native calls. The single-value parametrize nit is gone with that rewrite.
  • 82 tests pass across test_sdk_history_tool_calls.py, test_sdk_tool_messages.py, test_claude_provider.py, test_turn_metrics_wire.py.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

The agent eval gate has now run on this PR, together with the other open agent fixes (#3751, #3755, #3758, #3765, #3791) merged onto one branch: no regressions. Every category passes the same scenarios as the unchanged base commit, and no scenario flipped between pass and fail.

🔍 Technical details

Both legs ran on the same machine with local Gemma-4-E4B-it-GGUF at 65536 ctx and the same judge. Base is 70de0502, where these branches left main; the batch is that commit plus the PRs at their current heads.

Category Base Batch Avg score
tool_selection 4/5 4/5 8.4 → 8.8
rag_quality 7/8 7/8 9.4 → 9.4
context_retention 4/4 4/4 9.6 → 9.6
  • Against the committed baseline gemma-4-e4b-d71cd914: known_path_read goes FAIL → PASS, with no regressions.
  • data_vs_recall_disambiguation fails on both legs. Over three runs each the base averages 5.4 and the batch 5.2, and both sometimes answer from RAG chunks instead of calling analyze_data_file. It is a model miss that predates these changes.
  • csv_analysis is INFRA_ERROR on both legs: the scenario still requests the removed data agent, so no turn reaches the model. Pre-existing and unrelated.

theonlychant pushed a commit to theonlychant/gaia that referenced this pull request Sep 15, 2026
…files (amd#3755)

Ask the flagship to fix a bug, rename a function, or add a feature, and
most of the time it was not handed a tool that can change a file. It
could read the code but not edit it unless the model noticed and fetched
the edit tools itself — and the models that picked the wrong bundle
looped until the loop guard stopped them.

The edit tools were not *missed* by semantic selection; they were
matched and then **ranked out**. The flagship leaves 15 slots for
non-core tools, 46 others compete every turn, and bundle pull-in raises
every member of a bundle to its best member's score, so whole unrelated
cohorts — data tables, RAG indexing, clipboard, code index — landed
above them. On seven explicit edit prompts the edit tools made the
loaded set twice. Scores on these prompts are too close together (edit
tools 0.24–0.38, winners 0.35–0.42) to fix by tuning, so `write_file`
and `edit_file` now join `read_file` in the always-on set.

**Cost, measured the way `test_full_tool_bundles` measures it:** the
always-on floor goes from **3,141 to 3,963 tokens** (19.2% → 24.2% of
the full registry; the guard is 30%). The capped worst case is unchanged
at **5,417 tokens**, because the cap already bounds it. The always-on
block is part of the stable prompt prefix, so providers with prompt
caching bill most of it at the cached rate.

Closes amd#3752

## Test plan

- [x] Selector re-run against this branch — edit tools are in the loaded
set on every edit prompt that previously dropped them (numbers in the
thread).
- [x] `pytest hub/agents/gaia/python/tests/test_full_tool_bundles.py
tests/unit/test_chat_tool_bundles.py
tests/unit/test_chat_dynamic_tools.py
tests/unit/test_tool_loader_disambiguation.py` — full-profile coverage,
cap and token-budget guards pass.
- [x] 6 local failures are pre-existing and unrelated: identical on
`origin/main`, with **byte-identical numbers** with and without this
change — 2 need `search_documentation` (npx), 4 are doc-profile token
pins, and the doc profile is untouched here.
- [ ] `gaia eval agent` — required by CLAUDE.md for tool-registration
changes.
- [x] Benchmark A/B, the same battery before and after: coding tasks
finished with zero file edits in 18/48 runs before and 9/54 after;
`load_tools` calls 165 → 123. The first after-run was confounded by an
unrelated history regression (amd#3758), so these numbers come from the
re-run with that fixed.

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
t and others added 2 commits September 21, 2026 11:12
…ends

Merging main broke three of this PR's tests without touching its fix. amd#3997
replaced the text flattening they were written against: a tool-call turn now
keeps its native tool_calls with `content: None`, and a tool result is a
`role: "tool"` message instead of `[Tool result: …]` user text.

The one-line guard this PR exists for is still load-bearing — a `tool` turn or
a plain turn carrying `content: None` still stringified to the word "None",
which is what a model started echoing back. The tests now pin that case
directly and keep the native-shape assertions that amd#3997 made true.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 21, 2026
Merged via the queue into amd:main with commit 54e4d65 Sep 21, 2026
30 checks passed
github-merge-queue Bot pushed a commit that referenced this pull request Sep 25, 2026
GAIA can now answer follow-ups using prior tool evidence in the TUI,
including after reopening its transcript. Previously the saved
conversation could retain only the final prose, losing facts the tools
had read. Complete turns are archived locally and replayed within a
budget that reserves room for the current prompt, tools, and answer.

Closes #3628. Depends on #3669 (included here); also includes the SDK
null-content normalization from #3758 with original authorship.

<details>
<summary>🔍 Technical details</summary>

The TUI stores its transcript under `GAIA_TUI_HOME/history/`;
`--history-file` or `GAIA_HISTORY_FILE` reopens an explicit transcript.
Whole tool groups stay intact when older turns leave the active window.
Persistence completes before the terminal response, and clearing the
history deletes its archive. Legacy chat persistence uses the same
budget calculation.
</details>

## Test plan

- [x] 219 integrated configuration, SDK, history, and stdio tests
passed; 106 history/stdio tests passed after the final error-handler
cleanup.
- [x] CI runs the history/stdio regression coverage and
context-resolution tests.
- [x] Real TUI with local Gemma-4-E4B and memory disabled: read a file,
omit its facts from the final answer, delete the file, then recover its
code in a follow-up without a tool call.
- [x] Restart the TUI with the same transcript and recover ledger number
`7319`, which appeared only in the deleted file's tool result.
- [ ] Formal agent quality evaluation and human review. One initial live
follow-up hit a backend timeout; the retry and restart checks passed.
These checks establish evidence retention, not a latency or quality
benchmark.

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Tomasz Iniewicz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chat Chat SDK changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

On non-Claude backends, every tool call is replayed to the model as an assistant message saying "None"

2 participants