Skip to content

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

Merged
kovtcharov-amd merged 3 commits into
mainfrom
replicate/answer-from-step-limit-4028
Sep 25, 2026
Merged

kovtcharov-amd merged 3 commits into
mainfrom
replicate/answer-from-step-limit-4028

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

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 #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

  • 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
  • python -m pytest tests/unit/agents — 1511 passed, 50 skipped, 0 failed
  • 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)
  • 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 fix(agent): answer from what it found when the step limit runs out #4028
  • Live step-capped run on NPU/FLM — the Lemonade half was confirmed on fix(agent): answer from what it found when the step limit runs out #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
🔍 Technical details

Replication method. #4028 was stacked on #3908, which main squash-merged as 69fc540b5. A plain merge would re-apply #3908's fork commit on top of its own squash, so instead the three commits that are #4028's own work were cherry-picked onto main: 2dc1e47d7, 50aa38fb0, 429de6a48. #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); #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 #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. #3908 is merged. #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.

kovtcharov and others added 3 commits September 25, 2026 13:10
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.
…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]>
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes agents labels Sep 25, 2026
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into main with commit 52c373f Sep 25, 2026
52 of 61 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the replicate/answer-from-step-limit-4028 branch September 25, 2026 20:32
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

The one red check, Unit Tests (Windows smoke), is not from this change — every PR opened in the last hour fails it on the same test.

🔍 Technical details

tests/unit/chat/ui/test_toctou.py::TestSafeOpenDocument::test_safe_open_rejects_symlinked_directory_escape — Failed: DID NOT RAISE HTTPException. Same failure on claude/lemonade-one-resolver (job 108234594830), replicate/lemonade-stop-without-killing-caller-4263 and claude/qwen38-flash-default, none of which touch src/gaia/ui. This PR touches the agent loop and the LLM providers only. The test skips locally where the runner lacks symlink privilege, so it looks like a runner-image change rather than a source regression.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions — no blocking issues.

A step-capped run now ends with the agent actually saying what it found and what it couldn't finish, instead of a canned notice whose "tools used" list was always empty. The closing model call reuses the loop's own path with the tools kept and calling them forbidden, which is the right shape, and it's backed by tests that assert the real request body rather than "a method was called."

Two things worth a look before this pattern spreads further:

  • When the closing call fails, a CLI user sees nothing. The fallback notice ("here's the limit, here's why the summary couldn't be written") is returned to callers but never printed, so on the command line a failed closing call shows only an error log and an empty turn. That matches the old behaviour, but it isn't what the PR promises the user gets.
  • The closing call has no room to shrink. It resends the whole conversation plus every tool definition, and unlike the loop it can't trim and retry when the context is full. The runs most likely to exhaust 50 steps are also the ones closest to the ceiling, so the feature may fall back to the canned notice exactly where it's needed most.

Real-world evidence

The evidence bundle reports that the harness errored before producing evidence, so it certifies nothing. The stage did leave partial artifacts in the tree (test-runs/); relayed as data, they show the change working on the CLI path:

Before (base) vs after (this PR), same scripted scenario, step limit reached:

BASE_cap  (pre-PR)  → 3 model calls, run ends with no answer text at all
A_cap_answer (PR)   → 4 model calls, ends with:
  🧠 gaia: I ran out of steps before finishing. What I found: the directory holds
  violet-otter-92-notes.txt. What I could not finish: reading it, because the step
  limit ran out first. What you can do next: re-run with --max-steps 20.

Request bodies captured on the wire (wire.jsonl), confirming the closing call keeps the tools and forbids calls, on both transports:

A_cap_answer     4 requests  #1-3 tool_choice=<absent> tools=55 stream=False
                             #4   tool_choice=none     tools=55 stream=False
C_cap_streaming  4 requests  #4   tool_choice=none     tools=55 stream=True
D_answer_before_cap 2 requests — answered before the cap, no extra call

Failure path (B_cap_call_fails, backend 500 on the closing call) reproduces finding 1: the log shows Could not write the step-limit summary: ... status 500, and stdout ends with no answer.

Not exercised here: the HTTP API scenario aborted (No module named 'uvicorn'), and there is no Agent UI screenshot — pending the strix-halo lane. The verdict for those surfaces rests on static review alone.

🔍 Technical details

Issues

🟡 Failed closing call never reaches the console (src/gaia/agents/base/agent.py:8055)

The except branch sets final_answer to _generate_max_steps_message(...) + "The summary … couldn't be written: {e}", but only the success branch calls self.console.print_final_answer(...). Callers that read result["result"] (API, UI) get the notice; a CLI turn ends silent. test-runs/B_cap_call_fails/cli.txt shows this: agent.py:8056 | Could not write the step-limit summary: … status 500 and then nothing. Printing the fallback the same way the success branch prints its answer would close the gap.

🟡 No overflow recovery on the closing call (src/gaia/agents/base/agent.py:4493)

_answer_at_step_cap sends messages + [instruction] with the full self._openai_tools, and the loop's trim-and-retry (_shrink_messages_for_overflow, used at agent.py:6317 / 6469) doesn't apply. A context-overflow error raises, gets caught, and degrades to the canned notice — loud and explained, so not a correctness bug, but the degradation correlates with long runs, which are the ones that hit the cap. Worth reusing the loop's retry here (or in the _closing_answer generalization #4035 is planning).

🟢 Final-answer event under-reports tokens at the cap (src/gaia/agents/base/agent.py:8071)

_cap_input_tokens is computed and dropped, and cached_tokens isn't passed, so the cap's final-answer event carries output tokens only while the normal path at agent.py:7990 carries all three.

                    _cap_input_tokens, cap_output_tokens = _sum_conversation_tokens(
                        conversation, self._tool_reported_usage
                    )
                    turn_record = self._finish_turn_record(final_answer, steps_taken)
                    self._publish_turn_metrics(turn_record)
                    self.console.print_final_answer(
                        final_answer,
                        streaming=self.streaming,
                        total_tokens=cap_output_tokens,
                        input_tokens=_cap_input_tokens,
                        cached_tokens=_sum_cached_tokens(conversation),
                        ttft_seconds=_query_ttft_seconds(conversation),
                        tok_per_s=_query_tok_per_s(conversation),
                    )

🟢 max_steps_reached is False when the user declines more steps (src/gaia/agents/base/agent.py:8042)

docs/spec/agent-base.mdx documents the field as "Hit the step limit before answering," but user_stopped suppresses it — an interactive run that reached the cap and declined Continue with 50 more steps? reports False with no answer. Skipping the closing call there is right (that's what 8aba0adc fixed); the flag just no longer matches its documented meaning. Either widen the flag and gate only the call on user_stopped, or reword the spec line.

🟢 Duplicated call plumbing — _answer_at_step_cap re-implements the loop's streaming/non-streaming branch, stats append, <think> strip and parse. Fine as a first cut given #4035 generalizes it to _closing_answer; worth landing that soon so the two copies can't drift.

Strengths

  • The provider tests assert what goes over the wire (responses for the non-streaming body, a real OpenAI client over httpx.MockTransport for the streaming one) rather than that a mock was called — exactly the boundary-validity gap CLAUDE.md calls out from gaia init --profile npu fails with status 400 (missing user. prefix for model name) #1655.
  • tool_choice fails loudly and identically at all three layers when passed without tools, and the Claude provider rejects anything it can't faithfully map instead of silently approximating it.
  • Real bug fixed in passing: _generate_max_steps_message was scanning assistant entries for OpenAI-style tool_calls, which GAIA's conversation never carries, so the "tools used" list was always empty. Counting role: tool entries is right and is covered by a test.
  • The keep-the-tools-and-send-tool_choice: none shape is the correct resolution for Anthropic's rule that tool history requires a tools array — and the JSON-protocol path correctly sends neither.

kovtcharov-amd added a commit that referenced this pull request Sep 25, 2026
One conflict, in the turn's result status. `main` (#4373) made a
step-capped turn report "incomplete" even when the closing call answered;
this branch made a turn with completion gaps report "incomplete" too.
Both conditions kept, with the branch's errors-first ordering: "success"
now needs a valid answer, no completion gaps, and no step cap.
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.
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