Repository navigation
fix(agent): the loop guard corrects before it stops, and names the real cause - #3908
Conversation
|
Verdict: Approve with suggestions This fixes a real and well-diagnosed problem: the agent used to end a task after four identical tool calls and tell the user a service was down, even when nothing was down. Now a throttled call (which never ran) doesn't count as a repeat, the model gets one "try something else" nudge before the turn is killed, and the closing message names the actual cause. The legacy tool path also stops reporting "Task completed" on a loop of failures — that was reading a results list that error recovery had already emptied. Two things to look at before merging:
Smaller: the counts in both the nudge and the final message are one or two higher than the number of calls that actually executed, since the repeats that trigger the guard are never run. Real-world evidenceN/A — no evidence bundle was produced for this run. The change is internal to the agent loop with no CLI/API/UI surface of its own, so the automated lane had nothing to exercise; the behaviour it does change is user-visible in chat output, and that is exactly what the pending agent-eval run would cover. The verdict here rests on static review plus the unit tests in the PR. 🔍 Technical details🟡 ImportantWindows connection refusals classify as "not permitted" (
Worth a parametrized case in Agent eval not yet run (process, not a code line)
🟢 MinorRepeat counts overstate the calls that actually ran ( With Throttled calls are now fully exempt from the loop guard ( Popping from Stale parameter name (
Strengths
|
|
Verdict: Approve The loop guard now corrects before it stops, and rate-throttled calls no longer count as repeats — two clean, independently useful improvements that ship together naturally. No blocking issues. A few things worth noting for the record: The shared The correction message in the native path passes The The One note for the commit record: the correction message says "called N times" where N equals |
|
Verdict: Approve — the loop-guard correction mechanism is correct, well-scoped, and has thorough tests. The PR adds three things: a one-shot correction message before the loop terminates (giving the model one chance to change approach), rate-limit-aware repeat counting (throttled results don't advance the repeat counter), and better-categorized terminal summaries that name the real cause. The logic is sound. A few things I verified:
Tests in No security concerns. No silent fallbacks introduced. Scope is clean. |
|
Verdict: Approve with suggestions The loop-guard correction flow is sound — giving the LLM one chance to self-correct before hard-stopping is exactly the right UX, and counting only calls that actually ran prevents misleading "tried N times" messages. The new test file covers the correction flow, throttle handling, and all four terminal-summary categories (rate-limited, connection error, not-permitted, plain failure). The Windows socket-error fix ( 🟢 One nit: 🔍 Technical detailsThe
Both execution paths covered — the success branch (line ~6280) and the error branch (line ~6524) both get the throttle pop and the |
|
Verdict: Approve 🟢 The correction-before-termination logic is sound and the tests cover it well. No blocking issues found. Two small observations worth a look before merge: 🟡 🟢 🔍 Technical details
For context: the test suite only exercises |
|
Tool output that only mentions "blocked", like "unblocked 3 connections", is no longer reported to the user as "not permitted here". A repeat limit below 2 now fails when the agent is built, instead of producing a guard that never lets a tool run and a message saying "called X 0 times". Still open: the agent eval, which runs in the self-hosted CI job once a maintainer pushes this branch to amd/gaia. 🔍 Technical details
|
Both PRs change what happens when the guard stops a turn, so they have to agree on the order: correct once in place of the repeated call, and only on the next identical call end the turn — now with the closing answer instead of the canned notice. The summary stays for the error and refused branches, which is where its rate-limited / not-permitted / dead-service wording belongs. The count handed to the closing call is the calls that actually ran, the same number the summary reports, and the cleanliness check both sides need is one predicate now instead of two copies.
…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
7110edd to
41b17cf
Compare
|
Rebased onto current main as one commit. First in the turn-ending stack, nothing to merge before it; #4028 builds on this. |
|
Merge this one first — two other open PRs sit on top of it. #4028 and #4035 both already contain this PR's commit, but all three are marked Order: #3908 → #4028 → #4035, as merge commits rather than squashes. 🔍 Technical details
The bases can't be retargeted as-is — All three rewrite |
…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]>
After four identical tool calls, the agent ended the task and blamed a service outage. In a 168-run Fireworks benchmark the guard fired 6 times with no outage behind any of them: a throttle where none of the calls ran, a policy refusal, a bad argument, a 404, and a test script that exited non-zero. Two of those stops replaced a finished refactor's answer with "it kept failing … check that the underlying service is running." Now throttled calls don't count as repeats, the model gets one "try a different approach" correction before the guard stops it, and the final message names the real cause (rate-limited, not permitted, or the actual error — the service hint only for connection failures).
The legacy tool path also summarised every failing loop as "Task completed", because error recovery cleared the results it read; it now reads the same history as the native path.
Test plan
pytest tests/unit/agents/test_loop_guard_correction.py— throttled calls not counted (and the wait is capped/cancellable), correction injected before termination on both the legacy and native paths (native keeps itstool_call_id), and each summary variant: rate-limited, not permitted, connection, plain failure, last stderr line, return code; output that merely mentions "blocked" stays a plain failure; a repeat limit below 2 is refusedpytest tests/unit/agents/ hub/agents/gaia/python/tests hub/agents/chat/python/tests— 1540 passed; the 3 failures (tool-count goldens) fail onmainin the same environmentFixes #3888