From 1b362323228a29bc12c428a2cf629f4662dc4514 Mon Sep 17 00:00:00 2001 From: James Wiesebron Date: Tue, 28 Jul 2026 21:56:36 -0700 Subject: [PATCH 1/2] litellm: add Patch 10, carry prior-turn assistant reasoning to OpenRouter On egg's primary route (Claude Code -> gateway -> LiteLLM /v1/messages -> OpenRouter), assistant reasoning from prior turns was never sent back to the model. LiteLLM's Anthropic adapter converts incoming `thinking` content blocks into `assistant_message["thinking_blocks"]`, but nothing on the OpenRouter request path consumes that field: stock openrouter/chat/transformation.py names reasoning only on the response side, and `reasoning_details` appears nowhere under llms/ or litellm_core_utils/. The parent `transform_request` puts `messages` straight into the body, so `thinking_blocks` reached OpenRouter as a field no one reads and every historical assistant turn arrived with no reasoning. For a model whose chat template re-renders prior thinking that is a malformed history, not a lost optimisation: Poolside Laguna renders `'' + message.reasoning|message.reasoning_content + ''` per previous assistant turn, so each one became a literal empty ``, which Poolside's model card warns degrades follow-up behaviour. The gap is upstream's and predates every egg and fork change; jwbron/litellm#8 touches only `get_supported_openai_params`, which acts on `optional_params` and cannot reach a message field. Patch 10 maps the blocks onto `reasoning_content` in `OpenrouterConfig.transform_request` and removes `thinking_blocks`. The logic lives in a fourth staged module (`openrouter_reasoning_roundtrip.py` -> `llms/openrouter/_egg_reasoning_roundtrip.py`), following the same convention as Modules 1-3 so it stays lintable and unit-testable here. Multiple blocks concatenate in order; `redacted_thinking` carries no plaintext and contributes nothing; a whitespace-only result emits no field rather than re-creating the empty ``; Anthropic `signature` values are not forwarded; assistant messages only; fail soft, so a block that cannot be parsed leaves its message untouched. Note the direction: this is request-path (client -> provider). Patches 4, 5a and 5b are response-path (provider -> client). Adjacent, not the same. Verified by applying the full script to a real stock litellm 1.86.2 install (all 10 patches and 4 modules apply, and re-applying is a no-op) and replaying a real Claude Code /v1/messages body through it with the provider endpoint captured: before, the outgoing assistant message was `['role', 'thinking_blocks', 'tool_calls']` with no reasoning field; after, `['reasoning_content', 'role', 'tool_calls']`. Mirrors jwbron/litellm#11. --- config/litellm/Dockerfile | 4 +- .../litellm/openrouter_reasoning_roundtrip.py | 125 ++++++++++ config/litellm/patch_litellm_cache.py | 135 +++++++++-- tests/config/test_litellm_runtime_modules.py | 217 ++++++++++++++++++ tests/config/test_patch_litellm_cache.py | 79 +++++++ 5 files changed, 543 insertions(+), 17 deletions(-) create mode 100644 config/litellm/openrouter_reasoning_roundtrip.py diff --git a/config/litellm/Dockerfile b/config/litellm/Dockerfile index 734b92d4b..01c8c10e1 100644 --- a/config/litellm/Dockerfile +++ b/config/litellm/Dockerfile @@ -5,7 +5,8 @@ # stock image's Anthropic->OpenAI translation drops prompt-cache hits on # Qwen/DeepSeek, mis-streams reasoning models, silently drops params it does # not recognise, and manufactures a reasoning ceiling from the caller's -# thinking budget. patch_litellm_cache.py closes the nine gaps at build time +# thinking budget, and never sends prior-turn reasoning back. +# patch_litellm_cache.py closes the ten gaps at build time # (see that script for the diagnosis); # cost_callback.py surfaces the resulting cost/cache stats into the pod log # stream. Both mirror the host-side dotfiles setup that took Qwen cache hit @@ -31,6 +32,7 @@ COPY patch_litellm_cache.py /egg/patch_litellm_cache.py COPY openrouter_capabilities.py /egg/openrouter_capabilities.py COPY drop_params_visibility.py /egg/drop_params_visibility.py COPY anthropic_thinking_policy.py /egg/anthropic_thinking_policy.py +COPY openrouter_reasoning_roundtrip.py /egg/openrouter_reasoning_roundtrip.py RUN python3 /egg/patch_litellm_cache.py # Custom cost/cache logger, registered as `cost_callback.cost_logger` under diff --git a/config/litellm/openrouter_reasoning_roundtrip.py b/config/litellm/openrouter_reasoning_roundtrip.py new file mode 100644 index 000000000..eda7f2dce --- /dev/null +++ b/config/litellm/openrouter_reasoning_roundtrip.py @@ -0,0 +1,125 @@ +"""Carry prior-turn assistant reasoning back to OpenRouter. + +egg's primary route is ``/v1/messages``: Claude Code -> egg-gateway -> LiteLLM +-> OpenRouter. On the way in, LiteLLM's Anthropic adapter turns each assistant +``thinking`` content block into an entry on +``assistant_message["thinking_blocks"]`` (``_translate_anthropic_messages_to_openai`` +in ``llms/anthropic/experimental_pass_through/adapters/transformation.py``). +Nothing on the OpenRouter **request** path then reads that field: stock +``llms/openrouter/chat/transformation.py`` mentions reasoning exactly once, on +the *response* side (``reasoning`` -> ``reasoning_content`` on streaming +deltas), and ``reasoning_details`` appears nowhere in ``llms/`` or +``litellm_core_utils/`` at all. So ``thinking_blocks`` rides to the provider as +a field no one reads, and every historical assistant turn arrives carrying no +reasoning. + +For a model whose chat template re-renders prior thinking that is not merely a +lost optimisation, it is a malformed history. Poolside Laguna renders +``'' + message.reasoning|message.reasoning_content + ''`` for +every previous assistant turn, so each one arrives as a literal empty +````; Poolside's model card warns that this degrades follow-up +behaviour. The measured cost in egg was a livelock whose per-turn prompt growth +was exactly +243 tokens, leaving no budget for reasoning content. + +This module maps the blocks the adapter produced onto the field OpenRouter +actually reads. OpenRouter accepts ``reasoning``, ``reasoning_content`` and +``reasoning_details`` interchangeably on an assistant message and documents +this for exactly this multi-turn tool-calling case; Poolside's template reads +``message.reasoning`` / ``message.reasoning_content``. We send the plain string +form, which satisfies both: ``reasoning_details`` exists to carry encrypted or +summarised blocks, and we have neither. Anthropic ``signature`` values are +meaningless to OpenRouter and are not forwarded. + +The gap is upstream's, not egg's: it predates every egg and ``jwbron/litellm`` +change, and the fork's OpenRouter work (jwbron/litellm#8) is confined to +``get_supported_openai_params``, which acts on ``optional_params`` and cannot +reach a message field. + +Note the direction. Patches 4, 5a and 5b are response-path (provider -> +client): they fix how reasoning is *streamed back*. This is request-path +(client -> provider). They are adjacent, not the same thing. +""" + +from typing import Any + +# Blocks the adapter can put on ``thinking_blocks``. ``redacted_thinking`` +# carries an opaque ``data`` payload rather than text (see +# ``ChatCompletionRedactedThinkingBlock``); there is no plaintext to hand a +# provider that wants a string, so those blocks contribute nothing. +_THINKING_BLOCK_TYPE = "thinking" + +# The field the adapter writes and the field OpenRouter reads. +_SOURCE_FIELD = "thinking_blocks" +_TARGET_FIELD = "reasoning_content" + + +def _extract_reasoning_text(blocks: Any) -> str: + """Concatenate the plaintext of ``blocks``, in order. + + Non-dict entries, entries of any type other than ``thinking``, and entries + whose ``thinking`` is not a string are skipped individually rather than + failing the whole message: one malformed block should not cost us the + reasoning from its well-formed siblings. A ``blocks`` that is not a list at + all is a shape we do not understand, and the caller leaves the message + untouched. + """ + if not isinstance(blocks, list): + raise TypeError(f"{_SOURCE_FIELD} is {type(blocks).__name__}, expected list") + parts: list[str] = [] + for block in blocks: + if not isinstance(block, dict): + continue + if block.get("type") != _THINKING_BLOCK_TYPE: + continue + text = block.get(_THINKING_BLOCK_TYPE) + if isinstance(text, str): + parts.append(text) + return "".join(parts) + + +def map_thinking_blocks_to_reasoning_content(messages: Any) -> Any: + """Return ``messages`` with assistant reasoning moved to the wire field. + + For each assistant message carrying ``thinking_blocks``: drop that field so + no unknown key is transmitted, and set ``reasoning_content`` to the + concatenated plaintext when there is any. A message whose blocks yield only + whitespace (or nothing at all, e.g. ``redacted_thinking`` only) loses the + field and gains nothing, which is what OpenRouter would have received + anyway minus the noise. + + User, system and tool messages are returned untouched, as is any assistant + message with no ``thinking_blocks`` key. Input is not mutated: touched + messages are shallow-copied. + + Never raises. A message this function cannot make sense of is passed + through exactly as it arrived, so the worst case is stock behaviour. + """ + if not isinstance(messages, list): + return messages + + out: list[Any] = [] + for message in messages: + try: + if not isinstance(message, dict): + out.append(message) + continue + if message.get("role") != "assistant" or _SOURCE_FIELD not in message: + out.append(message) + continue + + text = _extract_reasoning_text(message.get(_SOURCE_FIELD)) + + updated: dict[str, Any] = dict(message) + updated.pop(_SOURCE_FIELD, None) + # Whitespace-only reasoning is not reasoning; emitting it would put + # an empty in the rendered prompt, which is the + # exact failure this patch exists to remove. + if text.strip(): + updated[_TARGET_FIELD] = text + out.append(updated) + except Exception: # noqa: BLE001 - a request must survive a bad block + out.append(message) + return out + + +__all__ = ["map_thinking_blocks_to_reasoning_content"] diff --git a/config/litellm/patch_litellm_cache.py b/config/litellm/patch_litellm_cache.py index b4e1b64a4..16306dd90 100644 --- a/config/litellm/patch_litellm_cache.py +++ b/config/litellm/patch_litellm_cache.py @@ -7,9 +7,10 @@ reasoning models, and its OpenRouter param gate reads a model-cost map that does not carry current OpenRouter slugs, and it discards caller-specified params in total silence, while manufacturing a -reasoning ceiling nobody asked for. Nine independent gaps cause it; this -script closes all nine by editing the installed ``litellm`` -package in place (and installing three new modules), then +reasoning ceiling nobody asked for and never sending prior-turn +reasoning back. Ten independent gaps cause it; this +script closes all ten by editing the installed ``litellm`` +package in place (and installing four new modules), then ``config/litellm/Dockerfile`` bakes the result into the ``egg-litellm`` image. @@ -151,6 +152,43 @@ with the derived effort, because stock carries the summary only as a field of the ``reasoning_effort`` dict and there is no wire shape for "summary, no effort". + 10. ``OpenrouterConfig.transform_request`` + (openrouter/chat/transformation.py) carry prior-turn assistant + reasoning back to the provider. The Anthropic adapter converts + incoming ``thinking`` content blocks into + ``assistant_message["thinking_blocks"]``, and NOTHING on the + OpenRouter request path consumes that field: stock + openrouter/chat/transformation.py names reasoning exactly once, on + the response side (``reasoning`` -> ``reasoning_content`` on + streaming deltas), and ``reasoning_details`` appears nowhere in + ``llms/`` or ``litellm_core_utils/``. The parent + ``transform_request`` puts ``messages`` straight into the body, so + ``thinking_blocks`` reaches OpenRouter as a field no one reads and + every historical assistant turn arrives with no reasoning attached. + For a model whose chat template re-renders prior thinking that is a + malformed history rather than a lost optimisation: Poolside Laguna + renders ``'' + message.reasoning|message.reasoning_content + + ''`` for every previous assistant turn, so each one arrives + as a literal empty ````, which Poolside's model card + warns degrades follow-up behaviour; the measured cost in egg was a + livelock whose per-turn prompt growth was exactly +243 tokens, + leaving no budget for reasoning content. The companion module + ``llms/openrouter/_egg_reasoning_roundtrip.py`` (installed by + ``NEW_MODULES``) maps the blocks onto ``reasoning_content``, the + plain string form OpenRouter documents for exactly this multi-turn + tool-calling case and the field Poolside's template reads; + ``reasoning_details`` exists to carry encrypted or summarised + blocks and we have neither. ``redacted_thinking`` blocks contribute + nothing (no plaintext to send), Anthropic ``signature`` values are + not forwarded (meaningless to OpenRouter), and ``thinking_blocks`` + is removed either way so no unknown field is transmitted. Fails + soft per message: a block it cannot parse leaves that message + exactly as it arrived. NOTE the DIRECTION — this is request-path + (client -> provider); patches 4, 5a and 5b are response-path + (provider -> client). Adjacent, not the same thing. The gap is + upstream's and predates every egg and fork change: jwbron/litellm#8 + touches only ``get_supported_openai_params``, which acts on + ``optional_params`` and cannot reach a message field. Idempotent: each patch detects whether it is already applied. Fails loudly (non-zero exit) if a needle is missing, so a LiteLLM version bump @@ -279,7 +317,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - ' QWEN = "qwen"\n' ' DEEPSEEK = "deepseek"\n' ), - "label": "Patch 1/9 (CacheControlSupportedModels)", + "label": "Patch 1/10 (CacheControlSupportedModels)", }, # Patch 2 — broaden ONLY the cache_control gate (not the shared # is_anthropic_claude_model predicate, which also gates thinking @@ -309,7 +347,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - " )\n" " ):\n" ), - "label": "Patch 2/9 (cache_control gate)", + "label": "Patch 2/10 (cache_control gate)", }, # Patch 3 — drop x-anthropic-billing-header during Anthropic->OpenAI translation. { @@ -343,7 +381,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - ' "text": text,\n' " }\n" ), - "label": "Patch 3/9 (x-anthropic-billing-header filter)", + "label": "Patch 3/10 (x-anthropic-billing-header filter)", }, # Patch 4 — OpenRouter-style reasoning_content must open a thinking # content block, not fall through to a text block. The bare @@ -381,7 +419,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - ' choice.delta, "thinking_blocks"\n' " ):\n" ), - "label": "Patch 4/9 (reasoning_content thinking block)", + "label": "Patch 4/10 (reasoning_content thinking block)", }, # Patch 5a — sync __next__: don't drop the first delta on text or # thinking block transitions. @@ -481,7 +519,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - " ):\n" " self.chunk_queue.append(processed_chunk)\n" ), - "label": "Patch 5a/9 (sync first-delta requeue)", + "label": "Patch 5a/10 (sync first-delta requeue)", }, # Patch 5b — async __anext__: same first-delta preservation. { @@ -579,7 +617,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - " ):\n" " self.chunk_queue.append(processed_chunk)\n" ), - "label": "Patch 5b/9 (async first-delta requeue)", + "label": "Patch 5b/10 (async first-delta requeue)", }, # Patch 6 — streamed usage must report provider-automatic cache hits. # The needle spans the whole usage-merge region so both edit points @@ -671,7 +709,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - " elif cached_tokens > 0:\n" ' usage_dict["cache_read_input_tokens"] = cached_tokens\n' ), - "label": "Patch 6/9 (streaming cache_read fallback)", + "label": "Patch 6/10 (streaming cache_read fallback)", }, # Patch 7 — OpenrouterConfig.get_supported_openai_params: consult # OpenRouter's published capabilities instead of only the bundled @@ -742,7 +780,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - " pass\n" " try:\n" ), - "label": "Patch 7/9 (openrouter live capabilities)", + "label": "Patch 7/10 (openrouter live capabilities)", }, # Patch 8 — get_optional_params: log what ``drop_params`` discards. # @@ -791,7 +829,7 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - " for k in unsupported_params.keys():\n" " non_default_params.pop(k, None)\n" ), - "label": "Patch 8/9 (drop_params visibility)", + "label": "Patch 8/10 (drop_params visibility)", }, # Patch 9 — _translate_thinking_to_openai: stop synthesizing # ``reasoning_effort`` from the caller's ``thinking`` block for non-Claude @@ -884,7 +922,67 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - "\n" ' summary = thinking.get("summary") if isinstance(thinking, dict) else None\n' ), - "label": "Patch 9/9 (thinking->reasoning_effort synthesis gate)", + "label": "Patch 9/10 (thinking->reasoning_effort synthesis gate)", + }, + # Patch 10 — OpenrouterConfig.transform_request: carry prior-turn assistant + # reasoning back to the provider. + # + # The Anthropic adapter converts incoming ``thinking`` content blocks into + # ``assistant_message["thinking_blocks"]``, and nothing on the OpenRouter + # REQUEST path consumes that field: stock openrouter/chat/transformation.py + # names reasoning once, on the response side, and ``reasoning_details`` + # appears nowhere in llms/ or litellm_core_utils/. The parent + # ``transform_request`` drops ``messages`` straight into the body, so + # ``thinking_blocks`` reaches OpenRouter as a field no one reads and every + # historical assistant turn arrives with no reasoning attached. + # + # For a model whose chat template re-renders prior thinking that is a + # malformed history rather than a missed optimisation: Poolside Laguna + # renders ``'' + message.reasoning|message.reasoning_content + + # ''`` per historical assistant turn, so each one becomes a literal + # empty ````, which Poolside's model card warns degrades + # follow-up behaviour. + # + # DIRECTION: this is request-path (client -> provider). Patches 4, 5a and 5b + # are response-path (provider -> client). Adjacent, not the same thing. + # + # NEEDLE ANCHORING: ``_supports_cache_control_in_content`` appears twice in + # 1.86.2 (its own ``def`` and the call in + # ``remove_cache_control_flag_from_messages_and_tools``), and + # ``_move_cache_control_to_content`` likewise. Neither call alone is unique. + # The needle therefore spans the cache_control pair AND the following + # ``extra_body`` pop, a sequence that occurs only in ``transform_request``. + { + "file": F1, + "present": "# egg reasoning round-trip patch", + "needle": ( + " if self._supports_cache_control_in_content(model):\n" + " messages = self._move_cache_control_to_content(messages)\n" + "\n" + ' extra_body = optional_params.pop("extra_body", {})\n' + ), + "replacement": ( + " if self._supports_cache_control_in_content(model):\n" + " messages = self._move_cache_control_to_content(messages)\n" + "\n" + " # egg reasoning round-trip patch. The Anthropic adapter parks\n" + " # prior-turn assistant reasoning on `thinking_blocks`, which no\n" + " # OpenRouter request-path code reads; map it onto the field\n" + " # OpenRouter documents for multi-turn tool calling so models whose\n" + " # template re-renders prior thinking stop seeing empty .\n" + " # See patch 10 notes in patch_litellm_cache.py.\n" + " try:\n" + " from litellm.llms.openrouter._egg_reasoning_roundtrip import (\n" + " map_thinking_blocks_to_reasoning_content as _egg_map_reasoning,\n" + " )\n" + "\n" + " messages = _egg_map_reasoning(messages)\n" + " except Exception:\n" + " pass\n" + "\n" + ' extra_body = optional_params.pop("extra_body", {})\n' + ), + "label": "Patch 10/10 (assistant reasoning round-trip)", }, ] @@ -913,17 +1011,22 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - { "source": "openrouter_capabilities.py", "dest": "llms/openrouter/_egg_capabilities.py", - "label": "Module 1/3 (openrouter capabilities)", + "label": "Module 1/4 (openrouter capabilities)", }, { "source": "drop_params_visibility.py", "dest": "_egg_drop_params_visibility.py", - "label": "Module 2/3 (drop_params visibility)", + "label": "Module 2/4 (drop_params visibility)", }, { "source": "anthropic_thinking_policy.py", "dest": "_egg_anthropic_thinking_policy.py", - "label": "Module 3/3 (thinking synthesis policy)", + "label": "Module 3/4 (thinking synthesis policy)", + }, + { + "source": "openrouter_reasoning_roundtrip.py", + "dest": "llms/openrouter/_egg_reasoning_roundtrip.py", + "label": "Module 4/4 (openrouter reasoning round-trip)", }, ] diff --git a/tests/config/test_litellm_runtime_modules.py b/tests/config/test_litellm_runtime_modules.py index 6d80d644b..10bc7b6b7 100644 --- a/tests/config/test_litellm_runtime_modules.py +++ b/tests/config/test_litellm_runtime_modules.py @@ -625,3 +625,220 @@ def test_unrecognised_value_warning_survives_a_swallowed_emit_failure(policy, mo assert policy.should_synthesize_reasoning_effort() is False assert len(recorder.messages("warning")) == 1, "and dedup still holds once it is out" + + +# --- Module 4: openrouter reasoning round-trip ----------------------------- +# +# The adapter parks prior-turn assistant reasoning on ``thinking_blocks``, a +# field no OpenRouter request-path code reads. These lock in the mapping onto +# ``reasoning_content`` and, just as importantly, the cases that must NOT be +# rewritten: a request has to survive a block this never anticipated. + + +@pytest.fixture +def roundtrip(): + return _load("openrouter_reasoning_roundtrip") + + +def _thinking(text, signature="sig"): + return {"type": "thinking", "thinking": text, "signature": signature} + + +def test_assistant_thinking_becomes_reasoning_content(roundtrip): + """The whole point: the field the adapter writes reaches the field + OpenRouter reads, and the one it does not read stops being transmitted.""" + messages = [ + {"role": "user", "content": "hi"}, + { + "role": "assistant", + "content": "answer", + "thinking_blocks": [_thinking("because X")], + }, + ] + + out = roundtrip.map_thinking_blocks_to_reasoning_content(messages) + + assert out[1]["reasoning_content"] == "because X" + assert "thinking_blocks" not in out[1], "no unknown field may reach the provider" + assert out[1]["content"] == "answer", "the rest of the message is untouched" + + +def test_anthropic_signature_is_not_forwarded(roundtrip): + """``signature`` is an Anthropic re-verification token; it means nothing to + OpenRouter, so it must not ride along in any shape.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": [_thinking("t", signature="deadbeef")]}] + ) + + assert out[0]["reasoning_content"] == "t" + assert "deadbeef" not in repr(out[0]) + + +def test_multiple_blocks_concatenate_in_order(roundtrip): + """Order is the content: reasoning read back out of sequence is worse than + no reasoning at all.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [ + { + "role": "assistant", + "thinking_blocks": [_thinking("first "), _thinking("second "), _thinking("third")], + } + ] + ) + + assert out[0]["reasoning_content"] == "first second third" + + +def test_redacted_thinking_is_skipped(roundtrip): + """A ``redacted_thinking`` block carries opaque ``data``, not text. There is + nothing to send, and inventing an empty string would put the very + ```` this patch exists to remove back into the prompt.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [ + { + "role": "assistant", + "thinking_blocks": [ + {"type": "redacted_thinking", "data": "opaque"}, + _thinking("visible"), + ], + } + ] + ) + + assert out[0]["reasoning_content"] == "visible", "redacted contributes nothing" + assert "opaque" not in repr(out[0]) + + +def test_only_redacted_blocks_emit_no_field_at_all(roundtrip): + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": [{"type": "redacted_thinking", "data": "d"}]}] + ) + + assert "reasoning_content" not in out[0] + assert "thinking_blocks" not in out[0], "still stripped: no unknown field on the wire" + + +@pytest.mark.parametrize("text", ["", " ", "\n\t "]) +def test_whitespace_only_reasoning_emits_nothing(roundtrip, text): + """Empty reasoning is not reasoning. Emitting it renders as an empty + ```` on templates that re-render prior thinking.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": [_thinking(text)]}] + ) + + assert "reasoning_content" not in out[0] + assert "thinking_blocks" not in out[0] + + +@pytest.mark.parametrize("role", ["user", "system", "tool"]) +def test_non_assistant_messages_are_never_touched(roundtrip, role): + """Assistant turns only. A ``thinking_blocks`` key on any other role is not + ours to reinterpret, so it passes through byte-identical.""" + original = {"role": role, "content": "c", "thinking_blocks": [_thinking("t")]} + + out = roundtrip.map_thinking_blocks_to_reasoning_content([dict(original)]) + + assert out[0] == original + assert "reasoning_content" not in out[0] + + +def test_assistant_without_thinking_blocks_is_returned_as_is(roundtrip): + original = {"role": "assistant", "content": "plain"} + + out = roundtrip.map_thinking_blocks_to_reasoning_content([original]) + + assert out[0] is original, "no copy, no rewrite, nothing to do" + + +@pytest.mark.parametrize( + "blocks", + [ + "not-a-list", + {"type": "thinking"}, + 17, + [None], + ["bare string"], + [{"type": "thinking", "thinking": None}], + [{"type": "thinking"}], + [{}], + ], +) +def test_malformed_blocks_never_raise(roundtrip, blocks): + """Fail soft. A shape this did not anticipate must cost the reasoning, not + the request.""" + messages = [{"role": "assistant", "content": "c", "thinking_blocks": blocks}] + + out = roundtrip.map_thinking_blocks_to_reasoning_content(messages) + + assert len(out) == 1 + assert out[0]["role"] == "assistant" + assert out[0]["content"] == "c" + assert "reasoning_content" not in out[0], "nothing parseable, so nothing emitted" + + +def test_a_malformed_sibling_does_not_cost_a_good_block(roundtrip): + """One bad entry in the list should not discard the reasoning that parsed + fine beside it.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [ + { + "role": "assistant", + "thinking_blocks": [ + _thinking("kept "), + None, + {"type": "thinking"}, + _thinking("too"), + ], + } + ] + ) + + assert out[0]["reasoning_content"] == "kept too" + + +def test_unparseable_blocks_field_leaves_the_message_untouched(roundtrip): + """``thinking_blocks`` that is not a list at all is a shape we do not + understand; the message goes to the provider exactly as it arrived rather + than being half-rewritten.""" + original = {"role": "assistant", "content": "c", "thinking_blocks": "not-a-list"} + + out = roundtrip.map_thinking_blocks_to_reasoning_content([dict(original)]) + + assert out[0] == original, "untouched, including the field we could not read" + + +def test_input_messages_are_not_mutated(roundtrip): + """litellm hands us the caller's list; rewriting it in place would leak + into logging and retries.""" + block = _thinking("t") + messages = [{"role": "assistant", "content": "a", "thinking_blocks": [block]}] + before = [{"role": "assistant", "content": "a", "thinking_blocks": [dict(block)]}] + + roundtrip.map_thinking_blocks_to_reasoning_content(messages) + + assert messages == before + + +def test_mapping_is_idempotent(roundtrip): + """Applying twice is a no-op: after the first pass there is no + ``thinking_blocks`` left to map, and ``reasoning_content`` is preserved.""" + messages = [{"role": "assistant", "content": "a", "thinking_blocks": [_thinking("why")]}] + + once = roundtrip.map_thinking_blocks_to_reasoning_content(messages) + twice = roundtrip.map_thinking_blocks_to_reasoning_content(once) + + assert twice == once + assert twice[0]["reasoning_content"] == "why" + + +def test_non_list_messages_pass_through(roundtrip): + assert roundtrip.map_thinking_blocks_to_reasoning_content(None) is None + assert roundtrip.map_thinking_blocks_to_reasoning_content("nope") == "nope" + + +def test_module_imports_without_litellm_installed(roundtrip): + """Same contract as the other three staged modules: no litellm import at + module scope, or it could not be tested here at all.""" + source = (CONFIG_DIR / "openrouter_reasoning_roundtrip.py").read_text() + assert "import litellm" not in source + assert "from litellm" not in source diff --git a/tests/config/test_patch_litellm_cache.py b/tests/config/test_patch_litellm_cache.py index 7079440aa..1a46fb11a 100644 --- a/tests/config/test_patch_litellm_cache.py +++ b/tests/config/test_patch_litellm_cache.py @@ -554,3 +554,82 @@ def test_patch8_needle_disambiguates_the_two_drop_sites(tmp_path): start = result.index("SENTINEL_PASS_SITE_BEGIN") end = result.index("SENTINEL_PASS_SITE_END") + len("SENTINEL_PASS_SITE_END\n") assert result[start:end] == sibling, "patch 8 rewrote the embeddings-path drop site" + + +def test_patch10_needle_anchors_on_transform_request(tmp_path): + """Patch 10 must land in ``transform_request`` and nowhere else. + + Both cache_control helpers are *named twice* in 1.86.2: each has its own + ``def``, and ``remove_cache_control_flag_from_messages_and_tools`` calls + ``_supports_cache_control_in_content`` too. A needle built from either call + alone could retarget after an upstream reorder — the same trap Patches 4 + and 8 document. The needle therefore runs through the ``extra_body`` pop, + which happens only here.""" + patch10 = next(p for p in plc.PATCHES if p["label"].startswith("Patch 10/")) + + # A sibling that mentions the same helper, ahead of the real site. + sibling = ( + " def remove_cache_control_flag_from_messages_and_tools(\n" + " self, model, messages, tools=None\n" + " ):\n" + " if self._supports_cache_control_in_content(model):\n" + " return messages, tools\n" + ) + target = tmp_path / patch10["file"] + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(sibling + "\n" + patch10["needle"]) + + plc._apply( + str(target), + present=patch10["present"], + needle=patch10["needle"], + replacement=patch10["replacement"], + label=patch10["label"], + ) + result = target.read_text() + + assert sibling in result, "the sibling call site must be left alone" + inserted_at = result.index(patch10["present"]) + assert inserted_at > result.index(sibling), "patch 10 must land after the sibling" + + +def test_patch10_preserves_the_cache_control_step(tmp_path): + """Patch 10 shares its needle with Patch 1's file and sits directly on top + of the cache_control rewrite. Asserting on the RESULT (rather than on the + replacement literal) is what catches a patch that dropped that step while + inserting its own.""" + patch10 = next(p for p in plc.PATCHES if p["label"].startswith("Patch 10/")) + + target = tmp_path / patch10["file"] + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(patch10["needle"]) + + plc._apply( + str(target), + present=patch10["present"], + needle=patch10["needle"], + replacement=patch10["replacement"], + label=patch10["label"], + ) + result = target.read_text() + + # The cache_control step survives, and still precedes the extra_body pop. + assert "messages = self._move_cache_control_to_content(messages)" in result + assert result.index("_move_cache_control_to_content") < result.index("_egg_map_reasoning") + assert result.index("_egg_map_reasoning") < result.index('optional_params.pop("extra_body"') + + # The mapping runs on the REQUEST path, and a failure in it cannot + # propagate into the request. + assert "except Exception:" in result + assert "_egg_reasoning_roundtrip" in result + + +def test_patch10_maps_onto_the_request_not_the_response(tmp_path): + """Guard against the adjacent-patch confusion the docstring calls out: + patches 4/5a/5b are provider -> client, this one is client -> provider. + A patch that touched ``transform_response`` would be a different bug.""" + patch10 = next(p for p in plc.PATCHES if p["label"].startswith("Patch 10/")) + + assert "transform_response" not in patch10["needle"] + assert "transform_response" not in patch10["replacement"] + assert patch10["file"] == plc.F1 From 97feafff0409f33d4d4f14301b1d875c14f1307e Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Wed, 29 Jul 2026 05:42:42 +0000 Subject: [PATCH 2/2] litellm: fix Patch 10 None sentinel, scope it, and surface it Review feedback on #3698. The adapter sets thinking_blocks=None (key present, TypedDict) on every assistant turn that produced no reasoning, so the key-presence guard sent that value into _extract_reasoning_text, which raised, which routed the dominant message shape through the fail-soft branch: "thinking_blocks": null still reached OpenRouter, and the branch reserved for corruption became the hot path. It is now read as the sentinel it is. Also: decline anthropic/* and google/* slugs, whose upstream re-verifies the block signature this plain-string form cannot carry; join blocks on a newline rather than running them together; never overwrite a reasoning_content the caller already set; log an unmappable shape and an unavailable module once each; add LITELLM_OPENROUTER_REASONING_ROUNDTRIP=0 as a runtime escape hatch, as for Patches 7 and 9; refresh the four stale doc/test references to the patch and module counts. --- .../litellm/openrouter_reasoning_roundtrip.py | 224 +++++++++++++++-- config/litellm/patch_litellm_cache.py | 51 +++- docs/development/STRUCTURE.md | 3 +- docs/guides/per-agent-models.md | 23 +- k8s/base/litellm-deployment.yaml | 11 + tests/config/test_litellm_runtime_modules.py | 234 ++++++++++++++++-- tests/config/test_patch_litellm_cache.py | 28 +++ 7 files changed, 523 insertions(+), 51 deletions(-) diff --git a/config/litellm/openrouter_reasoning_roundtrip.py b/config/litellm/openrouter_reasoning_roundtrip.py index eda7f2dce..02206f733 100644 --- a/config/litellm/openrouter_reasoning_roundtrip.py +++ b/config/litellm/openrouter_reasoning_roundtrip.py @@ -27,8 +27,37 @@ this for exactly this multi-turn tool-calling case; Poolside's template reads ``message.reasoning`` / ``message.reasoning_content``. We send the plain string form, which satisfies both: ``reasoning_details`` exists to carry encrypted or -summarised blocks, and we have neither. Anthropic ``signature`` values are -meaningless to OpenRouter and are not forwarded. +summarised blocks, and we have neither. + +Three boundaries are deliberate and worth stating outright. + +**The adapter's "no thinking" sentinel is not a bad shape.** +``ChatCompletionAssistantMessage`` is a ``TypedDict``, so the adapter's +``thinking_blocks=(blocks if len(blocks) > 0 else None)`` leaves the key +*present and None* on every assistant turn that reasoned about nothing — the +majority of turns on any route, and every turn on a route that returns no +reasoning at all. That is the dominant input to this module, not an edge case: +it is read as "nothing to map", the key is dropped, and no field is emitted. + +**Signature-verifying providers are out of scope.** For an Anthropic or Google +model reached *through* OpenRouter, the ``signature`` on a thinking block is +not decoration — it is what the upstream verifies when prior thinking is +replayed on a tool-calling turn, and OpenRouter's own docs carry it inside +``reasoning_details`` with "pass back unmodified; you cannot rearrange or +modify the sequence of these blocks". Flattening N ordered blocks into one +string and discarding their signatures is precisely what those routes must not +receive, so this module declines to rewrite them at all and leaves the message +byte-identical to what stock LiteLLM would have sent — a known-working state, +since stock has never mapped this field. egg pins no such slug today, but +``CacheControlSupportedModels`` in the patched file already carries ``CLAUDE`` +and ``GEMINI``, so the route is anticipated rather than hypothetical. Emitting +a proper ``reasoning_details`` for them is a separate change with a separate +wire shape to verify. + +**A ``reasoning_content`` the caller already set wins.** litellm's own response +objects carry both fields, so any client echoing an assistant message back +sends both. One rule covers both branches: a non-empty ``reasoning_content`` +already on the message is never overwritten, whatever the blocks yield. The gap is upstream's, not egg's: it predates every egg and ``jwbron/litellm`` change, and the fork's OpenRouter work (jwbron/litellm#8) is confined to @@ -38,10 +67,26 @@ Note the direction. Patches 4, 5a and 5b are response-path (provider -> client): they fix how reasoning is *streamed back*. This is request-path (client -> provider). They are adjacent, not the same thing. + +Set ``LITELLM_OPENROUTER_REASONING_ROUNDTRIP=0`` to restore stock behaviour +(``thinking_blocks`` transmitted, no reasoning field) without rebuilding the +image — the same runtime escape hatch Patches 7 and 9 carry, and for the same +reason: this one changes the outgoing body on every OpenRouter call, and its +correctness rests on provider-side behaviour verified against two models. A +value that is neither a recognised on nor off spelling warns once and takes the +default rather than being read as off. """ +import os from typing import Any +ENV_VAR = "LITELLM_OPENROUTER_REASONING_ROUNDTRIP" + +_TRUTHY = ("1", "true", "yes", "on") +# An empty value counts as off, matching ``anthropic_thinking_policy``: an env +# var set to nothing is an operator clearing a knob, not a typo. +_FALSY = ("0", "false", "no", "off", "") + # Blocks the adapter can put on ``thinking_blocks``. ``redacted_thinking`` # carries an opaque ``data`` payload rather than text (see # ``ChatCompletionRedactedThinkingBlock``); there is no plaintext to hand a @@ -52,16 +97,111 @@ _SOURCE_FIELD = "thinking_blocks" _TARGET_FIELD = "reasoning_content" +# Blocks are separate thoughts, not a single stream that happens to be split: +# the adapter emits one per ``thinking`` content block, and Claude Code +# interleaves them with text and tool_use inside one assistant turn. Joining on +# "" runs the last word of one into the first word of the next, which is how a +# ```` re-render would then read it. +_BLOCK_SEPARATOR = "\n" + +# Substrings that mark a provider whose reasoning is signature-verified when +# replayed. Matched against the slug OpenRouter routes on +# (``anthropic/claude-...``, ``google/gemini-...``), so the test is a substring +# rather than a prefix: litellm may or may not have stripped its own +# ``openrouter/`` prefix by the time ``transform_request`` runs. +_SIGNATURE_VERIFYING_MARKERS = ("anthropic", "claude", "google", "gemini") + +# Diagnostics already emitted. Bounded by construction: one entry per distinct +# key below, and the keys are literals in this file. Needed because everything +# here sits on the per-request path. +_WARNED: set[str] = set() + + +def _log(level: str, message: str, *args: object) -> bool: + """Log via litellm's ``verbose_logger``, deferring the import. + + Kept out of module scope so this file stays importable — and therefore unit + testable — where litellm is not installed. Never raises: a diagnostic must + not be able to break a request. + + Returns whether the call completed without raising, not whether a record + reached a handler; see the same note in ``openrouter_capabilities._log``. + """ + try: + from litellm._logging import verbose_logger + + getattr(verbose_logger, level)(message, *args) + return True + except Exception: # noqa: BLE001 - diagnostics must never break a request + return False + + +def _warn_once(key: str, message: str, *args: object) -> None: + """Warn at most once per ``key`` for the life of the process. + + Recorded only once the emit did not raise, for the reason given in + ``openrouter_capabilities._warn_env_once``: ``_log`` swallows its own + failure, so recording first would let a logger that is not yet in place on + the first request suppress the warning permanently. + """ + if key in _WARNED: + return + if _log("warning", message, *args): + _WARNED.add(key) + + +def is_enabled() -> bool: + """Whether the round-trip mapping should run at all. + + Defaults to True — the mapping is the patch. ``0`` (and the other off + spellings) backs it out of a live cluster without an image rebuild. + """ + raw = os.getenv(ENV_VAR) + if raw is None: + return True + value = raw.strip().lower() + if value in _TRUTHY: + return True + if value in _FALSY: + return False + _warn_once( + f"env:{value}", + "openrouter reasoning round-trip: %s=%r is neither an on (%s) nor an " + "off (%s) spelling; leaving the mapping enabled, which is also the " + "default — set %s=0 if you meant to disable it.", + ENV_VAR, + raw, + ", ".join(_TRUTHY), + ", ".join(v for v in _FALSY if v), + ENV_VAR, + ) + return True + + +def provider_verifies_reasoning_signatures(model: Any) -> bool: + """Whether ``model``'s upstream re-verifies replayed reasoning. + + See the docstring above: for those routes the signature and the block + boundaries are load-bearing, and the plain-string form this module emits + would destroy both. A non-string model is not a slug we can reason about, + so it is treated as ordinary rather than as a match. + """ + if not isinstance(model, str): + return False + slug = model.lower() + return any(marker in slug for marker in _SIGNATURE_VERIFYING_MARKERS) + def _extract_reasoning_text(blocks: Any) -> str: """Concatenate the plaintext of ``blocks``, in order. - Non-dict entries, entries of any type other than ``thinking``, and entries - whose ``thinking`` is not a string are skipped individually rather than - failing the whole message: one malformed block should not cost us the - reasoning from its well-formed siblings. A ``blocks`` that is not a list at - all is a shape we do not understand, and the caller leaves the message - untouched. + Non-dict entries, entries of any type other than ``thinking``, entries + whose ``thinking`` is not a string, and entries whose text is blank are + skipped individually rather than failing the whole message: one malformed + block should not cost us the reasoning from its well-formed siblings, and a + blank one should not contribute a bare separator. A ``blocks`` that is not + a list at all is a shape we do not understand, and the caller leaves the + message untouched. """ if not isinstance(blocks, list): raise TypeError(f"{_SOURCE_FIELD} is {type(blocks).__name__}, expected list") @@ -72,30 +212,38 @@ def _extract_reasoning_text(blocks: Any) -> str: if block.get("type") != _THINKING_BLOCK_TYPE: continue text = block.get(_THINKING_BLOCK_TYPE) - if isinstance(text, str): + if isinstance(text, str) and text.strip(): parts.append(text) - return "".join(parts) + return _BLOCK_SEPARATOR.join(parts) -def map_thinking_blocks_to_reasoning_content(messages: Any) -> Any: +def map_thinking_blocks_to_reasoning_content(messages: Any, model: Any = None) -> Any: """Return ``messages`` with assistant reasoning moved to the wire field. For each assistant message carrying ``thinking_blocks``: drop that field so no unknown key is transmitted, and set ``reasoning_content`` to the - concatenated plaintext when there is any. A message whose blocks yield only - whitespace (or nothing at all, e.g. ``redacted_thinking`` only) loses the - field and gains nothing, which is what OpenRouter would have received - anyway minus the noise. + concatenated plaintext when there is any and the message does not already + carry a non-empty ``reasoning_content`` of its own. A message whose blocks + yield only whitespace — or nothing at all, which is the adapter's + ``thinking_blocks: None`` sentinel and its ``redacted_thinking``-only case + — loses the field and gains nothing, which is what OpenRouter would have + received anyway minus the noise. User, system and tool messages are returned untouched, as is any assistant - message with no ``thinking_blocks`` key. Input is not mutated: touched - messages are shallow-copied. + message with no ``thinking_blocks`` key. ``messages`` is returned unchanged + in full when the knob is off or when ``model`` names a provider that + re-verifies replayed reasoning. Input is not mutated: touched messages are + shallow-copied. Never raises. A message this function cannot make sense of is passed through exactly as it arrived, so the worst case is stock behaviour. """ if not isinstance(messages, list): return messages + if not is_enabled(): + return messages + if provider_verifies_reasoning_signatures(model): + return messages out: list[Any] = [] for message in messages: @@ -107,19 +255,49 @@ def map_thinking_blocks_to_reasoning_content(messages: Any) -> Any: out.append(message) continue - text = _extract_reasoning_text(message.get(_SOURCE_FIELD)) + blocks = message.get(_SOURCE_FIELD) + if blocks is None: + # The adapter's own "this turn produced no thinking" sentinel, + # not a shape we failed to parse. Reading it as the latter + # would leave ``thinking_blocks: null`` on the wire for the + # majority of assistant turns AND route ordinary traffic + # through the branch reserved for corruption below. + blocks = [] + text = _extract_reasoning_text(blocks) updated: dict[str, Any] = dict(message) updated.pop(_SOURCE_FIELD, None) - # Whitespace-only reasoning is not reasoning; emitting it would put - # an empty in the rendered prompt, which is the - # exact failure this patch exists to remove. - if text.strip(): + existing = updated.get(_TARGET_FIELD) + if isinstance(existing, str) and existing.strip(): + # The caller stated this field outright; the blocks are a + # second rendering of the same reasoning. One rule, applied + # whether or not the blocks yield text: we do not overwrite it. + pass + elif text.strip(): + # Whitespace-only reasoning is not reasoning; emitting it would + # put an empty in the rendered prompt, which is + # the exact failure this patch exists to remove. updated[_TARGET_FIELD] = text out.append(updated) except Exception: # noqa: BLE001 - a request must survive a bad block + # With the sentinel handled above this branch means a genuinely + # unrecognised shape, so it is worth exactly one line: silence here + # is how a mapping that quietly stopped working would look. + _warn_once( + "unmappable-message", + "openrouter reasoning round-trip: could not map %r on an " + "assistant message; sending it as it arrived (stock " + "behaviour). Reasoning from prior turns may not reach the " + "provider. Logged once per proxy process.", + _SOURCE_FIELD, + ) out.append(message) return out -__all__ = ["map_thinking_blocks_to_reasoning_content"] +__all__ = [ + "ENV_VAR", + "is_enabled", + "map_thinking_blocks_to_reasoning_content", + "provider_verifies_reasoning_signatures", +] diff --git a/config/litellm/patch_litellm_cache.py b/config/litellm/patch_litellm_cache.py index 16306dd90..9043caff8 100644 --- a/config/litellm/patch_litellm_cache.py +++ b/config/litellm/patch_litellm_cache.py @@ -178,12 +178,24 @@ plain string form OpenRouter documents for exactly this multi-turn tool-calling case and the field Poolside's template reads; ``reasoning_details`` exists to carry encrypted or summarised - blocks and we have neither. ``redacted_thinking`` blocks contribute - nothing (no plaintext to send), Anthropic ``signature`` values are - not forwarded (meaningless to OpenRouter), and ``thinking_blocks`` - is removed either way so no unknown field is transmitted. Fails - soft per message: a block it cannot parse leaves that message - exactly as it arrived. NOTE the DIRECTION — this is request-path + blocks and we have neither. Blocks join on a newline (they are + separate thoughts, and "" runs the last word of one into the first + of the next), ``redacted_thinking`` blocks contribute nothing (no + plaintext to send), a ``reasoning_content`` the caller already set + is never overwritten, and ``thinking_blocks`` is removed either way + — including for the adapter's ``thinking_blocks: None`` sentinel, + which it sets on every assistant turn that reasoned about nothing + and which is therefore the DOMINANT input, not an edge case — so no + unknown field is transmitted. Two whole-request opt-outs: the + module declines any slug whose upstream re-verifies replayed + reasoning (``anthropic``/``google``, where the discarded + ``signature`` and the flattened block order are load-bearing and + OpenRouter's ``reasoning_details`` is the right shape — a separate + change), and ``LITELLM_OPENROUTER_REASONING_ROUNDTRIP=0`` backs the + patch out of a live cluster without an image rebuild, as for + patches 7 and 9. Fails soft per message: a block it cannot parse + leaves that message exactly as it arrived, and says so once. + NOTE the DIRECTION — this is request-path (client -> provider); patches 4, 5a and 5b are response-path (provider -> client). Adjacent, not the same thing. The gap is upstream's and predates every egg and fork change: jwbron/litellm#8 @@ -970,15 +982,36 @@ def _apply(path: str, present: str, needle: str, replacement: str, label: str) - " # OpenRouter request-path code reads; map it onto the field\n" " # OpenRouter documents for multi-turn tool calling so models whose\n" " # template re-renders prior thinking stop seeing empty .\n" + " # `model` is passed so the module can decline the routes whose\n" + " # upstream re-verifies replayed reasoning (anthropic/*, google/*).\n" " # See patch 10 notes in patch_litellm_cache.py.\n" " try:\n" " from litellm.llms.openrouter._egg_reasoning_roundtrip import (\n" " map_thinking_blocks_to_reasoning_content as _egg_map_reasoning,\n" " )\n" "\n" - " messages = _egg_map_reasoning(messages)\n" - " except Exception:\n" - " pass\n" + " messages = _egg_map_reasoning(messages, model)\n" + " except Exception as _egg_roundtrip_exc:\n" + " # The module is installed by the same build step as this patch,\n" + " # so this is unreachable in a built image. Say so once rather\n" + " # than reverting to stock in silence — an invisible no-op here\n" + " # shows up only as a model quietly reasoning worse, which is\n" + " # the condition patch 8 exists to stop repeating.\n" + " try:\n" + " from litellm._logging import verbose_logger\n" + "\n" + " if not getattr(\n" + ' verbose_logger, "_egg_reasoning_roundtrip_warned", False\n' + " ):\n" + " verbose_logger.warning(\n" + ' "egg reasoning round-trip module unavailable (%s); "\n' + ' "prior-turn assistant reasoning will not reach "\n' + ' "OpenRouter. Logged once per proxy process.",\n' + " _egg_roundtrip_exc,\n" + " )\n" + " verbose_logger._egg_reasoning_roundtrip_warned = True\n" + " except Exception:\n" + " pass\n" "\n" ' extra_body = optional_params.pop("extra_body", {})\n' ), diff --git a/docs/development/STRUCTURE.md b/docs/development/STRUCTURE.md index e65079bf4..02bd5cefd 100644 --- a/docs/development/STRUCTURE.md +++ b/docs/development/STRUCTURE.md @@ -542,10 +542,11 @@ config/ ├── routing-policy.template.yaml # Operator template for the gateway's hot-reloadable model routing policy: switchover remaps + fallback chains (copy to ~/.config/egg/routing-policy.yaml) ├── litellm/ # egg-litellm image sources │ ├── Dockerfile # Builds egg-litellm: stock LiteLLM + prompt-cache and reasoning-parameter patches -│ ├── patch_litellm_cache.py # Build-time patches: cache_control passthrough on Qwen/DeepSeek routes, live OpenRouter capability lookup, drop_params visibility, no synthesized reasoning ceiling +│ ├── patch_litellm_cache.py # Build-time patches: cache_control passthrough on Qwen/DeepSeek routes, live OpenRouter capability lookup, drop_params visibility, no synthesized reasoning ceiling, prior-turn reasoning round-trip │ ├── openrouter_capabilities.py # Patch 7: live GET /api/v1/models capability lookup, unioned with LiteLLM's bundled model-cost map │ ├── drop_params_visibility.py # Patch 8: warn once per proxy process per (provider, model, param-set) when drop_params discards a parameter │ ├── anthropic_thinking_policy.py # Patch 9: stop synthesizing a reasoning_effort ceiling from the caller's thinking budget on non-Claude models +│ ├── openrouter_reasoning_roundtrip.py # Patch 10: map prior-turn assistant thinking_blocks onto reasoning_content so OpenRouter models that re-render prior thinking stop seeing empty │ └── cost_callback.py # LiteLLM custom logger: upstream + estimated cost, per-role attribution (x-egg-* headers), cache hit rate, per-call decoding config -> pod stdout ├── redis/ # egg-redis image sources │ └── Dockerfile # Builds egg-redis: pinned stock Redis, repackaged for the local build/publish supply chain; backs the orchestrator's Redis Streams message store diff --git a/docs/guides/per-agent-models.md b/docs/guides/per-agent-models.md index 31a51f09b..234261d22 100644 --- a/docs/guides/per-agent-models.md +++ b/docs/guides/per-agent-models.md @@ -593,7 +593,7 @@ data: > Claude Code prepends (the block's `cch=` hash invalidates the cache key > every turn). egg ships a custom **`egg-litellm`** image > ([`config/litellm/Dockerfile`](../../config/litellm/Dockerfile)) that -> bakes in nine patches closing those gaps and the reasoning-parameter ones +> bakes in ten patches closing those gaps and the reasoning-parameter ones > below > ([`config/litellm/patch_litellm_cache.py`](../../config/litellm/patch_litellm_cache.py)); > the build fails loudly if a LiteLLM bump moves the patched code. Pinning @@ -609,9 +609,10 @@ data: > line to the LiteLLM pod stream, visible via `get_service_logs` / the > structured-logging stream. -> **Reasoning depth on OpenRouter routes, and the four env vars that -> control it.** Two of the baked-in patches decide whether a reasoning -> parameter reaches the provider, and both are runtime-overridable on +> **Reasoning depth on OpenRouter routes, and the five env vars that +> control it.** Three of the baked-in patches decide what reasoning a +> provider sees — two whether a reasoning *parameter* reaches it, one +> whether prior-turn reasoning does — and all three are runtime-overridable on > [`k8s/base/litellm-deployment.yaml`](../../k8s/base/litellm-deployment.yaml) > (where they are present but commented out) without rebuilding the image: > @@ -644,6 +645,20 @@ data: > adaptive request that names an effort outright > (`output_config: {effort: ...}`) is an instruction rather than a > manufactured ceiling, and still reaches the provider with this off. +> - **Patch 10 — prior-turn reasoning actually reaches the provider.** The +> same adapter parks each historical assistant turn's thinking on a +> `thinking_blocks` field that no OpenRouter request-path code reads, so +> every previous turn arrived with its reasoning missing. On a model whose +> chat template re-renders prior thinking (Poolside Laguna renders +> `{{ message.reasoning_content }}` per assistant turn) +> that is a malformed history, not a lost optimisation. The patch maps +> those blocks onto `reasoning_content`, the field OpenRouter documents +> for multi-turn tool calling. `LITELLM_OPENROUTER_REASONING_ROUNDTRIP=0` +> restores stock behaviour. Two things it deliberately does not do: +> Anthropic- and Google-via-OpenRouter slugs are left untouched (their +> upstream re-verifies the block `signature` this plain-string form cannot +> carry), and a `reasoning_content` the caller already set is never +> overwritten. > > The same measurement is why the commented-out > `extra_body.reasoning.effort: "high"` in diff --git a/k8s/base/litellm-deployment.yaml b/k8s/base/litellm-deployment.yaml index b555d8052..ec8145b19 100644 --- a/k8s/base/litellm-deployment.yaml +++ b/k8s/base/litellm-deployment.yaml @@ -121,6 +121,17 @@ spec: # measured to need an explicit ask. # - name: LITELLM_ANTHROPIC_THINKING_TO_REASONING_EFFORT # value: "1" + # + # Patch 10 — prior-turn assistant reasoning round-trip, on by + # default. ``0`` restores stock LiteLLM: the reasoning of every + # historical assistant turn rides to OpenRouter on a + # ``thinking_blocks`` field no request-path code reads, so models + # whose chat template re-renders prior thinking (Poolside Laguna) + # see an empty per turn. This is the one patch that + # changes the outgoing request body on every OpenRouter call, so it + # is the one worth being able to back out without a rebuild. + # - name: LITELLM_OPENROUTER_REASONING_ROUNDTRIP + # value: "0" livenessProbe: httpGet: path: /health/liveliness diff --git a/tests/config/test_litellm_runtime_modules.py b/tests/config/test_litellm_runtime_modules.py index 10bc7b6b7..67a1888e5 100644 --- a/tests/config/test_litellm_runtime_modules.py +++ b/tests/config/test_litellm_runtime_modules.py @@ -1,7 +1,8 @@ -"""Unit tests for the three modules the patch script installs into litellm. +"""Unit tests for the four modules the patch script installs into litellm. ``config/litellm/{openrouter_capabilities,drop_params_visibility, -anthropic_thinking_policy}.py`` are staged by the Dockerfile and copied into +anthropic_thinking_policy,openrouter_reasoning_roundtrip}.py`` are staged by +the Dockerfile and copied into every litellm tree by ``patch_litellm_cache.py``. They are kept as real files rather than string literals inside the patch script precisely so they can be linted and tested here — but that only works if they import without litellm @@ -455,6 +456,7 @@ def test_module_imports_without_litellm(monkeypatch): assert _load("openrouter_capabilities") is not None assert _load("drop_params_visibility") is not None assert _load("anthropic_thinking_policy") is not None + assert _load("openrouter_reasoning_roundtrip") is not None # -------------------------------------------------------------------------- @@ -636,8 +638,12 @@ def test_unrecognised_value_warning_survives_a_swallowed_emit_failure(policy, mo @pytest.fixture -def roundtrip(): - return _load("openrouter_reasoning_roundtrip") +def roundtrip(monkeypatch): + module = _load("openrouter_reasoning_roundtrip") + module._WARNED.clear() + # Never let a test inherit a stray value from the ambient environment. + monkeypatch.delenv(module.ENV_VAR, raising=False) + return module def _thinking(text, signature="sig"): @@ -681,12 +687,40 @@ def test_multiple_blocks_concatenate_in_order(roundtrip): [ { "role": "assistant", - "thinking_blocks": [_thinking("first "), _thinking("second "), _thinking("third")], + "thinking_blocks": [_thinking("first"), _thinking("second"), _thinking("third")], } ] ) - assert out[0]["reasoning_content"] == "first second third" + assert out[0]["reasoning_content"] == "first\nsecond\nthird" + + +def test_blocks_are_separated_rather_than_run_together(roundtrip): + """The adapter emits one block per ``thinking`` content block, so adjacent + blocks are separate thoughts. Joining on "" runs the last word of one into + the first word of the next — ``...decided.We then...`` — which is exactly + how a ```` re-render would read it back.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": [_thinking("decided."), _thinking("We then")]}] + ) + + assert out[0]["reasoning_content"] == "decided.\nWe then" + assert "decided.We" not in out[0]["reasoning_content"] + + +def test_a_blank_block_contributes_no_bare_separator(roundtrip): + """A block with nothing in it must not turn into a leading or doubled + newline, which would render as an empty thought.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [ + { + "role": "assistant", + "thinking_blocks": [_thinking(" "), _thinking("real"), _thinking("")], + } + ] + ) + + assert out[0]["reasoning_content"] == "real" def test_redacted_thinking_is_skipped(roundtrip): @@ -743,6 +777,9 @@ def test_non_assistant_messages_are_never_touched(roundtrip, role): def test_assistant_without_thinking_blocks_is_returned_as_is(roundtrip): + """The key genuinely absent — a message this module never saw the adapter + build. Contrast ``thinking_blocks: None`` below, which is what the adapter + actually emits for a turn that produced no thinking.""" original = {"role": "assistant", "content": "plain"} out = roundtrip.map_thinking_blocks_to_reasoning_content([original]) @@ -750,6 +787,34 @@ def test_assistant_without_thinking_blocks_is_returned_as_is(roundtrip): assert out[0] is original, "no copy, no rewrite, nothing to do" +def test_adapter_none_sentinel_is_stripped_not_treated_as_malformed(roundtrip): + """``ChatCompletionAssistantMessage`` is a ``TypedDict``, so the adapter's + ``thinking_blocks=(blocks if len(blocks) > 0 else None)`` leaves the key + PRESENT with value ``None`` on every assistant turn that reasoned about + nothing. That is the dominant input on any route — and every turn on a + route that returns no reasoning at all — so reading it as an unparseable + shape would ship ``"thinking_blocks": null`` to OpenRouter on the majority + of turns, exactly the unknown field this patch promises to remove.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "content": "hi", "thinking_blocks": None}] + ) + + assert "thinking_blocks" not in out[0], "the sentinel must be stripped, not passed through" + assert "reasoning_content" not in out[0], "no reasoning to emit" + assert out[0]["content"] == "hi" + + +def test_none_sentinel_does_not_fire_the_fail_soft_diagnostic(roundtrip, logger): + """The last-resort branch must stay last-resort. If the commonest message + shape routes through it, a later log line or counter there fires on ~100% + of traffic and a genuinely malformed block becomes unfindable.""" + roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "content": "hi", "thinking_blocks": None}] + ) + + assert logger.messages() == [] + + @pytest.mark.parametrize( "blocks", [ @@ -784,7 +849,7 @@ def test_a_malformed_sibling_does_not_cost_a_good_block(roundtrip): { "role": "assistant", "thinking_blocks": [ - _thinking("kept "), + _thinking("kept"), None, {"type": "thinking"}, _thinking("too"), @@ -793,7 +858,7 @@ def test_a_malformed_sibling_does_not_cost_a_good_block(roundtrip): ] ) - assert out[0]["reasoning_content"] == "kept too" + assert out[0]["reasoning_content"] == "kept\ntoo" def test_unparseable_blocks_field_leaves_the_message_untouched(roundtrip): @@ -836,9 +901,150 @@ def test_non_list_messages_pass_through(roundtrip): assert roundtrip.map_thinking_blocks_to_reasoning_content("nope") == "nope" -def test_module_imports_without_litellm_installed(roundtrip): - """Same contract as the other three staged modules: no litellm import at - module scope, or it could not be tested here at all.""" - source = (CONFIG_DIR / "openrouter_reasoning_roundtrip.py").read_text() - assert "import litellm" not in source - assert "from litellm" not in source +def test_an_unmappable_shape_says_so_once(roundtrip, logger): + """Once the ``None`` sentinel is handled, reaching the fail-soft branch + means a shape nobody anticipated. Silence there is how a mapping that + quietly stopped working would look — patch 8's whole lesson.""" + messages = [{"role": "assistant", "thinking_blocks": "not-a-list"}] * 5 + + roundtrip.map_thinking_blocks_to_reasoning_content(messages) + + warnings = logger.messages("warning") + assert len(warnings) == 1, "bounded: this sits on the per-request path" + assert "thinking_blocks" in warnings[0] + + +def test_diagnostic_is_retried_if_the_first_emit_raises(roundtrip, monkeypatch): + """Same discipline as the other three modules: record the warning as sent + only once the emit did not raise, or a logger that is not yet in place on + the first request suppresses it permanently.""" + flaky = _install_logger(monkeypatch, _FlakyLogger(failures=1)) + + for _ in range(3): + roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": 17}] + ) + + assert len(flaky.messages("warning")) == 1 + + +# --- signature-verifying providers ----------------------------------------- +# +# For an Anthropic or Google model reached THROUGH OpenRouter, the block +# signature is what the upstream verifies when prior thinking is replayed on a +# tool-calling turn, and OpenRouter's docs say to pass those blocks back +# unmodified and unreordered. The plain-string form destroys both, so those +# routes are declined outright rather than half-served. + + +@pytest.mark.parametrize( + "model", + [ + "anthropic/claude-sonnet-4.5", + "openrouter/anthropic/claude-opus-4", + "google/gemini-3-pro", + "OpenRouter/Google/Gemini-3-Pro", + ], +) +def test_signature_verifying_routes_are_left_exactly_as_they_arrived(roundtrip, model): + original = {"role": "assistant", "content": "a", "thinking_blocks": [_thinking("why")]} + + out = roundtrip.map_thinking_blocks_to_reasoning_content([dict(original)], model) + + assert out[0] == original, "stock behaviour is the known-working state for these routes" + assert "reasoning_content" not in out[0] + + +@pytest.mark.parametrize( + "model", + ["deepseek/deepseek-v4-pro", "qwen/qwen3-max", "poolside/laguna-s-2.1", None, 17], +) +def test_ordinary_routes_still_map(roundtrip, model): + """The gate must not be so broad that it swallows the routes this patch + exists for. A non-string model is not a slug we can reason about, so it is + treated as ordinary rather than as a match.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": [_thinking("why")]}], model + ) + + assert out[0]["reasoning_content"] == "why" + + +# --- a reasoning_content the caller already set ---------------------------- + + +def test_existing_reasoning_content_is_never_overwritten(roundtrip): + """litellm's own response objects carry both fields, so a client echoing an + assistant message back sends both. One rule for both branches: what the + caller stated wins, whether or not the blocks yield text.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [ + { + "role": "assistant", + "reasoning_content": "the caller's own", + "thinking_blocks": [_thinking("from blocks")], + } + ] + ) + + assert out[0]["reasoning_content"] == "the caller's own" + assert "thinking_blocks" not in out[0] + + +def test_a_blank_existing_reasoning_content_does_not_block_the_mapping(roundtrip): + """Set means set to something. An empty string is the absence of reasoning + wearing the field's name, so the blocks still win over it.""" + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [ + { + "role": "assistant", + "reasoning_content": " ", + "thinking_blocks": [_thinking("from blocks")], + } + ] + ) + + assert out[0]["reasoning_content"] == "from blocks" + + +# --- runtime escape hatch -------------------------------------------------- + + +@pytest.mark.parametrize("value", ["0", "false", "no", "off", ""]) +def test_knob_off_restores_stock_behaviour(roundtrip, monkeypatch, value): + """Patches 7 and 9 are both revertable on a live cluster without an image + rebuild; this one changes the outgoing body on every OpenRouter call, so it + carries the same hatch.""" + monkeypatch.setenv(roundtrip.ENV_VAR, value) + original = {"role": "assistant", "content": "a", "thinking_blocks": [_thinking("why")]} + + out = roundtrip.map_thinking_blocks_to_reasoning_content([dict(original)]) + + assert out[0] == original + + +@pytest.mark.parametrize("value", ["1", "true", "YES", "on"]) +def test_knob_on_is_the_default_spelled_out(roundtrip, monkeypatch, value): + monkeypatch.setenv(roundtrip.ENV_VAR, value) + + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": [_thinking("why")]}] + ) + + assert out[0]["reasoning_content"] == "why" + + +def test_unrecognized_knob_value_warns_once_and_keeps_the_default(roundtrip, monkeypatch, logger): + """Off is also the default, so reading a near-miss as off would leave an + operator unable to tell "ignored" from "working as configured".""" + monkeypatch.setenv(roundtrip.ENV_VAR, "disabled") + + for _ in range(3): + out = roundtrip.map_thinking_blocks_to_reasoning_content( + [{"role": "assistant", "thinking_blocks": [_thinking("why")]}] + ) + + assert out[0]["reasoning_content"] == "why", "unrecognized is not off" + warnings = logger.messages("warning") + assert len(warnings) == 1 + assert roundtrip.ENV_VAR in warnings[0] diff --git a/tests/config/test_patch_litellm_cache.py b/tests/config/test_patch_litellm_cache.py index 1a46fb11a..4f82fa184 100644 --- a/tests/config/test_patch_litellm_cache.py +++ b/tests/config/test_patch_litellm_cache.py @@ -624,6 +624,34 @@ def test_patch10_preserves_the_cache_control_step(tmp_path): assert "_egg_reasoning_roundtrip" in result +def test_patch10_passes_the_model_and_reports_an_unavailable_module(tmp_path): + """Two properties of the injected call site. + + The module declines routes whose upstream re-verifies replayed reasoning + (anthropic/*, google/*), which it can only do if the call site hands it + ``model``. And an import failure means a broken image, not a bad request: + reverting to stock in silence there is invisible until a model quietly + reasons worse — the condition Patch 8 exists to stop repeating.""" + patch10 = next(p for p in plc.PATCHES if p["label"].startswith("Patch 10/")) + + target = tmp_path / patch10["file"] + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(patch10["needle"]) + + plc._apply( + str(target), + present=patch10["present"], + needle=patch10["needle"], + replacement=patch10["replacement"], + label=patch10["label"], + ) + result = target.read_text() + + assert "_egg_map_reasoning(messages, model)" in result + assert "verbose_logger.warning(" in result + assert "_egg_reasoning_roundtrip_warned" in result, "warned once, not once per request" + + def test_patch10_maps_onto_the_request_not_the_response(tmp_path): """Guard against the adjacent-patch confusion the docstring calls out: patches 4/5a/5b are provider -> client, this one is client -> provider.