Skip to content

fix(agent): answer from what it found when the step limit runs out - #4028

Closed
kovtcharov wants to merge 7 commits into
amd:mainfrom
kovtcharov:claude/step-cap-final-answer
Closed

kovtcharov wants to merge 7 commits into
amd:mainfrom
kovtcharov:claude/step-cap-final-answer

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

When an agent ran out of steps, the user got a canned "Reached maximum steps limit" note with an empty tool list and no word on what happened. In today's benchmark GitHub rate-limited every gh call; GAIA spent all 30 steps on workarounds and never mentioned the rate limit, while Claude Code in the same spot said what happened and how to retry. Now, at the step limit, the agent gets one more model call in which it can't use tools, and answers from what its tool results show: what it found, what it couldn't finish and why, and what to do next. If that call fails, the note comes back with a line saying why.

Test plan

  • python -m pytest tests/unit/agents/test_step_cap_final_answer.py: 22 tests covering streaming and non-streaming, written first and failing before the fix
  • python -m pytest tests/unit/test_claude_provider.py tests/unit/test_lemonade_tool_choice.py: tool_choice mapping, validation, and the request body on both Lemonade paths
  • python -m pytest tests/unit: no new failures against main (the remaining failures are environment-only and fail on main too)
  • black, isort, flake8 and pylint clean on the touched source files
  • gaia eval agent --category tool_selection shows no regression against the baseline
  • A step-capped query on a live Lemonade model (a local GGUF and a Fireworks model) gets its answer from the closing call, confirming the server honours tool_choice="none" with tool-call history in the request
🔍 Technical details
  • The closing call goes through the loop's own path: self.chat.send_messages or send_messages_stream (chosen by self.streaming), with the loop's messages plus one user instruction, the same system prompt, the same tools, and tool_choice="none". The tools stay because Anthropic rejects tool_use/tool_result history on a request with no tools. A model without native tool calling sends no tools and no tool_choice, as in the loop. The closing call counts as one more step, and its stats land in conversation, so steps_taken and the token totals include it.
  • tool_choice is a new explicit parameter on LemonadeProvider.chat, ClaudeProvider.chat and LemonadeClient.chat_completions. Lemonade sends it unchanged, top-level on the streaming path too, and only when set; it's withheld along with the tools for a model without native tool calling. Claude maps "none"/"auto" to {"type": ...} and raises on any other value. Both raise if tool_choice comes without tools.
  • The reply goes through _parse_llm_response, finalize_answer and _with_verification_scope, then print_final_answer, like any other answer. Status stays incomplete (or failed when error_history is non-empty, as before). max_steps_reached is new on every result.
  • Failure: the canned note plus "The summary of what I found couldn't be written: ", with a warning logged. This covers the call raising, an empty reply, and a reply that calls a tool anyway (native, JSON or tool markup).
  • Cancellation: a set _cancel_event skips the call and names that as the reason. Agent UI Stop during the closing stream ends the turn as cancelled with empty text, as fix(ui): Stop doesn't abort in-flight chat generation — cancel only observed at step boundaries #2157 requires.
  • _generate_max_steps_message looked for OpenAI-style tool_calls on assistant entries, which GAIA's conversation never contains. It now counts role: tool entries, which every execution path writes once per call that ran.
  • The CLI now shows "Processing stopped after 51/50 steps" at the cap, because the closing call counts as a step.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

Good change with a real user win: when an agent burns through its step budget, it now says what it found and why it stopped instead of printing a canned notice with an empty tool list. The tests are thorough and the docs were updated alongside. Two things should be sorted before merge.

A user who asks the agent to stop now gets one more model call anyway. In an interactive terminal, when the agent hits the limit it asks "Continue with 50 more steps?". Answering no — or pressing Ctrl-C at that prompt — takes the same exit path as running out of steps, so the new wrap-up call fires and the user watches another generation they just declined. Mark the user-declined exit so the wrap-up call is skipped.

On the Claude backend this new call will fail every time. The wrap-up request replays the tool history but offers no tools, and the Anthropic API rejects a conversation containing tool blocks when no tools are defined. The failure is handled — the user gets the old notice plus a raw API error line — but the feature never actually works there. Either keep sending the tool definitions and rely on the existing "the model asked for a tool instead of answering" guard, or drop the tool exchanges from the wrap-up request.

Missing checks the change calls for. The PR's own test plan leaves the agent eval and the live-model run unchecked. This touches the agent loop and adds a new model-facing instruction, so the project rules ask for an eval run against the committed baseline before merge, and the live run is the only thing that answers the Anthropic question above for the Lemonade/OpenAI side too.

Real-world evidence

N/A — no evidence bundle was produced for this run, and pytest isn't installed in the review environment, so I could not execute the new tests either. The verdict rests on static review alone. The user-facing surfaces this touches (the gaia CLI answer at the step cap, and the new 51/50 step count it prints) have no captured CLI output on the PR; a real gaia chat --max-steps <n> transcript of a capped run would close that gap, along with the two unchecked test-plan items.

🔍 Technical details

🟡 Important

1. User-declined continuation falls into the step-cap wrap-up (src/gaia/agents/base/agent.py:7514)

max_steps_reached = final_answer is None and not cancelled_by_console also captures the two interactive exits at agent.py:7504 (EOFError/KeyboardInterrupt) and agent.py:7507 (answered n), both of which break with final_answer still None. The result is an unrequested LLM call after the user said stop. Track the decline explicitly — initialise user_stopped = False next to cancelled_by_console (agent.py:5398), set it in both break branches, then:

        max_steps_reached = (
            final_answer is None and not cancelled_by_console and not user_stopped
        )

With max_steps_reached false and final_answer still None, the result falls through to the existing _generate_max_steps_message fallback at agent.py:7615 — the pre-PR behaviour for that path.

2. The wrap-up call is structurally invalid on the Claude provider (agent.py:4270)

ClaudeProvider._to_anthropic_tools returns None for tools=None (src/gaia/llm/providers/claude.py:243), while _tool_use_content/_append_tool_result still emit tool_use/tool_result blocks from the replayed history. Anthropic 400s that combination ("Requests which include tool_use or tool_result blocks must define tools"), so on --model claude-* every step-capped run lands in the except branch with the raw API error appended to the notice. This is the known risk named in the PR description — confirming it's deterministic, not speculative. Two workable shapes: pass tools=self._format_tools_for_prompt(...) as usual and let the existing parsed.get("tool") guard reject a tool call, or filter tool-role entries out of request before sending.

3. Eval + live-model verification not run

_STEP_CAP_ANSWER_PROMPT is new model-facing text and the change alters when tools are offered — both on CLAUDE.md's "requires an eval run before merge" list. gaia eval agent against the relevant category, compared to the committed baseline, before merge.

🟢 Minor

  • steps_taken now exceeds steps_limit (agent.py:7517) — print_completion renders 51/50, and result["steps_taken"] reports the same to Agent UI consumers. The PR notes this; worth deciding whether the wrap-up should count as a step at all, or be reported separately (the new max_steps_reached flag already carries the signal).
  • The failure-path reason never reaches the console (agent.py:7526-7532) — the canned notice was already printed as a warning inside the loop at agent.py:7479; the appended "The summary of what I found couldn't be written: …" only lands in the returned dict and the log, so a CLI user sees the notice without the reason.
  • Unguarded stream.close() (agent.py:4287) — the loop's equivalent teardown at agent.py:5895 wraps close() in a best-effort try. Here a raising close() converts a clean cancel into the failure branch.
  • Double notice on the success path — at a capped run the user now sees the ⚠️ Reached maximum steps limit warning and then a substantive answer. Reads slightly contradictory; consider moving print_warning after the wrap-up attempt, or downgrading it to an info line.

Strengths

  • _generate_max_steps_message fix is a real latent-bug fix (agent.py:4222-4228): it scanned assistant entries for an OpenAI-style tool_calls key that GAIA's conversation never contains, so the "tools used" list was always empty. Counting role: tool entries matches what both the native path (agent.py:4858) and the JSON path (agent.py:4623) actually append, and test_max_steps_message_lists_the_tools_that_ran pins it.
  • Test file earns its length: parametrized over streaming/non-streaming, covers both the native tool-call and JSON-envelope protocols, asserts the wrap-up request's exact message shape and tools is None, and covers all three failure reasons plus both cancellation routes (console Stop mid-stream vs. _cancel_event).
  • Docs updated across all three surfaces in the same change (cli.mdx, agent-system.mdx, agent-base.mdx), including the new max_steps_reached result field — matches CLAUDE.md's rule that a behavioural change updates every doc describing it.
  • The wrap-up reply goes through the normal answer pipeline (_parse_llm_response → finalize_answer → _with_verification_scope → print_final_answer), so the verification scope line and turn metrics behave the same as any other answer rather than being a special case.

@github-actions github-actions Bot added llm LLM backend changes performance Performance-critical changes labels Sep 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🟡 The prior review's finding about the user-declined continuation path wasn't addressed in this push. When a user answers "n" (or presses Ctrl-C) at the "Continue with 50 more steps?" prompt, the loop breaks with final_answer = None and cancelled_by_console = False, so max_steps_reached evaluates to True and the wrap-up call fires anyway — generating output the user just said they didn't want. The structural Claude-provider fix (keeping tools + tool_choice="none") landed correctly, but this interactive path still needs the user_stopped guard the prior review described.

🔍 Technical details

agent.py:7527:

max_steps_reached = final_answer is None and not cancelled_by_console

cancelled_by_console is only set by the Agent UI Stop button (agent.py:5907). The two interactive break paths at lines 7515–7520 (user typed "n" or got EOFError/KeyboardInterrupt) leave cancelled_by_console = False and final_answer = None, so max_steps_reached is True for both and _answer_at_step_cap fires.

Fix from the prior review: add user_stopped = False near cancelled_by_console at line 5411, set it True in both break branches (lines 7517 and 7520), then:

max_steps_reached = final_answer is None and not cancelled_by_console and not user_stopped

Silent-mode break at line 7523 should keep firing the wrap-up (no user intent there).

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Checked against a live server: Lemonade proxying fireworks.kimi-k2p7-code, non-streaming, max_steps=2. The closing call went out with the loop's tools, the tool-call history and tool_choice="none", and was accepted. The result had status: incomplete and max_steps_reached: True, and the answer said what it found (the two directory listings), what it couldn't finish (reading each file) and the next step. Before this change the same run ended with the canned "Run with --max-steps" note. The Lemonade half of the live Test-plan item is done; NPU/FLM backends are still unchecked.

Kalin Ovtcharov and others added 3 commits September 21, 2026 04:32
…al cause

After four identical tool calls the loop guard ended the task and told the user
to "check that the underlying service is running" — even when calls were
throttled and never ran, refused by policy, or a script exited non-zero. In a
168-run benchmark it fired 6 times with no outage behind any of them, and twice
replaced a finished task's answer with a failure message.

- Rate-limited calls never executed, so they no longer count as repeats; the
  loop waits out the reported wait (capped at 15s) before continuing.
- The first time a call hits the limit, the model gets one correction as that
  call's result ("do not repeat it — try a different approach"); only a repeat
  after the correction ends the turn.
- The summary now says rate-limited, not permitted, or the actual failure, and
  only blames a service for connection errors. With no error key it quotes the
  last stderr line.
- The legacy path read step_results, which error recovery clears before every
  retry, so a loop of failures was summarised as "Task completed". It now reads
  previous_outputs like the native path.

Folded in from review:
- read a Windows socket error as a dead service, not a refusal
- read a dead service as a dead service, and count only calls that ran
- read "blocked" as a refusal only when it is one, and reject a repeat limit
  below 2

Fixes amd#3888
An agent that ran out of steps replied with a canned note that never said
what it found or why it stopped. In a benchmark run GitHub rate-limited every
`gh` call; the agent spent all 30 steps on workarounds and never mentioned the
rate limit. The note's "tools used" list was also always empty.

At the step limit the agent now makes one more model call on the loop's own
path, with no tools offered, asking for a final answer from what the tool
results show: what it found, what it couldn't finish and why, and what the
user can do next. The run still reports "incomplete" and sets
max_steps_reached. If that call fails or doesn't answer, the canned note comes
back with a line saying why and a warning is logged. The note now lists the
tools that actually ran.
On the Claude backend the step-limit summary would always have failed:
Anthropic rejects a request whose history holds tool calls and results when it
defines no tools, so the user got the canned note every time. The closing call
now sends the same tools as the loop with tool_choice="none", which every
backend accepts and which leaves the tool schemas at the front of the prompt
unchanged.

tool_choice is now an explicit parameter on the Lemonade and Claude providers
and on LemonadeClient.chat_completions. Lemonade sends it unchanged, top-level
on the streaming path too, and only when set. Claude maps "none" and "auto" to
Anthropic's shape and raises on anything else. Both raise when tool_choice
comes without tools. A reply that calls a tool anyway still counts as a failed
summary.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #3908 (fix-3888-loop-guard). Merge after #3908.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The user-declined-continuation path still fires the wrap-up call — the prior review's open request-changes finding wasn't addressed in this push.

When a user answers "n" at the "Continue with 50 more steps?" prompt, or presses Ctrl-C there, the loop breaks with final_answer = None and cancelled_by_console = False. Because max_steps_reached = final_answer is None and not cancelled_by_console (agent.py:7572), the condition is True and _answer_at_step_cap fires anyway — generating a model call the user just explicitly declined, after they already saw "Stopping at user request."

The tool_choice="none" fix for Claude (the prior review's other request-changes item) is in and looks correct. But this interactive-exit path still needs a user_stopped flag.

🔍 Technical details

agent.py:7560–7568 — the two user-decline breaks leave cancelled_by_console = False:

else:
    self.console.print_info("Stopping at user request.")
    break        # final_answer still None, cancelled_by_console still False
except (EOFError, KeyboardInterrupt):
    self.console.print_info("\nStopping at user request.")
    break        # same
else:
    # Silent mode - just stop
    break        # same (silent mode should also skip the wrap-up)

Fix from the prior review: initialise user_stopped = False near cancelled_by_console (agent.py:5417), set it True in all three break branches above, then:

max_steps_reached = final_answer is None and not cancelled_by_console and not user_stopped

With user_stopped = True, the condition is False, _answer_at_step_cap is skipped, and the run falls through to the existing _generate_max_steps_message fallback — which is already what the user saw before they said stop.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

This PR is stacked on #3908 — that one has to merge first.

Its commit is already inside this branch, but both PRs say base: main, so GitHub presents them as independent and will happily merge this one first. That leaves #3908 open carrying work main already has. #4035 sits on top of this PR in turn.

Order: #3908 → #4028 → #4035, as merge commits rather than squashes — a squash here rewrites the shared commit and conflicts both neighbours.

🔍 Technical details

git log --oneline origin/main..fork/claude/step-cap-final-answer lists 41b17cf9f (#3908) beneath this PR's own 2dc1e47d7 and 50aa38fb0. The branch history is already correct (triage/3908 merged into triage/4028); only the PR base field is out of step.

The base can't be retargeted as-is — claude/fix-3888-loop-guard exists only on the kovtcharov fork, and a PR base must be a branch in amd/gaia.

This PR rewrites 352 lines of src/gaia/agents/base/agent.py, a file 29 other open PRs also touch.

Kalin Ovtcharov and others added 2 commits September 23, 2026 16:29
# Conflicts:
#	src/gaia/llm/providers/claude.py
…anyway

Answering "n" at "Continue with 50 more steps?" — or pressing Ctrl-C there —
left `final_answer` empty and `cancelled_by_console` false, so the step-cap
wrap-up call fired and produced the answer the user had just declined. Only the
Agent UI Stop button sets `cancelled_by_console`; the two interactive breaks
set nothing.

They now set `user_stopped`, which the wrap-up decision reads. Silent mode is
untouched: running out of steps unattended still gets the closing answer.

Not unit-covered: the continue prompt only runs on a step that is neither a
tool call nor an answer, which the existing harness cannot script.

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

Copy link
Copy Markdown
Collaborator

Replicated as #4373 — fork push access (kovtcharov/gaia) was revoked mid-review, so this PR could no longer be refreshed against main. Same content, conflicts re-resolved against current main. Closing in favor of the replacement.

🔍 Technical details

#3908 has since merged (squash 69fc540b5), so the replacement cherry-picks only this PR's own three commits (2dc1e47d7, 50aa38fb0, 429de6a48) onto main rather than merging the branch — a merge would have re-applied #3908's fork commit on top of its own squash. The one conflict (claude.py: main's new name_map return vs. this PR's tool_choice parameter) was resolved exactly as you resolved it in 26d80fcfa.

#4035 is stacked on this branch and will need retargeting onto #4373.

kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
…md#4373)

When an agent ran out of steps, the user got a canned "Reached maximum
steps limit" note with an empty tool list and no word on what happened.
In a benchmark where GitHub rate-limited every `gh` call, GAIA spent all
30 steps on workarounds and never mentioned the rate limit. Now, at the
step limit, the agent gets one more model call in which it can't use
tools, and answers from what its tool results show: what it found, what
it couldn't finish and why, and what to do next. If that call fails, the
old note comes back with a line saying why.

Replicates amd#4028, which lives on the `kovtcharov/gaia` fork — push
access was revoked mid-review, so that PR could no longer be refreshed
against main and was stuck `CONFLICTING`. Same content, re-resolved
against current main. No content changes beyond the conflict resolution.

## Test plan

- [x] `python -m pytest tests/unit/agents/test_step_cap_final_answer.py
tests/unit/test_claude_provider.py
tests/unit/test_lemonade_tool_choice.py` — 89 passed
- [x] `python -m pytest tests/unit/agents` — 1511 passed, 50 skipped, 0
failed
- [x] Provider-layer selection (`-k "claude or lemonade or provider"`)
diffed against a clean-`main` worktree baseline — identical failure
sets, zero regressions (the 12 remaining are pre-existing macOS/posix
tests failing on a Windows host)
- [x] `python util/lint.py --black --isort --fix` clean, no changes;
`python util/lint.py --flake8` passes
- [ ] `gaia eval agent --category tool_selection` — not run here;
carried over unchecked from amd#4028
- [ ] Live step-capped run on NPU/FLM — the Lemonade half was confirmed
on amd#4028 (a `fireworks.kimi-k2p7-code` run accepted the closing call
with tools + `tool_choice="none"` and answered from its results);
NPU/FLM still unchecked

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

**Replication method.** amd#4028 was stacked on amd#3908, which main
squash-merged as `69fc540b5`. A plain merge would re-apply amd#3908's fork
commit on top of its own squash, so instead the three commits that are
amd#4028's own work were cherry-picked onto main: `2dc1e47d7`, `50aa38fb0`,
`429de6a48`. amd#3908's fork commit and main's squash were verified
byte-identical before dropping it.

**Only conflict: `src/gaia/llm/providers/claude.py`.** Main changed
`_build_params` to also return a `name_map` (`_to_anthropic_tools` now
returns a tuple); amd#4028 added a `tool_choice` parameter and passed it
through from `chat`. Both kept — the signature takes `tool_choice` and
returns `tuple[dict, Dict[str, str]]`. This is the identical resolution
the author made in `26d80fcfa` on the fork, confirmed by reading that
merge's combined diff; it was the only evil-merge content across all
three of the branch's merge commits, so the replicated tree reproduces
the PR head exactly. Verified by matching symbol counts for
`_STEP_CAP_ANSWER_PROMPT`, `_answer_at_step_cap`, `max_steps_reached`,
`user_stopped` and `tool_choice` against `refs/pull/4028/head`.

**Review findings from amd#4028 are all addressed in the replicated
commits.** The `user_stopped` guard (declining "Continue with 50 more
steps?" no longer fires the wrap-up call) landed in `429de6a48`, and the
Claude structural fix (keep the tools, send `tool_choice="none"`) in
`50aa38fb0`.

- The closing call goes through the loop's own path:
`self.chat.send_messages` or `send_messages_stream`, with the loop's
`messages` plus one user instruction, the same system prompt, the same
tools, and `tool_choice="none"`. Tools stay because Anthropic rejects
tool_use/tool_result history on a request with no tools. A model without
native tool calling sends no tools and no `tool_choice`.
- `tool_choice` is a new explicit parameter on `LemonadeProvider.chat`,
`ClaudeProvider.chat` and `LemonadeClient.chat_completions`. Both raise
if it comes without tools; Claude maps `"none"`/`"auto"` and raises on
anything else.
- `_generate_max_steps_message` looked for OpenAI-style `tool_calls` on
assistant entries, which GAIA's `conversation` never contains, so the
"tools used" list was always empty. It now counts `role: tool` entries.
- The closing call counts as one more step, so the CLI shows "Processing
stopped after 51/50 steps" at the cap. `max_steps_reached` is new on
every result.

**Stacking.** amd#3908 is merged. amd#4035 sits on top of this PR and
generalises the closing call to the loop-guard path (`_closing_answer`);
it will need retargeting onto this branch once this lands.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
amd#4373 landed this PR's step-cap half on main (replicating amd#4028), and amd#3908
merged as a squash, so both of this branch's stacked parents are now upstream.
Nine conflicts in agent.py, all in the code the two changes share:

- `_answer_at_step_cap` → `_closing_answer(messages, conversation, instruction,
  step)`. This PR generalises the method so the loop-guard path can reuse it;
  the step-cap call site now passes `_STEP_CAP_ANSWER_PROMPT` as the
  instruction. Same request, same prompt.
- `max_steps_reached` keeps main's `user_stopped` term. That is this PR's own
  first review finding — declining "Continue with 50 more steps?" or pressing
  Ctrl-C must not fire another model call — and amd#4373 fixed it while this
  branch was open.
- Both loop-guard call sites drop main's `_build_loop_break_summary`
  assignment: `_answer_after_repeated_calls` builds that summary itself and
  returns it for repeats that failed or were refused.
- `_build_loop_break_summary` keeps the extracted `_repeats_carry_a_failure`
  predicate over main's inline condition; they are equivalent, and `denied` is
  still used further down.
- `min_context_size`'s docstring takes main's wording, which describes the
  resolver that is now in place.

The closing answer is now printed, not just returned. The normal and step-cap
paths call `print_final_answer` where they set `final_answer`; the loop guard
returned its answer and broke out, so on the CLI — where the console is the
only thing that prints — the turn ended on the repeat warning and the answer
this path exists to produce was never shown. Confirmed by driving a real
loop-guard break: `print_final_answer` was called zero times while the answer
sat in `result["result"]`, which is why every existing test missed it. The
post-loop block mirrors the step-cap one, so the printed text carries its
verification-scope line and the turn record is sealed before it prints.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…4035)

An agent that finished a task and then re-ran the same check a few times
used to have its answer thrown away: the user got "I stopped after
calling `run_python` 3 times in a row without making progress, so I
can't confirm the task is finished" on runs where the code had been
changed, documented, and pytest had passed — the verification line on
that same answer said "verified — pytest ran and passed". A judge scored
one of those tasks 3.00 against Claude Code's 4.75, the largest quality
gap left in the suite. The agent now answers from the work it actually
did; repeats that failed or were refused still report the failure,
because there the failure is what the user needs to hear.

Stacked on amd#4028 and amd#3908, merged in that order (main → amd#4028 → amd#3908 →
this), so the diff here includes both until they land. Together the
guard corrects once in place of the repeated call and only ends the turn
on the next identical call — that closing turn is what this PR changes.

## Test plan

- [ ] `python -m pytest tests/unit/agents/test_loop_break_answer.py
tests/unit/agents/test_loop_guard_correction.py
tests/unit/agents/test_step_cap_final_answer.py
tests/unit/agents/test_loop_break_truthful.py -q` — closing answer on
both tool paths after the correction round, error/refused repeats
unchanged, failure and cancel handling
- [ ] `python -m pytest tests/unit/agents -q` (1056 passed locally on
the merged tree)
- [ ] `gaia eval agent --category tool_selection` shows no regression
against the committed baseline — not run here

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

- The step-limit closing call was generalised to
`_closing_answer(messages, conversation, instruction, step)`; the
step-limit and loop-guard paths differ only in the instruction they
pass. Both loop-guard call sites (native fan-out and legacy
embedded-JSON) go through `_answer_after_repeated_calls`, which returns
`(answer, steps_taken)` and `(None, …)` when the user pressed Stop.
- Merge resolution at both call sites: `if current_call not in
loop_corrected_calls: … continue` first, then
`print_repeated_tool_warning()` followed by
`_answer_after_repeated_calls(...)` with `consecutive_count - 2` — the
calls that actually ran, the same number `_build_loop_break_summary`
reports.
- The gate is `_repeats_carry_a_failure`: an errored or `status:
"denied"` last result keeps `_build_loop_break_summary`, so amd#3908's
rate-limited / not-permitted / dead-service wording is untouched.
`_build_loop_break_summary` now calls that predicate instead of
repeating the condition.
- The guard stops mid-fan-out, which leaves an assistant tool-call turn
with no result for the call it stopped — Anthropic and other spec-strict
providers reject that outright. `_unanswered_tool_call_messages` answers
every dangling id with "Not run — the turn stopped before this call"
before the closing request goes out, and a test asserts the outgoing
message list accounts for every id (the correction message answers its
own id, so only the stopping call needs sealing).
- On failure the behaviour mirrors the step-limit path: warn, and return
the existing notice with one line saying why the summary couldn't be
written. A reply that asks for a tool instead of answering counts as a
failure.
- The extra call counts as a step and its stats land in `conversation`,
so tokens are aggregated as usual. The verification-scope line is still
appended once, post-loop.
- Both call sites pass `recent_results` (from `previous_outputs`), never
`step_results`, which error recovery clears before every retry — a
legacy-path test fails if that is swapped back.
- amd#3908's own `test_repeat_after_the_correction_ends_the_turn` needed no
change: its repeats return an error, which stays on the summary branch.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Ovtcharov <[email protected]>
Co-authored-by: probe <probe@local>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants