Skip to content

Better handling of reasoning output from thinking models #1201

Closed

Description

@planetf1

Thinking models — Qwen3, DeepSeek-R1, Anthropic extended thinking, OpenAI o-series — have gone from niche to mainstream. Users working with them naturally expect multi-turn conversations to work: the model reasons about your question, you follow up, the model continues with that context intact. In mellea today that expectation is not met.

Mellea does capture reasoning output correctly for a single call — result._thinking (soon result.thinking via #909 Area 4) holds the reasoning trace after await session.aact(prompt). The problem surfaces the moment you try to continue the conversation. The reasoning from the first turn is silently discarded and never included in what is sent to the model on subsequent turns. From the model's perspective it has no memory of having thought about the first question at all.

This is a meaningful gap. As thinking models become the default choice for complex tasks, multi-turn reasoning continuity is a basic expectation. This issue proposes we fix that — but the fix is more involved than it first appears, and this issue is intended to share the analysis and invite discussion before work begins.

What a user experiences today

# Single call — works, reasoning is captured
result = await session.aact("Explain the halting problem")
print(result._thinking)   # reasoning trace present

# Follow-up — reasoning is gone; the model starts cold
context.add(result)
result2 = await session.aact("Now give me a concrete example", ctx=context)
# mot._thinking from turn 1 was never in the messages sent to the model

The user has no indication anything went wrong. The model simply answers without the context of its prior reasoning, often producing a weaker or disconnected response.

Why "just pass the reasoning back" is the wrong fix

Every major provider has published rules on what to do with prior reasoning in a follow-up turn — and they disagree. The dividing line is whether the prior assistant turn issued a tool call:

Provider No tool call on prior turn Tool call on prior turn
Qwen3 Strip it. The Jinja chat template does this automatically; passing stale thinking back degrades quality (not a hard error, but measurable). Include reasoning
DeepSeek-R1 Do not include it — hard 400 on deepseek-reasoner if reasoning_content is present in history Required — hard 400 if absent
Anthropic Optional (newer models keep it; older models strip it silently) Required, unmodified, with cryptographic signature — 400 if absent or modified
OpenAI Chat Completions: reasoning is never returned to the caller, nothing to pass back. Responses API: reasoning items are optional and discarded by the model anyway Responses API: required — the API errors without them

The universal pattern: every provider flips from "strip or ignore" to "must round-trip" the moment a tool call was involved. A blanket "always pass reasoning back" policy causes a hard error on DeepSeek without tools and degraded quality on Qwen3. This has to be a per-backend, per-turn decision.

Anthropic requires structured blocks, not a string

There is a second, deeper problem with Anthropic. Extended thinking does not return reasoning as plain text — it returns structured thinking blocks, each carrying an opaque cryptographic signature. That signature must be passed back unmodified on subsequent turns so the API can verify provenance. There are also redacted_thinking blocks for safety-filtered reasoning, which must likewise be preserved.

Mellea currently concatenates reasoning into a plain str (mot._thinking), losing the signature in the process. On the LiteLLM path the full Anthropic response — including thinking blocks — survives incidentally inside mot._meta["litellm_full_response"], but nothing surfaces it into a structured field that mellea can actually round-trip. There is no accessible, reusable carrier for the signed blocks today. (LangChain shipped a production bug on Anthropic Opus 4.7 where replaying a thinking block with a signature but no text caused 400 errors on roughly 20 % of turns. This class of problem is subtle.)

Impact on mellea

The gaps stack up:

  • Multi-turn reasoning continuity is broken for all chat backends — OpenAI, LiteLLM, Ollama, WatsonX. Single-turn capture works; multi-turn does not.
  • HuggingFace and Bedrock never populate reasoning at all — models run via those backends return no _thinking regardless of what the model produces. Bedrock is a notable case: AWS Anthropic models return reasoningContent with a signature via the Converse API, so Bedrock has both the capture gap and the structured-block problem.
  • Anthropic extended thinking is unsupported end-to-end. Mellea has no native Anthropic backend; Anthropic is reachable only via LiteLLM's generic reasoning_effort passthrough. The extended thinking config (thinking: {type, budget_tokens}) and block round-trip are not supported at any layer.
  • ModelOption.THINKING was broken in OpenAIBackend for bool values — fixed by PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204. The native OllamaBackend (Ollama Python SDK) already handled thinking correctly via its own think= parameter and chunk.message.thinking capture — PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204 does not touch it. The fix is scoped to OpenAIBackend, which is the path used when connecting to vLLM (or Ollama's OpenAI-compatible endpoint) via base_url. LiteLLMBackend routes thinking through its own provider-level translation layer and is unaffected by this PR; for Ollama it works correctly (LiteLLM translates reasoning_effort → think=True for Ollama and normalises the response to reasoning_content). The remaining gap is the vLLM-via-LiteLLM path — two fixable bugs in LiteLLMBackend: (1) api_base / _base_url is stored but never passed to litellm.acompletion(), so the backend cannot route to a custom vLLM endpoint at all; (2) even if routing works, chat_template_kwargs.enable_thinking is never set, so THINKING=True does nothing for models like Gemma 4 where vLLM doesn't auto-inject from reasoning_effort alone (tested live: Qwen3 works via auto-injection; Gemma 4 does not). Both are follow-on fixes to LiteLLMBackend, similar in shape to PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204 but for that backend. HuggingFace and Bedrock remain gaps. See fix: improve ModelOption.THINKING with vLLM through OpenAI #1093.
  • Thinking-default behaviour is model-specific and currently undefined in mellea. Qwen3 (with --reasoning-parser qwen3) has thinking ON by server default; Gemma 4 (with --reasoning-parser gemma4) has it OFF. A mellea user who does not set ModelOption.THINKING gets reasoning on Qwen3 and none on Gemma 4 from the identical instruct() call — inconsistent without any indication why. The model registry has no thinking_default field; there is no convention for expressing or discovering this. This is also a precondition for workstream 5: you cannot decide whether to re-enable thinking on a subsequent turn without knowing what the model's default is.
  • No end-to-end test exists for a real thinking model across turns. Unit tests cover reasoning-string capture in isolation; the one real-model test (test_think_budget_forcing.py) is CI-skipped and has no assertions on reasoning content.

How this relates to #909 / discussion #1197 — scope boundary

Alex's #909 cleanup (discussion #1197) includes Area 4: promoting mot._thinking to the public mot.thinking. This issue is not part of that work and should not be folded into it. Area 4 is purely a rename/exposure change within the ModelOutputThunk boundary. This issue lives at the layer above: the Message type, chat.py:_parse, as_chat_history, and the per-backend input formatters.

That said, two of Alex's areas are worth sequencing before this work begins:

  • Area 4 — gives us the public mot.thinking property to read from, rather than the underscore name that will shortly be deprecated.
  • Area 1 — rewrites chat.py:_parse to switch on mot.raw.provider, which is the exact function this work needs to extend; it also introduces mot.raw.response, where the Anthropic signed block would live.

Strictly speaking, neither is a hard blocker — _parse can be changed independently and Message.thinking can read from the private name for now. But starting before Area 1 and Area 4 are merged means either rebasing onto an in-flight rewrite of the same function, or carrying forward a name that is about to be deprecated. Strongly recommended to sequence this after.

Related issues (not prerequisites):

Proposed first step — validation

Before designing the fix, we need to know precisely what mellea does today with a real thinking model over multiple turns: is reasoning captured, what does as_chat_history produce on turn 2, what does the backend actually send, does a tool call change anything?

Candidate models (cheapest first):

  • Qwen3 via Ollama — exercises the strip-by-default multi-turn behaviour and the reasoning_content/reasoning dual-key capture path
  • gpt-oss:20b via Ollama — already in the test suite; quick smoke check
  • DeepSeek-R1 (Ollama or a hosted endpoint) — confirms the hard 400-without-tools contract
  • Anthropic via LiteLLM — checks whether thinking_blocks/signature even reach mellea today

Some of these need a served endpoint, shared URL, or API credentials — that is a separate conversation to arrange. The deliverable is a short findings note, not code, to ground the design in what we observe rather than what we expect.

Update (2026-06-04) — Qwen3.6-27B against OpenAI-compat backend, confirmed. Using Qwen/Qwen3.6-27B served via vLLM with --reasoning-parser qwen3:

  • Capture: ✓ working. mot._thinking is populated via model_extra.get("reasoning") on streaming delta chunks. The vLLM field name is reasoning (not reasoning_content); the current backend probes both, so it happens to work. Worth noting: if reasoning ever becomes a typed native attribute on ChoiceDelta in a future OpenAI SDK version, model_extra would no longer hold it and capture would silently break.
  • _parse drop at chat.py:116: ✓ confirmed. mot.parsed_repr is Message(role="assistant", content="\n\n7"). The Message type has no thinking attribute; _thinking is likewise absent. The reasoning trace is gone at the parse boundary.
  • as_chat_history drop: ✓ confirmed. The assistant entry in the returned history is {'role': 'assistant', 'content': '\n\n7'} — no reasoning field, no trace of _thinking.
  • Turn 2 API payload: ✓ confirmed. The full messages array sent on the second call is [{role: user, content: "…"}, {role: assistant, content: "\n\n7"}, {role: user, content: "…"}]. No reasoning or reasoning_content field anywhere.
  • Bonus observation: mot.value carries a leading \n\n stripped from after the </think> block. This propagates through to Message.content. Not a reasoning issue, but callers will see the extra whitespace.

Update (2026-06-04) — google/gemma-4-31B-it against OpenAI-compat backend, confirmed. Using google/gemma-4-31B-it served via vLLM with --reasoning-parser gemma4:

  • THINKING=True sends correctly: ✓ confirmed. chat_template_kwargs.enable_thinking=True reaches the model; reasoning tokens are generated. This validates that PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204's dual-set behaviour (both reasoning_effort and chat_template_kwargs.enable_thinking) works for a second non-Qwen model using the same vLLM mechanism.
  • THINKING=False suppresses correctly: ✓ confirmed. With enable_thinking=False sent, mot.value is clean — no thinking prefix.
  • extra_body merge: ✓ no TypeError. Combining THINKING=True with a user-supplied extra_body in model_options works without collision.
  • _thinking capture: ✓ confirmed working with --reasoning-parser gemma4. The reasoning field is returned in the API response and is held in model_extra (not a typed attribute on ChatCompletionMessage as of openai SDK 2.24.0), so the existing (message.model_extra or {}).get("reasoning") capture path picks it up correctly. Fragility note: if a future SDK version promotes reasoning to a typed field, model_extra would no longer carry it and capture would silently break — this is the same risk flagged for Qwen3 above.
  • Thinking-default observation: Gemma 4 has thinking OFF by server default — correct for a general instruction model where thinking is an opt-in capability. This contrasts with Qwen3's thinking-ON default. A mellea user switching between the two models without explicitly setting ModelOption.THINKING gets different behaviour silently (see Impact section above).

Update (2026-06-04) — qwen3.6:35b via Ollama (0.30.4), confirmed. Using qwen3.6:35b served via Ollama's OpenAI-compatible endpoint:

  • Capture: ✓ working. Ollama 0.30.4 returns thinking in model_extra['reasoning'] — the same field name as vLLM, not a separate thinking attribute as earlier Ollama documentation suggested. Mellea's existing (message.model_extra or {}).get("reasoning") path picks it up correctly. No capture gap.
  • THINKING=True: ✓ working. Mellea sends chat_template_kwargs.enable_thinking=True via extra_body (the vLLM-standardised mechanism). Ollama accepts this because Qwen3's Jinja chat template uses enable_thinking as its native template variable — the mechanism is model-level, not server-level. mot._thinking is populated.
  • THINKING=False: ✓ working. enable_thinking=False suppresses reasoning; mot.value is clean.
  • think shorthand vs chat_template_kwargs: Ollama also exposes a top-level think bool (extra_body={"think": True}) as a convenience shorthand. Mellea does not use this path — but the Jinja-level mechanism works through both servers identically, so no Ollama-specific branch is needed in the backend.

Update (2026-06-04) — qwen3.6:35b via LiteLLMBackend → Ollama, confirmed.

  • THINKING=True: ✓ working. LiteLLM translates reasoning_effort="medium" → think=True for the Ollama provider internally. mot._thinking is populated.
  • THINKING=False: ✓ working. Thinking is suppressed; mot.value is clean.
  • Capture field differs from the OpenAI-compat path. LiteLLM normalises Ollama's response to reasoning_content in the message dict (rather than model_extra['reasoning']). The LiteLLM backend checks reasoning_content first (then reasoning), so capture is correct.
  • Note: A RuntimeWarning: coroutine 'Logging.async_success_handler' was never awaited appears on completion — pre-existing LiteLLM async telemetry issue, not mellea's.
  • LiteLLM → vLLM gap confirmed (live test). Using litellm.acompletion() directly with api_base pointing at the live vLLM endpoints: reasoning_effort='medium' engages thinking on Qwen3.6-27B (vLLM auto-injects enable_thinking for recognised reasoning parsers) but does not engage it on Gemma-4-31B-it — mot._thinking is empty. Gemma 4 requires an explicit chat_template_kwargs.enable_thinking=True, which LiteLLM never sends. Two LiteLLMBackend bugs to fix: (1) _base_url not passed as api_base to litellm.acompletion(); (2) no extra_body.chat_template_kwargs.enable_thinking set for bool THINKING. Both are follow-on to PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204 — to be converted to a sub-issue when the shape of Better handling of reasoning output from thinking models #1201 is agreed.

Remaining validation items: DeepSeek-R1 (to verify the hard-400 contract), Anthropic via LiteLLM (to check whether thinking_blocks/signature survive into _meta), and a tool-use turn on any provider. These need credentials or a hosted endpoint to arrange separately.

Candidate workstreams — if the shape is agreed, these become sub-issues

  1. Empirical validation — Qwen3.6-27B (vLLM), Gemma-4-31B-it (vLLM), qwen3.6:35b (Ollama OpenAI-compat), and qwen3.6:35b (LiteLLM → Ollama) done (see above); DeepSeek-R1, Anthropic, and tool-use turns outstanding
  2. Capture gaps — populate reasoning for HuggingFace; Bedrock (noting the Anthropic-signature problem applies there too); also IBM Granite 3.2 via vLLM (uses thinking=True not enable_thinking — capture path likely works but untested)
  3. Structured reasoning carrier — capture Anthropic thinking_blocks + signature; depends on Area 1's mot.raw
  4. Message.thinking + _parse rewrite — depends on Area 1 + Area 4
  5. Per-backend replay policy — strip/keep keyed on tool use; Ollama and openai-compat first. Note: this workstream has two distinct sub-problems that must not be conflated: (a) whether the reasoning content from the prior turn is included in the message history — the hard multi-provider problem described above; and (b) whether thinking is re-enabled for the next turn. Sub-problem (b) is largely solved on vLLM: sending reasoning_effort already causes vLLM v0.22.0+ to auto-inject enable_thinking server-side, so re-enablement happens without extra mellea logic. The unsolved part is (a).
  6. ModelOption.THINKING cross-platform unification — fix: improve ModelOption.THINKING with vLLM through OpenAI #1093 closed — bool routing fixed for OpenAIBackend (PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204) and LiteLLMBackend (PR fix(litellm): pass api_base and set enable_thinking for bool THINKING #1207); extend to the legacy thinking=True key used by IBM Granite 3.2 and DeepSeek-V3.1; address thinking-default inconsistency across models and define whether explicit THINKING is the required opt-in. See the vLLM reasoning outputs docs for the current model matrix.
  7. Anthropic backend + extended thinking — likely its own epic given the scope; worth deciding scope here first
  8. Test harness + cassettes — recorded multi-turn fixtures per provider so CI can assert on the divergent replay behaviour

I (@planetf1) am happy to take this forward once the shape is agreed. The validation work to date (Qwen3, Gemma 4, Ollama) came out of PR #1204; I have access to vLLM endpoints for further live testing and can lead the implementation workstreams above.

CC @ajbozarth @jakelorocco @psschwei — thoughts welcome on scope and sequencing. The key open question: should Anthropic extended thinking (and a native backend) be part of this or tracked as a sibling epic?

Activity

  1. added
    needs-design
    area/backends
    area/stdlib
    enhancement
    on Jun 4, 2026
  2. self-assigned this
    on Jun 4, 2026
  3. psschwei commented on Jun 4, 2026

    @psschwei
    Contributor

    Summarizing the above:

    1. The bug: Mellea captures reasoning from thinking models (Qwen3, DeepSeek-R1, Anthropic, OpenAI o-series) on single calls via mot._thinking, but silently drops it on follow-up turns — so the model has no memory of its prior reasoning in multi-turn chats.
    2. The gaps stack across the stack: Multi-turn reasoning is broken on every chat backend (OpenAI, LiteLLM, Ollama, WatsonX); HuggingFace and Bedrock never capture reasoning at all; ModelOption.THINKING is fragmented across three different mechanisms; and there's no end-to-end multi-turn test for any real thinking model.
    3. Proposed path forward: Start with empirical validation (observe what mellea actually sends today across Qwen3, DeepSeek-R1, Anthropic) before designing. The fix should sequence after Alex's Epic: ModelOutputThunk structural cleanup #909 Area 1 and Area 4 land, then split into ~8 sub-issues covering capture, structured carriers, _parse rewrite, per-backend replay policy, and test cassettes.

    Some thoughts:

    • Given our focus on open-weight models and the fact that Anthropic already has their own harness, I would think the Anthropic models are an extremely low priority (same for OpenAI, etc.)
    • In terms of priority, I think that this is absolutely needed, but not immediately.
    • If every model has their own way of doing things, we can't be building and maintaining custom support for each model. We need to either pick a subset of models or figure out a way to have a general method configured from what's available on HF
  4. jakelorocco commented on Jun 4, 2026

    @jakelorocco
    Contributor

    One proposed solution: we change how MOTs are represented when being formatted as messages. I think we could just change the meta dict on MOTs to store the full assistant response and serialize that full response back to the model. There might be some cross backend / cross model edge cases we need to handle, but that might be an easy solution.

  5. planetf1 commented on Jun 5, 2026

    @planetf1
    ContributorAuthor

    Storing the full response from _meta and replaying it is essentially the direction Area 1's mot.raw.response is heading — it solves the capture side cleanly: all the fields (reasoning_content, signatures, redacted blocks) are available when building the next turn's message history.

    What it doesn't resolve is the replay policy — whether to include the reasoning field at all. That decision is per-provider and flips on whether the prior assistant turn issued a tool call. deepseek-reasoner returns a hard 400 if reasoning_content appears in history without a prior tool call, but requires it when there was one. Xiaomi's MiMo documentation states the same contract explicitly, and GLM-4.5 follows the same strip-by-default behaviour as Qwen3. So even with the full response stored, logic is still needed to decide "for this provider, on this turn, does the reasoning go in or get stripped?"

    There's also a related capture fragility worth noting: vLLM recently renamed the response field from reasoning_content to reasoning. The current mellea capture path already uses model_extra.get("reasoning"), so it handles the new name — but the dual-key probe is load-bearing and will silently break if a future SDK version promotes reasoning to a typed attribute and removes it from model_extra. Qwen Cloud has addressed the multi-turn problem at the API level with a preserve_thinking parameter (opt-in, Qwen3.6/3.7 only) — that's a useful reference point for what the mellea-level behaviour should look like.

    The carrier shape (your proposal, workstreams 3+4) and the replay policy (workstream 5) are separable. The next concrete step is agreeing the carrier shape — does mot.raw.response storing the full provider response cover what's needed, or does the Message type also need an explicit thinking field for the common case?

  6. planetf1 commented on Jun 5, 2026

    @planetf1
    ContributorAuthor

    Agreed on priority and scope — and worth flagging that when we say "deprioritise OpenAI", we mean the proprietary models/endpoint (GPT-4, o-series). The OpenAI-compatible API format that vLLM, Ollama, and LiteLLM serve is actually the backbone of all the open-weight work here. Anthropic-native (signed thinking blocks, extended thinking config) is a different problem we're not proposing to tackle here.

    On the general method — the tool-use axis looks like it covers it. Across Qwen3, DeepSeek, Gemma 4, MiMo, and GLM-4.5, the contract is the same: strip reasoning on plain turns, round-trip it when the prior turn had a tool call. One rule. The per-backend work is just field name differences (reasoning_content vs reasoning vs Anthropic's blocks), not separate decision logic per model.

    Proposed scope: Qwen3/Gemma 4/DeepSeek via vLLM and Ollama first, Bedrock and HuggingFace as explicit follow-on.

  7. planetf1 commented on Jun 5, 2026

    @planetf1
    ContributorAuthor

    To summarise ...

    PRs #1204 and #1207 fix the input — ModelOption.THINKING bool now routes correctly for both OpenAIBackend and LiteLLMBackend. A prereq but doesn't touch multi-turn continuity.

    scope: open-weight models via vLLM and Ollama (Qwen3, Gemma 4, DeepSeek, MiMo, GLM-4.5). Anthropic-native and OpenAI proprietary excluded — the OpenAI-compatible format that vLLM and Ollama serve is in scope. HuggingFace and Bedrock as follow-on.

    1. Message.thinking + _parse + as_chat_history — reasoning is captured today but dropped at the parse boundary. Everything else depends on this. Best done after Epic: ModelOutputThunk structural cleanup #909, which rewrites _parse and adds the public mot.thinking property these changes need.
    2. Per-backend replay policy — strip on plain turns, include when the prior turn had a tool call. Five model families confirm the same contract; one rule, different field names per backend.
    3. Capture hardening — the model_extra.get("reasoning") probe will silently break if a future SDK version promotes the field to a typed attribute. Worth keeping in mind as a follow-on consideration.
    4. Test cassettes — multi-turn recorded fixtures per provider so CI can cover the divergent replay behaviour without a live model.

    I'm happy to pursue this...

  8. psschwei commented on Jun 5, 2026

    @psschwei
    Contributor

    I'd suggest a different scope. Let's chat internally.

  9. added
    p2
    on Jun 18, 2026
  10. changed the title [-]Multi-turn chat silently drops reasoning output from thinking models[/-] [+]Better handling of reasoning output from thinking models[/+] on Jun 19, 2026
  11. removed their assignment
    on Jun 19, 2026
  12. added
    p0
    and removed
    p2
    on Jul 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

area/backendsarea/stdlibenhancementneeds-designp0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions