Repository navigation
Description
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 modelThe 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
_thinkingregardless of what the model produces. Bedrock is a notable case: AWS Anthropic models returnreasoningContentwith 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_effortpassthrough. The extended thinking config (thinking: {type, budget_tokens}) and block round-trip are not supported at any layer. ModelOption.THINKINGwas broken inOpenAIBackendfor bool values — fixed by PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204. The nativeOllamaBackend(Ollama Python SDK) already handled thinking correctly via its ownthink=parameter andchunk.message.thinkingcapture — PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204 does not touch it. The fix is scoped toOpenAIBackend, which is the path used when connecting to vLLM (or Ollama's OpenAI-compatible endpoint) viabase_url.LiteLLMBackendroutes thinking through its own provider-level translation layer and is unaffected by this PR; for Ollama it works correctly (LiteLLM translatesreasoning_effort→think=Truefor Ollama and normalises the response toreasoning_content). The remaining gap is the vLLM-via-LiteLLM path — two fixable bugs inLiteLLMBackend: (1)api_base/_base_urlis stored but never passed tolitellm.acompletion(), so the backend cannot route to a custom vLLM endpoint at all; (2) even if routing works,chat_template_kwargs.enable_thinkingis never set, so THINKING=True does nothing for models like Gemma 4 where vLLM doesn't auto-inject fromreasoning_effortalone (tested live: Qwen3 works via auto-injection; Gemma 4 does not). Both are follow-on fixes toLiteLLMBackend, 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 setModelOption.THINKINGgets reasoning on Qwen3 and none on Gemma 4 from the identicalinstruct()call — inconsistent without any indication why. The model registry has nothinking_defaultfield; 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.thinkingproperty to read from, rather than the underscore name that will shortly be deprecated. - Area 1 — rewrites
chat.py:_parseto switch onmot.raw.provider, which is the exact function this work needs to extend; it also introducesmot.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):
- feat: distinguish thinking models #406 — tracking which models support thinking; provider parity
- fix: improve ModelOption.THINKING with vLLM through OpenAI #1093 —
ModelOption.THINKINGdisable lever not cross-platform for vLLM/Qwen3 (addressed by PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204) - feat(telemetry): normalise cache and reasoning token fields in GenerationMetadata across providers #1074 — reasoning token telemetry normalisation across providers
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/reasoningdual-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/signatureeven 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._thinkingis populated viamodel_extra.get("reasoning")on streaming delta chunks. The vLLM field name isreasoning(notreasoning_content); the current backend probes both, so it happens to work. Worth noting: ifreasoningever becomes a typed native attribute onChoiceDeltain a future OpenAI SDK version,model_extrawould no longer hold it and capture would silently break. _parsedrop atchat.py:116: ✓ confirmed.mot.parsed_reprisMessage(role="assistant", content="\n\n7"). TheMessagetype has nothinkingattribute;_thinkingis likewise absent. The reasoning trace is gone at the parse boundary.as_chat_historydrop: ✓ 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: "…"}]. Noreasoningorreasoning_contentfield anywhere. - Bonus observation:
mot.valuecarries a leading\n\nstripped from after the</think>block. This propagates through toMessage.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=Truereaches 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 (bothreasoning_effortandchat_template_kwargs.enable_thinking) works for a second non-Qwen model using the same vLLM mechanism. - THINKING=False suppresses correctly: ✓ confirmed. With
enable_thinking=Falsesent,mot.valueis clean — no thinking prefix. extra_bodymerge: ✓ no TypeError. CombiningTHINKING=Truewith a user-suppliedextra_bodyinmodel_optionsworks without collision._thinkingcapture: ✓ confirmed working with--reasoning-parser gemma4. Thereasoningfield is returned in the API response and is held inmodel_extra(not a typed attribute onChatCompletionMessageas 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 promotesreasoningto a typed field,model_extrawould 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.THINKINGgets 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 separatethinkingattribute 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=Trueviaextra_body(the vLLM-standardised mechanism). Ollama accepts this because Qwen3's Jinja chat template usesenable_thinkingas its native template variable — the mechanism is model-level, not server-level.mot._thinkingis populated. - THINKING=False: ✓ working.
enable_thinking=Falsesuppresses reasoning;mot.valueis clean. thinkshorthand vschat_template_kwargs: Ollama also exposes a top-levelthinkbool (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=Truefor the Ollama provider internally.mot._thinkingis populated. - THINKING=False: ✓ working. Thinking is suppressed;
mot.valueis clean. - Capture field differs from the OpenAI-compat path. LiteLLM normalises Ollama's response to
reasoning_contentin the message dict (rather thanmodel_extra['reasoning']). The LiteLLM backend checksreasoning_contentfirst (thenreasoning), so capture is correct. - Note: A
RuntimeWarning: coroutine 'Logging.async_success_handler' was never awaitedappears on completion — pre-existing LiteLLM async telemetry issue, not mellea's. - LiteLLM → vLLM gap confirmed (live test). Using
litellm.acompletion()directly withapi_basepointing at the live vLLM endpoints:reasoning_effort='medium'engages thinking on Qwen3.6-27B (vLLM auto-injectsenable_thinkingfor recognised reasoning parsers) but does not engage it on Gemma-4-31B-it —mot._thinkingis empty. Gemma 4 requires an explicitchat_template_kwargs.enable_thinking=True, which LiteLLM never sends. TwoLiteLLMBackendbugs to fix: (1)_base_urlnot passed asapi_basetolitellm.acompletion(); (2) noextra_body.chat_template_kwargs.enable_thinkingset 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
- 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
- Capture gaps — populate reasoning for HuggingFace; Bedrock (noting the Anthropic-signature problem applies there too); also IBM Granite 3.2 via vLLM (uses
thinking=Truenotenable_thinking— capture path likely works but untested) - Structured reasoning carrier — capture Anthropic
thinking_blocks+signature; depends on Area 1'smot.raw Message.thinking+_parserewrite — depends on Area 1 + Area 4- 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_effortalready causes vLLM v0.22.0+ to auto-injectenable_thinkingserver-side, so re-enablement happens without extra mellea logic. The unsolved part is (a). ModelOption.THINKINGcross-platform unification — fix: improve ModelOption.THINKING with vLLM through OpenAI #1093 closed — bool routing fixed forOpenAIBackend(PR fix(backends): route ModelOption.THINKING=bool to chat_template_kwargs for vLLM #1204) andLiteLLMBackend(PR fix(litellm): pass api_base and set enable_thinking for bool THINKING #1207); extend to the legacythinking=Truekey used by IBM Granite 3.2 and DeepSeek-V3.1; address thinking-default inconsistency across models and define whether explicitTHINKINGis the required opt-in. See the vLLM reasoning outputs docs for the current model matrix.- Anthropic backend + extended thinking — likely its own epic given the scope; worth deciding scope here first
- 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
psschwei commentedon Jun 4, 2026
Summarizing the above:
Some thoughts:
jakelorocco commentedon Jun 4, 2026
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.
planetf1 commentedon Jun 5, 2026
Storing the full response from
_metaand replaying it is essentially the direction Area 1'smot.raw.responseis 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-reasonerreturns a hard 400 ifreasoning_contentappears 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_contenttoreasoning. The current mellea capture path already usesmodel_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 promotesreasoningto a typed attribute and removes it frommodel_extra. Qwen Cloud has addressed the multi-turn problem at the API level with apreserve_thinkingparameter (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.responsestoring the full provider response cover what's needed, or does theMessagetype also need an explicitthinkingfield for the common case?planetf1 commentedon Jun 5, 2026
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_contentvsreasoningvs 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.
planetf1 commentedon Jun 5, 2026
To summarise ...
PRs #1204 and #1207 fix the input —
ModelOption.THINKINGbool now routes correctly for bothOpenAIBackendandLiteLLMBackend. 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.
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_parseand adds the publicmot.thinkingproperty these changes need.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.I'm happy to pursue this...
psschwei commentedon Jun 5, 2026
I'd suggest a different scope. Let's chat internally.
fix(litellm): pass api_base and set enable_thinking for bool THINKING (…
[-]Multi-turn chat silently drops reasoning output from thinking models[/-][+]Better handling of reasoning output from thinking models[/+]