Repository navigation
fix(agent): answer from what it found when the step limit runs out - #4028
kovtcharov wants to merge 7 commits into
Conversation
Request changesGood 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 evidenceN/A — no evidence bundle was produced for this run, and 🔍 Technical details🟡 Important1. User-declined continuation falls into the step-cap wrap-up (
With 2. The wrap-up call is structurally invalid on the Claude provider (
3. Eval + live-model verification not run
🟢 Minor
Strengths
|
|
🟡 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 🔍 Technical details
max_steps_reached = final_answer is None and not cancelled_by_console
Fix from the prior review: add max_steps_reached = final_answer is None and not cancelled_by_console and not user_stoppedSilent-mode |
|
Checked against a live server: Lemonade proxying |
…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.
34c2be5 to
50aa38f
Compare
|
🟡 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 The 🔍 Technical details
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 max_steps_reached = final_answer is None and not cancelled_by_console and not user_stoppedWith |
|
This PR is stacked on #3908 — that one has to merge first. Its commit is already inside this branch, but both PRs say Order: #3908 → #4028 → #4035, as merge commits rather than squashes — a squash here rewrites the shared commit and conflicts both neighbours. 🔍 Technical details
The base can't be retargeted as-is — This PR rewrites 352 lines of |
# 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]>
|
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 #4035 is stacked on this branch and will need retargeting onto #4373. |
…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]>
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.
…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]>
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
ghcall; 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 fixpython -m pytest tests/unit/test_claude_provider.py tests/unit/test_lemonade_tool_choice.py:tool_choicemapping, validation, and the request body on both Lemonade pathspython -m pytest tests/unit: no new failures against main (the remaining failures are environment-only and fail on main too)gaia eval agent --category tool_selectionshows no regression against the baselinetool_choice="none"with tool-call history in the request🔍 Technical details
self.chat.send_messagesorsend_messages_stream(chosen byself.streaming), with the loop'smessagesplus one user instruction, the same system prompt, the same tools, andtool_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 notool_choice, as in the loop. The closing call counts as one more step, and its stats land inconversation, sosteps_takenand the token totals include it.tool_choiceis a new explicit parameter onLemonadeProvider.chat,ClaudeProvider.chatandLemonadeClient.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 iftool_choicecomes without tools._parse_llm_response,finalize_answerand_with_verification_scope, thenprint_final_answer, like any other answer. Status staysincomplete(orfailedwhenerror_historyis non-empty, as before).max_steps_reachedis new on every result._cancel_eventskips the call and names that as the reason. Agent UI Stop during the closing stream ends the turn ascancelledwith empty text, as fix(ui): Stop doesn't abort in-flight chat generation — cancel only observed at step boundaries #2157 requires._generate_max_steps_messagelooked for OpenAI-styletool_callson assistant entries, which GAIA'sconversationnever contains. It now countsrole: toolentries, which every execution path writes once per call that ran.