Skip to content

fix(agent): keep the answer a model sends alongside its last tool call - #4745

Merged
kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:kalin/answer-with-tool-call
Oct 5, 2026
Merged

kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:kalin/answer-with-tool-call

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

When a model wrote its answer and called a cleanup tool in the same reply, the user only saw the wrap-up that came after it. In the data_followup_compound eval, DeepSeek V4.1 Flash answered with the revenue table and dropped the scratch table in one step, then closed with "Scratch table cleaned up." That one line was the whole reply. Now the answer comes first and the wrap-up follows it. Planning lines sent with a tool call ("Let me read the file first.") and model reasoning still never reach the answer.

task_sourcewatch_detects_change (whose final answer was just "Logged.") very likely hit the same bug. The source-watch skill tells the model to report what's new first and only then remember it, so the report goes out with the memory call and is followed by a one-word wrap-up.

🔍 Technical details
  • Text sent with the turn's last tool calls is promoted only when the closing reply is shorter than it and doesn't already contain it. A restated answer is therefore not duplicated, and any later tool call clears it.
  • A trailing next-step sentence ("Let me clean up the table.") is removed before promotion. If the text is narration only, nothing is promoted.
  • The promoted text is in place before the seam's completion, claim and verification checks run, so they check exactly what the user sees.
  • The ChatAgent scratchpad workflow prompt now puts drop_table before the final answer instead of ending with "drop_table when done".
  • The source-watch skill text is unchanged: the loop fix covers its report-then-record order.

Test plan

  • pytest tests/unit/agents/test_answer_beside_tool_calls.py: the 4-message reproduction fails on main and passes here. It covers streaming and non-streaming, narration that must not be promoted, de-duplication, a later tool call, and reasoning.
  • pytest tests/unit/agents/: 2326 passed
  • Hub gaia and chat agent tests: 668 passed. The 4 failures (tool-bundle/manifest counts, session storage) fail identically on origin/main.
  • python util/lint.py --black --isort
  • gaia eval agent --category gaia_data
  • gaia eval agent --category gaia_skills_tasks

A model that answered and cleaned up in the same reply (answer text plus a
drop_table call) ended the turn on a short wrap-up, and only that wrap-up
became the final answer: the user saw "Scratch table cleaned up." instead of
the result. Answer text sent alongside the turn's last tool calls now leads
the final answer when the closing reply is a shorter wrap-up. Reasoning and
next-step narration ("Let me read the file first.") are never promoted, and a
later tool call clears it. The completion checks see the combined text.

The scratchpad workflow prompt now places drop_table before the answer.
@github-actions github-actions Bot added tests Test changes agents labels Oct 5, 2026
@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

This fixes a real bug: when a model wrote its answer and called a cleanup tool in the same reply, the user saw only the wrap-up line. The fix is narrow and well tested. Two things need attention before merge:

  • Progress chatter can now leak into short answers. Only first-person "I'll / let me / I need to" lines are recognised as narration. A model that writes "The search returned three files. Reading the largest one now." beside its last tool call, then answers "Timeout is 30s.", gets that chatter put in front of the answer. That's because the answer is shorter than the chatter. Please tighten when text gets promoted, and add a test for this case.
  • The required agent evals haven't run. This changes how the agent builds its final answer, which CLAUDE.md says needs a gaia eval agent run. Both eval items in the test plan are still unchecked. Please run gaia_data and gaia_skills_tasks (dispatch eval_flagship.yml), and report any PASS→FAIL changes against the flagship baseline.

Real-world evidence

N/A: no evidence bundle was produced for this run, and the change is agent-loop behaviour that needs real inference (strix-halo eval lane). This verdict rests on static review alone. I couldn't run the new tests here either, because the runner lacks the project's dependencies.

🔍 Technical details

Issues

🟡 Narration filter only drops trailing first-person intent, so other progress text gets promoted (src/gaia/agents/base/agent.py, _answer_beside_tool_calls / _with_answer_beside_tool_calls)
The strip loop removes a trailing sentence only if it matches _NEXT_STEP_INTENT_PATTERN or _TOOL_STEP_INTENT_PATTERN. Narration in other shapes survives, and then the only remaining gate is len(answer) < len(beside):

  • "The search returned three candidate files. Reading the largest one now." has no match, so the whole text is promoted.
  • "I found config.yaml; it has 40 settings. I need to check the timeout section." loses its last sentence, and the first is promoted.

Paired with a short closing answer like "Timeout is 30s.", both produce <narration>\n\n<answer>. That's the leak the PR description says can't happen. Length is a weak signal because short, correct final answers are common. Some options:

  • Promote only when the closing reply looks like a wrap-up (acknowledges a side effect, no new facts).
  • Require the beside text to look like an answer (structure, or a meaningful length floor) rather than just "not intent".
  • At least add a negative test with participle/status narration ("Checking…", "Reading … now.") so the boundary is pinned down.

🟡 LLM-affecting change merged without the eval run (PR test plan)
This touches tool-call response handling and final-answer assembly, which is on CLAUDE.md's list of changes that need an eval. Run gaia_data (where the data_followup_compound repro lives) and gaia_skills_tasks (task_sourcewatch_detects_change). Compare against tests/fixtures/eval_baselines/gaia-flagship/, and list regressions and progress separately. The ChatAgent scratchpad prompt edit (drop_table → final answer) also falls under this rule.

🟢 text.rfind(last) can cut the wrong place (agent.py, strip loop)
rfind runs on the raw text, but last came from the split. If that sentence appears verbatim earlier too, the cut still lands on the final occurrence, which is correct. But if the split boundary is a \n inside a markdown table row, a table's last row ending in "Let me…" would be dropped. This is an edge case; a test with a trailing table would confirm it behaves.

Strengths

  • The promoted text is set before every completion, claim and verification check runs, so those checks see exactly what the user sees. The finalized assertion in the test pins that down.
  • The tests cover streaming and non-streaming, de-duplication, a later tool call clearing the carry-over, and <think> reasoning. They use a real 4-message reproduction rather than unit-testing the regex alone.
  • The CHANGELOG entry and the prompt fix ship together with the code.

kovtcharov and others added 4 commits October 5, 2026 08:41
…md#4726)

If you asked a chat about a document it hadn't been given, the answer
never came. Indexing the file was refused without asking you. Reading it
did ask, but the tool gave up after 180 s while your answer was still
pending, so clicking "Allow once" afterwards did nothing. Even an
approved file stayed blocked for document search. Now indexing asks the
same question reading does, one approval covers reading, indexing and
querying for the rest of the chat, and waiting on your answer no longer
counts against the tool's time limit. Live on DeepSeek V4.1 Flash, the
original question ("which source tag do bootstrap-discovered items
get…", 47-page PDF) gets one prompt and a cited answer. Before the fix
it ran 43 steps and never answered.

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

- `RAGToolsMixin._index_access_error` uses the agent's
`PathValidator.validate_read` (prompting) instead of
`_is_path_allowed(prompt_user=False)`.
- `RAGSDK(config, path_validator=...)`: ChatAgent passes its own
validator, so grants reach `_safe_open`. Before, text files failed
outright, and PDFs lost their content-keyed cache and were re-extracted
on every index.
- `_call_tool_bounded` excludes time spent on a prompt raised inside the
tool body, tracked through a contextvar clock in `_confirm_path_access`.
The prompt keeps its own 10-minute bound and cancellation.
- On an Agent UI cache hit, documents attached since the agent was built
are added to its validator.
- Model-visible text: `access_denied_message` gains "Do not copy, move
or convert it to another location to get around this." amd#4460 records
only confirmation denials and shell policy refusals, so it doesn't cover
a tool's own access-denied result.
- Agent UI eval runs set `GAIA_AUTO_APPROVE_TOOLS=1`. With that set,
path prompts are refused by design and never reach the scripted user, so
out-of-scope writes in `gaia_files` (e.g. `files_edit_file`) dead-end.
That's an eval-harness gap and isn't changed here.
</details>

## Test plan
- [x] `pytest tests/unit/test_path_access_grant.py`: 8 pass; 5 fail with
the src diff reversed
- [x] `tests/unit` plus the chat and gaia hub suites: 25 failures, all
identical with the src diff reversed; the rest are environment-only
- [x] `python util/lint.py --black --isort`
- [x] Live Agent UI backend, DeepSeek V4.1 Flash,
`GAIA_AGENT_TOOL_TIMEOUT=20`, prompt answered after 30 s: one prompt,
correct cited answer
- [ ] `gaia eval agent --category gaia_rag` and `--category gaia_files`
(tool results the model sees changed; run serially)

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
"Use your shell tool to run pwd" made the flagship guess the directory
instead of running the command (`gaia_shell/shell_pwd_basic` fails 2/2
on main). The shell was never offered. About 90 tools matched the
message semantically, the 29-tool cap decided, and `run_shell_command`
lost its slot to file browsers. Now a tool the user names, or a request
only the shell can answer (pwd, working directory, "run git status", "in
the terminal"), goes into the tool set ahead of semantic ranking.

This brings back a narrow keyword signal, which the tool-loader plan had
removed on purpose. It only adds tools and only fires on explicit asks;
the plan doc now says why.

## Test plan
- [x] `pytest tests/unit/test_chat_tool_requests.py
tests/unit/test_tool_loader_selection.py
hub/agents/gaia/python/tests/test_full_tool_bundles.py` passes. The
flagship test fails with the classifier disabled.
`test_core_and_bundles_cover_the_flagship_registry_exactly` and
`test_optional_tools_are_present_on_a_full_install` fail locally only
because Playwright isn't installed; they fail on main too.
- [x] `python util/lint.py --black --isort --flake8` is clean
- [x] With the real embedder, "Use your shell tool to run pwd…" now
selects `run_shell_command` and `get_shell_state` (before: neither,
`run_shell_command` skipped at the cap)
- [ ] `eval_flagship.yml`: `gaia_shell/shell_pwd_basic` passes, and no
category regresses against
`tests/fixtures/eval_baselines/gaia-flagship/` (especially
`tool_selection` and `gaia_shell`)

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

- New `REQUESTED` tier in `ToolLoader.select(requested_tools=...)`. It
is admitted after CORE and ahead of SKILL. It reuses the SKILL admission
loop (now `_admit_exact`), so it follows the same cap, LRU eviction and
per-turn protection. Its log key `requested` is emitted only when
non-empty.
- The classifier is `gaia_agent_chat.tool_requests.requested_tools`. It
matches an underscored registry name written out, or a
shell/working-directory phrase. "Terminal" and "bash" count only when
they name the place something runs ("in the terminal"), so "the airport
terminal" doesn't fire.
- Real-embedder scores for the turn-1 message: `get_shell_state` 0.69,
`run_shell_command` 0.40, threshold 0.20, cap 29.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Progress text sent beside a lookup ("The search returned three files.
Reading the largest one now.") was put in front of a shorter real answer.
Text beside read/search/query/run calls is now always progress; only text
beside closing actions like drop_table or remember can be the answer.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Fixed the progress-chatter leak. Text sent beside a lookup (reading, searching, querying, running something) is now always treated as progress, because the reply after a lookup is the answer. Only text sent beside a closing action, like dropping a scratch table or saving to memory, can be promoted. Your example ("The search returned three files. Reading the largest one now." then "Timeout is 30s.") is now a test, and it fails without the change.

The gaia_data and gaia_skills_tasks evals are queued on DeepSeek V4.1 Flash and will be re-run on this commit; results will follow here.

🔍 Technical details
  • _LOOKUP_TOOL_PATTERN in src/gaia/agents/base/agent.py: tool names starting read_, search_, find_, list_, get_, query_, run_, execute_ and similar disable promotion for that step.
  • New tests: test_progress_beside_a_lookup_is_not_promoted (fails on the previous commit, streaming and non-streaming) and test_report_sent_with_a_memory_save_reaches_the_user (the sourcewatch "Logged." shape).
  • pytest tests/unit/agents/: 2330 passed. black and isort clean.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 5, 2026
Merged via the queue into amd:main with commit 645d414 Oct 5, 2026
@kovtcharov-amd
kovtcharov-amd deleted the kalin/answer-with-tool-call branch October 5, 2026 16:24
grtninja pushed a commit to grtninja/gaia that referenced this pull request Nov 12, 2026
…md#4866)

**Branch:** `feat/verify-edits-before-the-answer-is-sealed`
**Base:** `e0fd6717f609a5be7ca8676a6be2c869fd4fe4b2` (`e0fd6717f`)
**Commits:**

| SHA | Subject |
|---|---|
| `bdfc3402885aedfb8fc3488a3aaa85da3ae2c3ab` | feat(agent): read this
turn's edits back before the answer is sealed |
| `836b57016695d59db4362ade466d60eb032d376f` | fix(agent): read back
only text-file edits, not every path a tool reports |

## Relationship to amd#4719 and amd#4745

amd#4719 ("keep the read-back check out of the user's answer") touches a
*model-facing prompt string* inside the completion check, and only fires
when
there is an artifact gap — the model claimed a save the evidence ledger
cannot
corroborate. It tells the model not to narrate that read-back in its
reply.

This change is a different mechanism answering a different question: an
in-process, read-only check the **loop** runs over the files the turn
actually
wrote, whenever it wrote any. It does not touch amd#4719's prompt string,
does not
re-instruct the model to read anything, and does not reintroduce the
narration
amd#4719 removed — its findings only enter the conversation when something
is
wrong. The two compose; neither is redundant.

amd#4745 ("keep the answer a model sends alongside its last tool call")
requires
the promoted answer to be in place before the seam's checks run. It is:
the
promotion happens earlier in `_process_query_impl` than this check, so
the
read-back still runs against exactly what the user will see.

## The problem

A tool result saying `"status": "success"` is not the same as a file
that is
still on disk, still has content, and still parses.

Today the only thing that closes that gap is the model choosing to check
— and
whether it does is a property of the **model**, not of the loop. Given
the same
tools and the same prompt, some models read their work back every time
and some
never do. That means the behaviour disappears the moment the model
changes,
which is not a property anyone can build on.

## The change

The loop is better placed to do it. It already records which files this
turn
wrote, so just before the answer is sealed it opens each of them and
asks three
questions the tool result cannot answer:

- is it still there,
- does it still have content,
- and, for Python and JSON, does it still parse.

If anything comes back wrong, the findings go into the context and the
turn gets
**two steps to fix them**.

### The free steps are the load-bearing part

Those two steps are granted on top of `max_steps`, not taken out of it.

Verifying currently costs steps from the same budget as working, so a
model
under budget pressure is right to skip it — and the pressure peaks at
the end of
a turn, which is exactly where the edits are. Making the repair free
removes the
incentive to look away. Charging for it would make this feature
self-defeating.

## Design notes

**Where "which files did this turn write" comes from.** The
completion-evidence
ledger, which every write tool feeds. `_turn_file_edits` looks like the
obvious
source and is not: it is appended only for a tool result carrying
`operation == "edit_file"`, and nothing in `file_io_tools` sets that
field, so
reading it would make the check silently do nothing for every shipped
file tool.
There is a test driving the real tools through the real loop
specifically to pin
that.

**Deliberately narrow.** Read-only, in-process, no shell, no subprocess,
no
repository walk. It cannot be slow in proportion to the repository and
cannot
touch anything the turn had not already touched, so it is safe to run
every
time. A file type it cannot parse is checked for existence and content
and
otherwise left alone, rather than having a syntax guessed at for it.

**Bounded.** Two rounds per turn, after which the turn is looping and
the
findings go into the answer instead of driving another repair.

**`GAIA_AGENT_VERIFY_EDITS=0`** turns it off.

## What this is not

This does not tell you whether a change is *correct* — nothing that
needs no
configuration could. It tells you the change is not **obviously
broken**, which
is the failure the loop can see by itself. Judging correctness needs the
repository's own tests, which is a different and much larger piece of
work.

## Two existing tests opt out

Both register write tools that report success without touching the disk,
so the
read-back correctly finds the file they named missing and spends a
repair step
saying so. One pins the loop's exact model-call count; the other scripts
a fixed
list of replies that the extra call exhausts. Neither is about writing
files, so
the honest fix is to turn the check off for them and say why in the
fixture, not
to weaken the check.

## Fix: only text-file edits are read back

The first version of this branch took its file list straight from the
completion-evidence ledger. That ledger records more than edits: it also
holds
the outputs of tools that *generate* files (`generate_image`,
`text_to_speech`, `take_screenshot`, ...) and paths an executor
reported. So a
turn that generated an image had the image path read back as if the
model had
edited it, found a "problem", and spent a repair round asking the model
to fix
a file it never edited. `tests/unit/agents/test_image_outcome_guard.py`
caught
it: two of its tests failed with an unexpected extra model call.

The second commit fixes the cause rather than the tests (which are
unchanged):

- the ledger marks an entry `edited` when its last writer was one of the
file-editing tools in `WRITE_TOOLS`, and only those are read back. Any
later
change by something else replaces the entry, so a file a script rewrote
or
  deleted on purpose after its edit is not reported as broken;
- binary files are skipped, by extension or by a NUL byte in the
content;
- reads go through the agent's read boundary without prompting, so a
path the
  model could not read is not read here either;
- a file over 2 MiB is checked for presence only.

New regression tests cover a generated image (unit, and through the real
loop
with the check on), a read-only tool, an executor output, a file deleted
on
purpose, binary content and a path outside the read boundary; five of
them fail
without the fix.

## Risk

The findings enter the conversation and can add turns, so this changes
model
behaviour and wants an eval run before merge.

## Test plan

- [x] `pytest tests/unit/test_post_edit_verification.py
  tests/unit/agents/test_cut_off_reply_guard.py
  tests/unit/agents/test_parse_error_recovery.py
  tests/unit/agents/test_completion_evidence.py
  tests/unit/agents/test_read_file_line_ranges.py
  tests/unit/agents/test_image_outcome_guard.py

tests/unit/eval/test_flagship_tasks.py::test_an_adversarial_task_rejects_the_shortcut`
on this branch alone — 251 passed, 2 skipped
(`test_post_edit_verification.py`
is 36 tests: a missing file, an emptied file, broken Python and broken
JSON,
  the free repair steps not counting against `max_steps`, the two-round
ceiling, an unparseable file type being left alone, the env knob, and
the
  over-reach cases above)
- [x] `tests/unit/agents/test_image_outcome_guard.py` — 8 passed,
unmodified
- [x] Full `tests/unit` — see below
- [x] `python util/lint.py --black --isort`
- [ ] **Eval (LLM-affecting):** compare against the same run with
  `GAIA_AGENT_VERIFY_EDITS=0`

### Full unit suite

`tests/unit`, Windows, `--timeout=300`, run on unmodified `main`
(`e0fd6717f`)
and on a disposable build with all four open branches stacked (line
endings in file tools, step-budget notices, post-edit
read-back, model-endpoint retry):

| | Passed | Failed | Skipped |
|---|---|---|---|
| `main` `e0fd6717f` | 19,373 | 5 | 410 |
| stacked build | 19,602 | 5 | 410 |

The same five tests fail on both, and none of them is touched by this
branch:
three installer TUI-detection tests,
`test_file_access_scope.py::test_no_allowlist_still_defaults_to_cwd`,
and
`test_lemonade_asr.py::TestRealServer::test_real_transcription_round_trip`,
which needs a live server. No test fails on the stacked build that
passes on
`main`.

### Stacking with other open branches

Applies cleanly to `main` on its own. It conflicts textually with the
step-budget notices branch
(`feat/tell-the-model-how-much-step-budget-is-left`), whichever lands
second: both add an env-knob function after `_TOOL_USER_WAIT` and
per-turn state in `__init__` and at the top of `_process_query_impl` in
`src/gaia/agents/base/agent.py`. The resolution is to keep both sides —
two separate functions and both sets of fields.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: v <v@x>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants