Repository navigation
fix(agent): answer from the work done when the loop guard stops - #4035
Conversation
Request changesThis makes an agent that ran out of steps — or got stopped for repeating one tool call — actually say what it found, instead of a canned "I can't confirm the task is finished". The idea and the implementation are sound, and the tests are genuinely good. Three things to settle before merge. Stopping the run yourself now triggers one more model call. When an interactive run hits the step limit, GAIA asks "Continue with 50 more steps?". Answering no — or pressing Ctrl-C at that prompt — now goes on to make an extra call to the model before returning, and the run is reported as having hit the step limit even though the user is what stopped it. Answering no getting a summary is arguably fine; a Ctrl-C should return immediately. The repeated-call path may never show its new answer. The step-limit path hands its answer to the console; the loop-guard path doesn't. On the CLI the console is the only thing that prints, so the answer this PR exists to produce can reach the user only as raw streamed text (without the verification line), or not at all when streaming is off. Worth confirming on a real run — if it's a gap, the fix is making both paths end the same way. The eval wasn't run. This changes the agent loop and adds two new model-facing prompts, which is exactly the case CLAUDE.md says must not merge without Real-world evidenceN/A — no evidence bundle was produced for this run, and the PR description carries no CLI transcript; the test-plan boxes are unchecked and the eval is marked "not run here". I also couldn't execute the new tests in this environment (no pytest available), so this verdict rests on static review alone. The change is user-visible on the CLI and Agent UI, so the natural evidence is a short 🔍 Technical details🟡 Important1. Declining the continue prompt still fires the closing call (
2. The step-cap branch does 3. No eval run for an LLM-affecting change (CLAUDE.md → "Run agent evals when changing LLM-affecting code paths") Two new model-facing prompts ( 🟢 Minor4. A refused tool gets a message that never mentions the refusal (
Strengths
|
…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.
A turn stopped for repeating one tool call threw away everything the agent had already done. 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 read "verified — pytest ran and passed". A judge scored one such task 3.00 against Claude Code's 4.75. The guard now makes the closing call the step limit already makes: the loop's own tools with tool_choice="none", asking the model to answer from the results it has — what it completed, what it could not confirm, what to do next. Repeats that errored or were refused keep today's message, because there the failure is the evidence. If the closing call fails or asks for a tool instead of answering, the old notice comes back with a line saying why, and a warning is logged. Both the native and legacy tool paths go through the same helper, the extra call counts as a step and its tokens, and any call the guard stopped mid-fan-out is answered in the transcript so spec-strict providers don't reject the request.
…nswer With the loop-guard correction in place a repeated call no longer ends the turn on the spot: the model gets one correction and only the next identical call stops it. The scripts now drive that extra round, and assert the closing call is told how many calls actually ran — two of the four, since the last two were never dispatched. A refused repeat now reads "not permitted here" rather than the generic notice, which is the summary doing its job, so the parametrised case expects that text. The two prose docs describing the guard gained the correction round.
Error recovery clears step_results before every retry, so a loop of failing calls on the embedded-JSON path reads as a clean run if the closing answer is handed that list — and the user gets a cheerful summary of a turn that failed every time. Reintroducing the swap fails this test.
6ec6c96 to
23de8e3
Compare
|
This PR is the top of a three-PR stack — #3908 and #4028 both have to merge before it. Both of their commit sets are already inside this branch, but all three PRs say Order: #3908 → #4028 → #4035, as merge commits rather than squashes. 🔍 Technical details
The bases can't be retargeted as-is — both parent branches exist only on the This PR rewrites 479 lines of |
# Conflicts: # src/gaia/llm/providers/claude.py
…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.
|
This PR is no longer a stack, and it is not redundant with #4373. Both of its parents are upstream now — #3908 squash-merged, and #4028 landed as #4373 — so what is left is only this PR's own work: the loop-guard half. #4373 handled the step cap; this handles the loop guard. Different trigger, and #4373's own description says so: "#4035 sits on top of this PR and generalises the closing call to the loop-guard path." The two are complementary, and the overlap is real but mechanical: this PR generalises the method #4373 added rather than adding a second one. Merged One correction to the framing in the review request: there is no A real defect fell out of the merge review: the answer was never printed. The step-cap and normal paths call 🔍 Technical detailsThe stack, resolved. Nine conflicts, all in
The print gap — fixed. Three tests pin it — native path, legacy embedded-JSON path, and the failed-repeat summary branch — each asserting Validation. Still open, unchanged: |
The email agent would have repeated its own grounding corrections when the loop guard ended a turn: four of its guards append a notice rather than replace the text, and the answer passed through finalize_answer twice — once where the closing reply was built, again in the post-loop print. A user who hit the guard on a calendar or invite question would have seen the same correction printed two times. The closing reply now comes back raw, like the failure-branch summary already did, so the post-loop block is the single place that finalizes. Both branches behave the same way, and a regression test pins the count at one.
|
Merged. The eval the review asked for was run as an A/B against main on the same backend, and one extra defect was found and fixed on the way in. The eval is a non-regression check here, not a test of the new path: the repeat guard never fired in any of the 14 scenario runs, so the code this PR changes did not execute. Scores were 8.5 (main) vs 8.4 (PR) with mixed per-scenario movement in both directions — retrieval and judge variance, not a signal. The defect: when the guard ended a turn, the answer went through the agent's post-processing hook twice. The base hook does nothing, but the email agent grounds its answer there and four of its guards append a correction rather than replace the text — so a user who hit the guard on a calendar or invite question would have seen the same correction printed twice. The closing reply now comes back raw and the post-loop block finalizes it once, with a test pinning the count. 🔍 Technical detailsEval — Fix — Merge — reconciled against Review items — the Ctrl-C finding was resolved upstream by the |
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_python3 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 #4028 and #3908, merged in that order (main → #4028 → #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 handlingpython -m pytest tests/unit/agents -q(1056 passed locally on the merged tree)gaia eval agent --category tool_selectionshows no regression against the committed baseline — not run here🔍 Technical details
_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.if current_call not in loop_corrected_calls: … continuefirst, thenprint_repeated_tool_warning()followed by_answer_after_repeated_calls(...)withconsecutive_count - 2— the calls that actually ran, the same number_build_loop_break_summaryreports._repeats_carry_a_failure: an errored orstatus: "denied"last result keeps_build_loop_break_summary, so fix(agent): the loop guard corrects before it stops, and names the real cause #3908's rate-limited / not-permitted / dead-service wording is untouched._build_loop_break_summarynow calls that predicate instead of repeating the condition._unanswered_tool_call_messagesanswers 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).conversation, so tokens are aggregated as usual. The verification-scope line is still appended once, post-loop.recent_results(fromprevious_outputs), neverstep_results, which error recovery clears before every retry — a legacy-path test fails if that is swapped back.test_repeat_after_the_correction_ends_the_turnneeded no change: its repeats return an error, which stays on the summary branch.