Skip to content

feat(agent): keep the model's reasoning and send it back within a request - #4055

Merged
kovtcharov-amd merged 11 commits into
amd:mainfrom
kovtcharov:feat/keep-model-reasoning
Sep 28, 2026
Merged

kovtcharov-amd merged 11 commits into
amd:mainfrom
kovtcharov:feat/keep-model-reasoning

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

GAIA threw away almost everything a reasoning model wrote. On one DeepSeek call, 91% of the output tokens were reasoning and the visible answer was 18 characters. So at every step of a tool-calling job, the model had to re-derive its plan from scratch, and a plan that existed only in its reasoning never reached the next step. When a reply had no visible text, GAIA did something worse: it handed the private reasoning to the user as the answer. Now reasoning is kept as its own field. It is recorded in the transcript, sent back to the model on each step of the same request (the provider's own guidance for thinking models that use tools), and never shown as the answer.

  • Earlier requests: reasoning from past user requests is kept but not sent again by default, so long conversations don't keep growing. resend_reasoning_across_requests=True turns that on. The owner may want it on.
  • Checked with a real call: one request through the Lemonade gateway to fireworks.deepseek-v4p1-flash, in a tool-call loop, sent back an assistant turn carrying reasoning_content. It was accepted and the model answered coherently. The prompt grew by 27 tokens for 117 characters of reasoning, which shows the reasoning reaches the model rather than being dropped.
  • Cost: each step's prompt grows by roughly that step's reasoning. On the TheRock benchmark, replies averaged about 1,000 tokens, mostly reasoning, so a 30-step job carries on the order of 30K extra prompt tokens by the end. Most of that is a cached prefix.
🔍 Technical details
  • LLMClient.get_last_reasoning() and accepts_reasoning_history are added, and LemonadeProvider implements both. The SDK attaches reasoning_content to assistant history only for a provider that accepts it, so OpenAI and LiteLLM never receive the field, and Claude's message translation already drops unknown keys.
  • Inline <think> blocks go into the same field as reasoning_content, including an unclosed block (a reply cut off mid-thought) and a lone </think> (the chat template opened the block in the prompt).
  • The Claude provider doesn't turn on extended thinking. It does drop any thinking blocks it gets back, so it would have the same gap if thinking were enabled. That provider is not changed here.
  • Callers that rebuild conversation_history from the UI database (ui/_chat_helpers.py, ui/agent_loop.py) store only the answer text, so the setting has no effect in the Agent UI until they store reasoning too.
  • fix(agent): continue a reply cut off by the token limit instead of ending on it #4054 (continue a cut-off reply) pairs with this change. With both merged, a reply cut off while the model is still thinking is continued with its reasoning intact. Neither PR depends on the other.

Test plan

  • pytest tests/unit/agents/test_model_reasoning_kept.py. Reasoning from reasoning_content and from inline <think> blocks is stored and kept out of the answer. Within a request, the next call carries the previous step's reasoning. Across requests it is not resent by default and is resent with the setting on. Ten of these tests failed before the change.
  • pytest tests/unit/agents tests/unit/chat tests/unit/test_claude_provider.py tests/unit/test_streaming_tool_calls.py tests/unit/test_tool_call_priority.py
  • One real tool-call round trip through the Lemonade gateway with reasoning_content sent back (see above)
  • gaia eval agent --category tool_selection
  • gaia eval agent --category rag_quality

…uest

GAIA threw away almost everything a reasoning model wrote. The provider read
reasoning_content only when a reply had no text (and then passed it off as
the answer), and the loop deleted inline <think> blocks. On one DeepSeek call
91% of the output tokens were reasoning, so every step of a tool-calling job
re-derived its plan from scratch.

Reasoning now travels as its own field: the provider returns it apart from
the answer, the transcript records it on each assistant step, and each step's
reasoning goes back to the model as reasoning_content on its assistant
message for the rest of the request. Reasoning stored from earlier user
requests is not resent unless resend_reasoning_across_requests is set.
Providers that reject the field (OpenAI, LiteLLM) never receive it.
@github-actions github-actions Bot added documentation Documentation changes chat Chat SDK changes llm LLM backend changes tests Test changes performance Performance-critical changes agents labels Sep 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

Keeping the model's reasoning as its own field instead of deleting it is the right call, and the layering (provider captures it, SDK only forwards it to backends that accept it, agent replays it within a request) is clean. Two edges in the parsing change need fixing before merge, and the required agent evals haven't been run.

What needs attention:

  • An answer that merely mentions a <think> tag loses everything after it. The new splitter treats any unclosed <think> as "the reply was cut off mid-thought", so a normal reply that happens to write that tag — explaining a chat template, quoting a prompt — is silently truncated at that point. Only treat an unclosed block as reasoning when it opens the reply.
  • A reply whose text arrives only in the reasoning field now reaches the user as "I received an empty response." The old code used that field as the answer when there was no other text, with a comment saying some local server builds put it there. That safety net is gone with nothing in its place. Worth deciding deliberately: when the model finished normally, produced no tool call and no visible text, that text really is the answer.
  • The agent evals in the test plan are unchecked. This change alters how every reply is split and parsed before the tool-call parser sees it, which the project's own rules put squarely in "must run an eval and compare to the baseline before merge."

One thing to confirm rather than change: the flag saying "this backend accepts reasoning in the history" is set for the whole local-inference provider, but that provider also points at any OpenAI-compatible URL a user configures. A strict server would reject the extra field on the second step of every tool-calling job — the same rejection the change is designed to avoid for other providers.

Real-world evidence

N/A — no evidence bundle was produced for this run (no runnable-surface artifact present), so the verdict rests on static review plus reading the tests. The PR describes one real tool-call round trip through a Lemonade gateway to a DeepSeek model with reasoning_content accepted, but the request/response itself isn't captured in the description, and both gaia eval agent items remain unchecked. I could not run the unit suite here — pytest isn't installed in this environment — so the test results are the author's, not reproduced.

🔍 Technical details

Issues

🟡 Unclosed <think> anywhere in the reply truncates the answer (src/gaia/agents/base/agent.py:31-47)

_THINK_BLOCK_PATTERN matches <think>(.*?)(?:</think>|\Z), so the \Z branch fires for a bare <think> at any offset. Verified against the actual function:

'Use the `<think>` tag like this in your prompt.'
  -> answer='Use the `', reasoning='` tag like this in your prompt.'

The previous re.sub(r"<think>.*?</think>", ...) left that text intact — only balanced pairs were stripped. The truncated-reply case this was written for always has the block at position 0, so anchoring it keeps the intended behaviour and drops the false positive:

_THINK_BLOCK_PATTERN = re.compile(r"<think>(.*?)</think>", re.DOTALL)
_UNCLOSED_THINK_PATTERN = re.compile(r"^<think>(?!.*</think>)(.*)\Z", re.DOTALL)


def _split_reasoning(text: str) -> Tuple[str, Optional[str]]:
    """Split inline ``<think>`` reasoning out of a reply.

    Returns ``(answer_text, reasoning)``. A reply that *opens* with an
    unclosed ``<think>`` was cut off mid-thought and is all reasoning, and
    text before a lone ``</think>`` (the template opened the block in the
    prompt) is reasoning.
    """
    parts: List[str] = []
    if "</think>" in text and "<think>" not in text.split("</think>", 1)[0]:
        head, _, text = text.partition("</think>")
        parts.append(head.strip())
    cut = _UNCLOSED_THINK_PATTERN.match(text.lstrip())
    if cut:
        parts.append(cut.group(1).strip())
        text = ""
    parts.extend(m.strip() for m in _THINK_BLOCK_PATTERN.findall(text))
    answer = _THINK_BLOCK_PATTERN.sub("", text).strip()
    return answer, "\n\n".join(p for p in parts if p) or None

🟡 Removing the reasoning_content content fallback has no replacement path (src/gaia/llm/providers/lemonade.py:503)

content = message.get("content") or "" drops a fallback that has been in this provider since before #865, documented as "some llama.cpp builds put text in reasoning_content instead of content". When that happens now, chat() returns "", _parse_llm_response takes the empty-response branch (agent.py:3397-3444) and the user gets the apology string — the answer is lost, not merely hidden. The streaming path already behaved this way, so this does make the two consistent; the question is whether consistency should be "both drop it" rather than "both recover it".

A narrow, non-silent recovery keeps the PR's invariant (reasoning is never the answer for a truncated reply) while not losing a complete one — the discriminator is finish_reason:

        content = message.get("content") or ""
        if not content and finish_reason == "stop" and self._last_reasoning:
            # A completed reply with no ``content``: this build routed the
            # answer into ``reasoning_content``. Truncated replies ("length")
            # are left empty on purpose — that text is a thought, not an answer.
            logger.warning(
                "Lemonade returned an empty 'content' with finish_reason=stop; "
                "using 'reasoning_content' as the answer (model=%s)",
                effective_model,
            )
            content = self._last_reasoning

🟡 Agent evals required by CLAUDE.md are unchecked

CLAUDE.md → "Run agent evals when changing LLM-affecting code paths" names "Tool-call response parsing / native-tool-call sentinel handling" explicitly, and this PR changes both what reaches _parse_llm_response and what the envelope's content holds on a tool-call reply (lemonade.py:491-498). Please run gaia eval agent --category tool_selection and --category rag_quality serially and compare against tests/fixtures/eval_baselines/<model>/scorecard_*.json.

🟡 accepts_reasoning_history is provider-wide, not endpoint-aware (src/gaia/llm/providers/lemonade.py:300)

LemonadeProvider is also what serves a user-supplied LEMONADE_BASE_URL / skip_lemonade=True OpenAI-compatible backend (the base Agent docstring says as much). By the reasoning in base_client.py:18-20, such a server may 400 on reasoning_content in an assistant message — and _build_assistant_message attaches it on every step of a tool-calling job, so the failure would be step 2, not step 1. Local llama.cpp tolerates it, so this won't show up in the default path. Maintainer call: gate on the base URL, or document the constraint.

Nits

🟢 BuilderAgent has its own history load that ignores the new flag (src/gaia/agents/builder/agent.py:305-306)

messages.extend(self.conversation_history) is the duplicate of the branch you changed at agent.py:5335-5342, so for this agent earlier-request reasoning would always be resent. Latent today (nothing writes reasoning_content into conversation_history yet), but it will drift.

🟢 AgentResponse docs don't list the new field (docs/spec/agent-sdk.mdx:71, docs/sdk/sdks/chat.mdx:49)

Both copies of the dataclass are already missing usage; reasoning makes it two fields out of date. Per CLAUDE.md, a change to a documented surface updates every doc that describes it:

@dataclass
class AgentResponse:
    """Response from chat operations."""

    text: str
    history: Optional[List[str]] = None
    stats: Optional[Dict[str, Any]] = None
    is_complete: bool = True
    usage: Optional[Dict[str, Any]] = None
    reasoning: Optional[str] = None  # the model's reasoning, kept apart from text

🟢 The unclosed-<think> test only asserts a negative (tests/unit/agents/test_model_reasoning_kept.py:704-714)

assert "Still working" not in answer passes whether the loop recovers with the second stubbed reply or dead-ends on the empty-response apology — which is exactly the distinction that matters for the finding above. Asserting the answer equals "It says hello." (and that both stubbed replies were consumed) would pin the intended behaviour.

Strengths

  • The provider/SDK/agent split is the right shape: accepts_reasoning_history as a client capability means Claude, OpenAI and LiteLLM never see the field without anyone special-casing them at the call site.
  • Resetting _last_reasoning at the top of chat() rather than inside the stream generator means the value is per-call even when a stream is abandoned, and setting it before the tool-call sentinel is yielded is what makes the SDK's sentinel branch read a populated value.
  • resend_reasoning_across_requests defaulting to off — with the growth cost quantified in the PR body — is the conservative default for a change that silently inflates every prompt.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The core change is well-motivated and the implementation is solid — reasoning is correctly captured from both reasoning_content fields and inline <think> blocks, sent back within a job, and filtered out for providers that reject it. Tests cover the key paths. Two things are worth fixing before merge.


🟡 Required eval runs are unchecked in the test plan. tool_selection and rag_quality evals are marked unchecked in the PR description. CLAUDE.md requires these to run before claiming a change is done whenever the agent loop is touched — which this PR does. Reasoning carried forward changes what the model sees on each step, which is exactly the kind of LLM-affecting change evals are meant to gate. This is a policy requirement, not a suggestion.

🟡 The streaming agent loop has no test coverage for the new reasoning path. The new test file sets agent.streaming = False for all agent-level tests, so the streaming branch in agent.py (reading chunk_response.reasoning from the complete chunk, the streaming plan path, plan_reasoning collection) has zero new test coverage. A bug in that path would only show up in a real streaming call. The SDK-level streaming test (test_provider_keeps_streamed_reasoning) exercises the provider but not the agent loop orchestration.

🔍 Technical details

Eval gap: agent.py's process_query now includes reasoning_content in every assistant turn of the in-flight messages list. On a 30-step tool-calling job, the prompt grows by ~1 K tokens per step (per the PR). That changes LLM behavior in ways unit tests cannot catch — tool selection and plan quality can shift. The unchecked items:

[ ] gaia eval agent --category tool_selection
[ ] gaia eval agent --category rag_quality

Streaming test gap: agent.py:5806-5856 collects response_reasoning on the streaming path via:

if chunk_response.is_complete:
    response_reasoning = getattr(chunk_response, "reasoning", None)

and the plan streaming path (agent.py:6297-6313) is also uncovered. To add a streaming test, set agent.streaming = True in the agent fixture and pass _stub_chat a mock that yields AgentResponse chunks with is_complete=True carrying reasoning.

Everything else looks correct: the _split_reasoning edge cases (unclosed block, lone </think>) are handled and tested; the accepts_reasoning_history filter is in the right place in sdk.py; _last_reasoning in LemonadeProvider is reset at the start of each chat() call; and the **extra / dict-merge ordering in _build_assistant_message is safe.

@kovtcharov

kovtcharov commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Whichever of this PR and #4054 merges second needs one small follow-up. When a reply is cut off while the model is still thinking, its visible text is empty, so the continuation has to carry the reasoning or the model has nothing to continue from.

🔍 Technical details

In the cut-off branch of the loop, replace if response: messages.append({"role": "assistant", "content": response}) with:

if response or reasoning:
    messages.append(
        {"role": "assistant", "content": response}
        | ({"reasoning_content": reasoning} if reasoning else {})
    )

Add a test that replays a cut-off reply with empty text and reasoning, and asserts the continuation carries reasoning_content.

Ovtcharov and others added 3 commits September 21, 2026 12:16
A reply that merely mentioned `<think>` part-way through prose was cut at
that point, and everything the model said after it was silently deleted as
reasoning. Only a reply that *opens* with an unclosed block was ever cut off
mid-thought, so the pattern is now anchored there.

Also from review:

- Restore the reasoning_content-as-answer recovery for llama.cpp builds that
  route a finished reply into that field, gated on finish_reason="stop" so a
  reply cut off by the token limit still is not shown as the answer.
- Route BuilderAgent's history through a shared _history_for_request, so
  resend_reasoning_across_requests holds for every subclass rather than only
  the base loop.
- Document `usage` and `reasoning` on AgentResponse; both were missing from
  the SDK reference and the spec.
- Cover the streaming loop, which reads reasoning off the is_complete chunk
  only, and pin the mid-prose-mention regression.
# Conflicts:
#	src/gaia/agents/base/agent.py
…odes

The trace tests stubbed the chat response with a bare MagicMock, so
once this branch started carrying the model's reasoning forward,
getattr(response, "reasoning", None) returned an auto-created MagicMock
instead of None. That rode into the turn record as reasoning_content
and json.dump refused it, failing all ten tests in the file.

Priming reasoning=None on both stubs keeps them a faithful stand-in for
a backend that returns no reasoning. Production code is untouched.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

All nine red unit tests were one missing field in a test stub, not a problem with the change itself. Fixed and pushed; the file is green locally on 3.13.

The trace tests hand the agent a bare MagicMock as the chat response. Once this branch started carrying the model's reasoning forward, asking that mock for its reasoning got a mock back instead of nothing — and the trace file can't be written with a mock inside it. Priming the field keeps the stub an honest stand-in for a backend that returns no reasoning. No production code changed.

🔍 Technical details

getattr(chunk_response, "reasoning", None) in agent.py returns an auto-created MagicMock rather than None, which rides into the turn record as reasoning_content and then hits json.dump in _write_json_to_file → TypeError: Object of type MagicMock is not JSON serializable.

Both stubs in tests/unit/test_trace_tool_schema.py::_make_agent and in test_schema_matches_what_the_backend_was_handed now pass reasoning=None. Commit 464ef0263.

tests/unit/test_trace_tool_schema.py .......... 10 passed
+ tests/unit/agents/test_model_reasoning_kept.py, tests/unit/test_claude_provider.py → 70 passed

Other MagicMock(text=...) response stubs exist (test_memory_mixin.py, test_agent_tool_timeout.py, test_talk_voice_commands.py) but none serialize a turn record to JSON, so they are unaffected — test_agent_tool_timeout.py re-run clean to confirm.

# Conflicts:
#	docs/spec/agent-base.mdx
#	src/gaia/agents/base/agent.py
#	src/gaia/llm/base_client.py
#	src/gaia/llm/providers/lemonade.py
Three tests in tests/unit/agents/test_model_history.py broke once this
branch met current main: the agent loop read `.reasoning` straight off
the chat response, and the MagicMock stubs that drive most agent-loop
tests answer that with another MagicMock. It rode into the request
history as `reasoning_content`, where json.dumps cannot serialise it.

The same shape was patched once already in test_trace_tool_schema.py by
priming the stub. There are 14 such _stub_chat helpers under
tests/unit/agents/, so fixing them one at a time is a treadmill --
and any of them not asserting on serialised messages would keep
silently polluting the history. Normalise at the capture point instead:
AgentResponse.reasoning is Optional[str], so anything that is not a
non-empty string is no reasoning.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Resynced with main, and found one real bug in the process: this branch breaks three history tests that pass on main, because it was reading the model's reasoning off the chat response without checking it was text. Fixed, with the review's earlier findings re-verified as already closed.

The two evals remain open and I could not run them here.

The bug

Most agent-loop tests drive the agent with a bare MagicMock response that sets only .text and .stats. Ask such an object for its reasoning and you get another mock back — which this branch then attached to the assistant turn as reasoning_content. Anything that later serialises the conversation (a trace file, or a test asserting on what the model was sent) dies on it.

test_trace_tool_schema.py was already patched for exactly this by priming the stub. That fix doesn't generalise: there are 14 _stub_chat helpers under tests/unit/agents/ with the same shape, and the ones that don't serialise their messages were quietly sending a mock to the model instead of failing. So the fix belongs at the capture point, not in the stubs.

🔍 Technical details

The failures (tests/unit/agents/test_model_history.py, all green on main, all red on this branch pre-fix):

test_real_agent_returns_only_current_turn_with_tool_evidence
test_real_agent_max_steps_preserves_tool_evidence_and_actual_answer
test_legacy_tool_evidence_does_not_replay_as_orphan_native_result
  -> TypeError: Object of type MagicMock is not JSON serializable

The fix — one helper beside _split_reasoning, used at all four capture sites (agent.py:6532, :6692, :6986, :7028), replacing the raw getattr(..., "reasoning", None):

def _response_reasoning(response: Any) -> Optional[str]:
    value = getattr(response, "reasoning", None)
    return value if isinstance(value, str) and value else None

getattr stays because a response may genuinely lack the attribute; the added check makes the defensiveness type-complete rather than adding a fallback. AgentResponse.reasoning is declared Optional[str], so "not a non-empty string" means "no reasoning" — there is no case where a non-string here is meaningful data being discarded.

New tests (tests/unit/agents/test_model_reasoning_kept.py): no reasoning attribute at all, a MagicMock reasoning, ""/None, real text preserved verbatim, plus one full loop run through the same MagicMock stub the other suites use, asserting json.dumps on the sent messages succeeds.

Mutation check — reverting the helper body to the plain getattr:

FAILED test_a_non_string_reasoning_is_not_carried_into_the_request
FAILED test_an_empty_reasoning_is_no_reasoning[]
FAILED test_real_agent_returns_only_current_turn_with_tool_evidence
FAILED test_real_agent_max_steps_preserves_tool_evidence_and_actual_answer
FAILED test_legacy_tool_evidence_does_not_replay_as_orphan_native_result
5 failed, 31 passed

Merge. Two rounds (main moved mid-review). Conflicts in base_client.py, providers/lemonade.py, agents/base/agent.py, docs/spec/agent-base.mdx — every one was an independent addition on each side (this branch's get_last_reasoning / resend_reasoning_across_requests vs main's get_last_finish_reason, get_last_ttft_seconds, _last_streamed, max_output_tokens), so both sides were kept in each. No conflict markers left in the tree; every touched file AST-parses.

Earlier review findings, re-verified as already fixed on the branch:

  • Unclosed <think> mid-reply — _CUT_OFF_THINK_PATTERN is \A-anchored, so a <think> mentioned in prose no longer truncates the answer.
  • reasoning_content content fallback — restored in providers/lemonade.py, gated on finish_reason == "stop" with a warning log, so a completed answer routed there is recovered while a truncated thought is not.
  • BuilderAgent history — now goes through _history_for_request().
  • Both AgentResponse doc snippets list usage and reasoning.
  • Streaming loop coverage — agent.streaming = True at test_model_reasoning_kept.py:314.

Tests: tests/unit/agents tests/unit/chat tests/unit/test_streaming_tool_calls.py tests/unit/test_tool_call_priority.py tests/unit/test_trace_tool_schema.py → 2602 passed, 61 skipped. python util/lint.py --black --isort clean.

tests/test_lemonade_client.py fails 11 tests on this box (AssertionError: 8123 != 13305) — the known stale-Lemonade-port issue (#4281). Confirmed environmental: it fails identically with main's copies of those files checked out.

Open, and not mine to close:

  • gaia eval agent --category tool_selection and --category rag_quality — no Lemonade slot here, so I'm not merging.
  • accepts_reasoning_history is set for the whole Lemonade provider, which also serves a user-supplied OpenAI-compatible LEMONADE_BASE_URL. Still the maintainer call the first review raised: gate it on the base URL, or document the constraint.
  • Per the note on this PR, whichever of this and fix(agent): continue a reply cut off by the token limit instead of ending on it #4054 merges second needs the cut-off branch to carry reasoning_content — a reply cut off mid-thought has no visible text, so the continuation has nothing to continue from. Both are still open, so it isn't blocking either one yet.

…ning

# Conflicts:
#	docs/sdk/sdks/chat.mdx
#	docs/spec/agent-sdk.mdx
#	src/gaia/agents/base/agent.py
#	src/gaia/chat/sdk.py
#	tests/unit/test_claude_provider.py
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 28, 2026
Merged via the queue into amd:main with commit 2f08108 Sep 28, 2026
43 of 47 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the feat/keep-model-reasoning branch September 28, 2026 17:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents chat Chat SDK changes 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