Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(anthropic): round-trip thinking blocks to OpenAI backends

mateo-berri766f72f1d7c1
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 6103b1bf484..ea54bd83e12 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -21,6 +21,9 @@ from pydantic import BaseModel
import litellm
from litellm import ModelResponse
from litellm._logging import verbose_logger
+from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ responses_reasoning_item_from_thinking_blocks,
+)
from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
from litellm.llms.base_llm.bridges.completion_transformation import (
CompletionTransformationBridge,
@@ -85,6 +88,21 @@ def _get_reasoning_items(
return []
+def _reasoning_input_items(msg: "AllMessageValues") -> list[dict[str, object]]: # mutable-ok: API message payload
+ """Reasoning input items for an assistant message.
+
+ Stored reasoning items win because they carry an id the Responses API minted; thinking
+ blocks are the fallback for turns that arrived over another API surface.
+ """
+ stored: Final = [_reasoning_item_to_response_input(r_item) for r_item in _get_reasoning_items(msg)]
+ if stored:
+ return stored
+ from_thinking: Final = responses_reasoning_item_from_thinking_blocks(
+ cast(Iterable[Mapping[str, Any]], msg.get("thinking_blocks") or ()) # cast-ok: untyped client thinking blocks
+ )
+ return [from_thinking] if from_thinking is not None else []
+
+
def _build_reasoning_item(
item_id: str,
encrypted_content: str | None,
@@ -372,8 +390,15 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
)
)
elif role == "assistant" and tool_calls and isinstance(tool_calls, list):
- for r_item in _get_reasoning_items(msg):
- input_items.append(_reasoning_item_to_response_input(r_item))
+ input_items.extend(_reasoning_input_items(msg))
+ if content:
+ input_items.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": self._convert_content_to_responses_format(content, "assistant"),
+ }
+ )
for tool_call in tool_calls:
function = tool_call.get("function")
custom = tool_call.get("custom")
@@ -400,8 +425,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
raise ValueError(f"tool call not supported: {tool_call}")
elif content is not None:
if role == "assistant":
- for r_item in _get_reasoning_items(msg):
- input_items.append(_reasoning_item_to_response_input(r_item))
+ input_items.extend(_reasoning_input_items(msg))
input_items.append(
{
"type": "message",
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index 2db5776047b..4211fbe610a 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -1549,6 +1549,38 @@ def _extract_reasoning_content(message: dict) -> tuple[str | None, str | None]:
return None, message_content
+def reasoning_content_from_thinking_blocks(
+ thinking_blocks: Iterable[Mapping[str, Any]],
+) -> str:
+ """Flatten Anthropic thinking blocks into the `reasoning_content` string chat models expect.
+
+ Redacted blocks carry no readable text, so they contribute nothing.
+ """
+ return "\n".join(
+ text
+ for block in thinking_blocks
+ if block.get("type") == "thinking" and (text := str(block.get("thinking") or ""))
+ )
+
+
+def responses_reasoning_item_from_thinking_blocks(
+ thinking_blocks: Iterable[Mapping[str, Any]],
+) -> dict[str, Any] | None: # mutable-ok: API message payload
+ """Build a Responses API `reasoning` input item from Anthropic thinking blocks.
+
+ The item carries no `id`: the Responses API rejects an empty one and 404s on any id it
+ did not mint itself, while an item without an id is always accepted.
+ """
+ summary: Final[list[dict[str, Any]]] = [ # mutable-ok: API message payload
+ {"type": "summary_text", "text": text} # mutable-ok: API message payload
+ for block in thinking_blocks
+ if block.get("type") == "thinking" and (text := str(block.get("thinking") or ""))
+ ]
+ if not summary:
+ return None
+ return {"type": "reasoning", "summary": summary} # mutable-ok: API message payload
+
+
def _parse_content_for_reasoning(
message_text: str | None,
) -> tuple[str | None, str | None]:
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index 34c2d837127..7c89da81fe6 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@ -64,6 +64,7 @@ from openai.types.chat.chat_completion_chunk import Choice as OpenAIStreamingCho
from litellm.litellm_core_utils.prompt_templates.common_utils import (
parse_tool_call_arguments,
+ reasoning_content_from_thinking_blocks,
with_prompt_cache_breakpoint,
)
from litellm.litellm_core_utils.prompt_templates.factory import (
@@ -592,6 +593,9 @@ class LiteLLMAnthropicMessagesAdapter:
assistant_message["tool_calls"] = tool_calls
if len(thinking_blocks) > 0:
assistant_message["thinking_blocks"] = thinking_blocks
+ reasoning_content = reasoning_content_from_thinking_blocks(thinking_blocks)
+ if reasoning_content:
+ assistant_message["reasoning_content"] = reasoning_content
new_messages.append(assistant_message)
return new_messages
diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py
index e2ad9c9c6d3..286edb24b9b 100644
--- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py
@@ -152,7 +152,7 @@ class AnthropicResponsesStreamWrapper:
if block_idx < 0:
if not delta:
return
- block_idx = self._open_block(item_id, {"type": "thinking", "thinking": ""})
+ block_idx = self._open_block(item_id, {"type": "thinking", "thinking": "", "signature": ""})
self._chunk_queue.append(
{
"type": "content_block_delta",
@@ -189,6 +189,17 @@ class AnthropicResponsesStreamWrapper:
block_idx = self._item_id_to_block_index.get(item_id, -1) if item_id else self._current_block_index
if block_idx < 0:
return
+ done_item_type: Final = (
+ getattr(item, "type", None) or (item.get("type") if isinstance(item, dict) else None) if item else None
+ )
+ if done_item_type == "reasoning" and item_id:
+ self._chunk_queue.append(
+ {
+ "type": "content_block_delta",
+ "index": block_idx,
+ "delta": {"type": "signature_delta", "signature": item_id},
+ }
+ )
self._chunk_queue.append(
{
"type": "content_block_stop",
diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py
index 25d729d8606..b1061f86d0b 100644
--- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py
@@ -6,12 +6,14 @@ path used for OpenAI and Azure models.
"""
import json
-from collections.abc import Iterable
+from collections.abc import Iterable, Mapping
+from itertools import groupby
from typing import Any, Final, cast
from litellm.litellm_core_utils.prompt_templates.common_utils import (
TOOL_RESULT_IMAGE_BOUNDARY,
TOOL_RESULT_IMAGE_PLACEHOLDER,
+ responses_reasoning_item_from_thinking_blocks,
with_prompt_cache_breakpoint,
)
from litellm.litellm_core_utils.reasoning_effort_utils import (
@@ -100,6 +102,58 @@ class LiteLLMAnthropicToResponsesAPIAdapter:
if isinstance(block, dict) and block.get("type") == "text" and (text := block.get("text")) # pyright: ignore[reportUnnecessaryIsInstance] # untrusted client payload
]
+ @staticmethod
+ def _summary_part_text(part: object) -> str:
+ if isinstance(part, Mapping):
+ mapping: Final = cast(Mapping[str, Any], part) # cast-ok: summary parts are untyped provider json
+ return str(mapping.get("text", ""))
+ return str(getattr(part, "text", ""))
+
+ @classmethod
+ def _thinking_blocks_from_reasoning_item(
+ cls,
+ item_id: str | None,
+ summary: Iterable[object],
+ ) -> tuple[dict[str, Any], ...]: # mutable-ok: API message payload
+ """Anthropic thinking blocks for one Responses reasoning item.
+
+ The reasoning item id rides along as the signature so that a follow-up turn can
+ regroup the summary parts into the single reasoning item they came from.
+ """
+ return tuple(
+ AnthropicResponseContentBlockThinking(
+ type="thinking",
+ thinking=text,
+ signature=item_id or None,
+ ).model_dump()
+ for part in summary
+ if (text := cls._summary_part_text(part))
+ )
+
+ @staticmethod
+ def _assistant_block_group_key(indexed_block: tuple[int, Mapping[str, Any]]) -> str:
+ """Group consecutive thinking blocks sharing a signature; keep every other block alone."""
+ index, block = indexed_block
+ signature: Final = block.get("signature") or ""
+ return f"thinking:{signature}" if block.get("type") == "thinking" else f"block:{index}"
+
+ @classmethod
+ def _assistant_group_to_input_item(
+ cls, group: tuple[Mapping[str, Any], ...]
+ ) -> dict[str, Any] | None: # mutable-ok: API message payload
+ first: Final = group[0]
+ btype: Final = first.get("type")
+ if btype == "thinking":
+ return responses_reasoning_item_from_thinking_blocks(group)
+ if btype == "tool_use":
+ return { # mutable-ok: API message payload
+ "type": "function_call",
+ "call_id": first.get("id", ""),
+ "name": first.get("name", ""),
+ "arguments": json.dumps(first.get("input", {})),
+ }
+ return None
+
def translate_messages_to_responses_input(
self,
messages: list[AllAnthropicPassThroughMessageValues],
@@ -113,6 +167,7 @@ class LiteLLMAnthropicToResponsesAPIAdapter:
user image -> message(role=user, input_image)
user tool_result -> function_call_output
assistant text -> message(role=assistant, output_text)
+ assistant thinking -> reasoning
assistant tool_use -> function_call
"""
input_items: Final[list[dict[str, Any]]] = []
@@ -233,27 +288,17 @@ class LiteLLMAnthropicToResponsesAPIAdapter:
}
)
elif isinstance(content, list):
- asst_parts: list[dict[str, Any]] = []
- for block in content:
- if not isinstance(block, dict):
- continue
- btype = block.get("type")
- if btype == "text":
- asst_parts.append({"type": "output_text", "text": block.get("text", "")})
- elif btype == "tool_use":
- # tool_use becomes a top-level function_call item
- input_items.append(
- {
- "type": "function_call",
- "call_id": block.get("id", ""),
- "name": block.get("name", ""),
- "arguments": json.dumps(block.get("input", {})),
- }
- )
- elif btype == "thinking":
- thinking_text = block.get("thinking", "")
- if thinking_text:
- asst_parts.append({"type": "output_text", "text": thinking_text})
+ blocks = tuple(block for block in content if isinstance(block, dict))
+ input_items.extend(
+ item
+ for _, group in groupby(enumerate(blocks), key=self._assistant_block_group_key)
+ if (item := self._assistant_group_to_input_item(tuple(block for _, block in group))) is not None
+ )
+ asst_parts: list[dict[str, Any]] = [ # mutable-ok: API message payload
+ {"type": "output_text", "text": block.get("text", "")} # mutable-ok: API message payload
+ for block in blocks
+ if block.get("type") == "text"
+ ]
if asst_parts:
input_items.append(
{
@@ -514,16 +559,7 @@ class LiteLLMAnthropicToResponsesAPIAdapter:
for item in response.output:
if isinstance(item, ResponseReasoningItem):
- for summary in item.summary:
- text = getattr(summary, "text", "")
- if text:
- content.append(
- AnthropicResponseContentBlockThinking(
- type="thinking",
- thinking=text,
- signature=None,
- ).model_dump()
- )
+ content.extend(self._thinking_blocks_from_reasoning_item(item.id, item.summary))
elif isinstance(item, ResponseOutputMessage):
for part in item.content:
@@ -555,6 +591,13 @@ class LiteLLMAnthropicToResponsesAPIAdapter:
content.append(
AnthropicResponseContentBlockText(type="text", text=part.get("text", "")).model_dump()
)
+ elif item_type == "reasoning":
+ content.extend(
+ self._thinking_blocks_from_reasoning_item(
+ item.get("id"),
+ cast(Iterable[object], item.get("summary") or ()), # cast-ok: untyped provider json
+ )
+ )
elif item_type == "function_call":
try:
input_data = json.loads(item.get("arguments", "{}"))
diff --git a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
index 4ff92aaf87d..124dc67b4fd 100644
--- a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
+++ b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
@@ -3762,3 +3762,90 @@ def test_response_incomplete_stream_event_without_details_defaults_to_length():
result = iterator.chunk_parser(chunk)
assert result.choices[0].finish_reason == "length"
+
+
+def test_assistant_message_with_tool_calls_keeps_its_content():
+ """Regression for https://github.com/BerriAI/litellm/issues/24985.
+
+ An assistant turn that both answered and called a tool used to lose its whole message:
+ the branch handling tool_calls emitted the calls and dropped the text.
+ """
+ handler = LiteLLMResponsesTransformationHandler()
+ messages = [
+ {"role": "user", "content": "What is the weather in Denver?"},
+ {
+ "role": "assistant",
+ "content": "Let me look that up.",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Denver"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "88F"},
+ ]
+
+ input_items, _ = handler.convert_chat_completion_messages_to_responses_api(messages)
+
+ assistant_message = next(
+ item for item in input_items if item.get("type") == "message" and item.get("role") == "assistant"
+ )
+ assert assistant_message["content"] == [{"type": "output_text", "text": "Let me look that up."}]
+ assert [item.get("type") for item in input_items] == [
+ "message",
+ "message",
+ "function_call",
+ "function_call_output",
+ ]
+
+
+def test_assistant_thinking_blocks_become_a_reasoning_input_item():
+ """Thinking blocks are how an Anthropic-shaped turn carries reasoning into this bridge."""
+ handler = LiteLLMResponsesTransformationHandler()
+ messages = [
+ {"role": "user", "content": "What is the weather in Denver?"},
+ {
+ "role": "assistant",
+ "content": "Denver is sunny.",
+ "thinking_blocks": [
+ {"type": "thinking", "thinking": "August in Denver is dry.", "signature": "sig1"},
+ {"type": "redacted_thinking", "data": "REDACTED"},
+ ],
+ },
+ {"role": "user", "content": "Why?"},
+ ]
+
+ input_items, _ = handler.convert_chat_completion_messages_to_responses_api(messages)
+
+ reasoning_item = next(item for item in input_items if item.get("type") == "reasoning")
+ assert reasoning_item["summary"] == [{"type": "summary_text", "text": "August in Denver is dry."}]
+ assert "id" not in reasoning_item
+
+
+def test_stored_reasoning_items_win_over_thinking_blocks():
+ """A minted reasoning id beats a re-derived one, so the two must not both be sent."""
+ handler = LiteLLMResponsesTransformationHandler()
+ messages = [
+ {
+ "role": "assistant",
+ "content": "Denver is sunny.",
+ "reasoning_items": [
+ {
+ "type": "reasoning",
+ "id": "rs_real",
+ "summary": [{"type": "summary_text", "text": "August in Denver is dry."}],
+ }
+ ],
+ "thinking_blocks": [
+ {"type": "thinking", "thinking": "August in Denver is dry.", "signature": "rs_real"}
+ ],
+ },
+ ]
+
+ input_items, _ = handler.convert_chat_completion_messages_to_responses_api(messages)
+
+ reasoning_items = [item for item in input_items if item.get("type") == "reasoning"]
+ assert len(reasoning_items) == 1
+ assert reasoning_items[0]["id"] == "rs_real"
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
index e4dacc308dc..d0169963962 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
@@ -359,6 +359,48 @@ def test_translate_anthropic_messages_to_openai_thinking_blocks():
assert result[1]["tool_calls"][0]["id"] == "toolu_01234"
+def test_translate_anthropic_messages_to_openai_sets_reasoning_content():
+ """Reasoning-aware chat providers read reasoning_content, so thinking text must land there.
+
+ Without it Moonshot and DeepSeek fill in a single-space placeholder and the model gets
+ a blank where its own prior reasoning belongs.
+ """
+
+ anthropic_messages = [
+ AnthropicMessagesUserMessageParam(
+ role="user",
+ content=[{"type": "text", "text": "Which city is best for a picnic?"}],
+ ),
+ AnthopicMessagesAssistantMessageParam(
+ role="assistant",
+ content=[
+ {"type": "thinking", "thinking": "Denver is dry in August.", "signature": "sig1"},
+ {"type": "thinking", "thinking": "San Francisco is foggy.", "signature": "sig2"},
+ {"type": "redacted_thinking", "data": "REDACTED"},
+ {"type": "text", "text": "Denver."},
+ ],
+ ),
+ ]
+
+ result = LiteLLMAnthropicMessagesAdapter().translate_anthropic_messages_to_openai(messages=anthropic_messages)
+
+ assert result[1]["reasoning_content"] == "Denver is dry in August.\nSan Francisco is foggy."
+ assert result[1]["content"] == "Denver."
+
+
+def test_translate_anthropic_messages_to_openai_sets_no_reasoning_content_without_thinking():
+ anthropic_messages = [
+ AnthopicMessagesAssistantMessageParam(
+ role="assistant",
+ content=[{"type": "text", "text": "Denver."}],
+ ),
+ ]
+
+ result = LiteLLMAnthropicMessagesAdapter().translate_anthropic_messages_to_openai(messages=anthropic_messages)
+
+ assert "reasoning_content" not in result[0]
+
+
def test_translate_anthropic_messages_to_openai_tool_message_placement():
"""Test that tool result messages are placed before user messages in the conversation order."""
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_streaming_iterator.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_streaming_iterator.py
index 8b591fcd7da..12a6ab4324f 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_streaming_iterator.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_streaming_iterator.py
@@ -139,14 +139,26 @@ class TestReasoningItemWithoutSummaryText:
("content_block_start", 0),
("content_block_delta", 0),
("content_block_delta", 0),
+ ("content_block_delta", 0),
("content_block_stop", 0),
("content_block_start", 1),
("content_block_delta", 1),
("content_block_stop", 1),
]
- assert chunks[1]["content_block"] == {"type": "thinking", "thinking": ""}
+ assert chunks[1]["content_block"] == {"type": "thinking", "thinking": "", "signature": ""}
assert "".join(c["delta"]["thinking"] for c in chunks[2:4]) == "Weighing options"
+ def test_reasoning_item_id_is_streamed_as_the_thinking_signature(self):
+ chunks = _drain_async(self._gpt_turn(reasoning_summary_deltas=["Weighing options"]))
+
+ signature_deltas = [c for c in chunks if c.get("delta", {}).get("type") == "signature_delta"]
+ assert [(c["index"], c["delta"]["signature"]) for c in signature_deltas] == [(0, "rs_1")]
+
+ def test_no_signature_delta_without_a_thinking_block(self):
+ chunks = _drain_async(self._gpt_turn(reasoning_summary_deltas=[]))
+
+ assert not [c for c in chunks if c.get("delta", {}).get("type") == "signature_delta"]
+
class TestToolUseBlockClosedExactlyOnce:
"""Regression for https://github.com/BerriAI/litellm/issues/37273.
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py
index 964f4b9f68b..6479c43ee7a 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py
@@ -486,8 +486,8 @@ class TestTranslateMessagesToResponsesInput:
}
]
- def test_assistant_thinking_block_becomes_output_text(self):
- """Assistant thinking block text is included as output_text."""
+ def test_assistant_thinking_block_becomes_reasoning_item(self):
+ """Assistant thinking block becomes a reasoning item, never visible assistant prose."""
messages = [
{
"role": "assistant",
@@ -495,7 +495,65 @@ class TestTranslateMessagesToResponsesInput:
}
]
result = _translate_messages(messages)
- assert result[0]["content"] == [{"type": "output_text", "text": "Let me reason step by step."}]
+ assert result == [
+ {
+ "type": "reasoning",
+ "summary": [{"type": "summary_text", "text": "Let me reason step by step."}],
+ }
+ ]
+
+ def test_reasoning_item_carries_no_id(self):
+ """A fabricated reasoning id 404s upstream, so the item must go out without one."""
+ messages = [
+ {
+ "role": "assistant",
+ "content": [{"type": "thinking", "thinking": "Private reasoning.", "signature": "rs_abc123"}],
+ }
+ ]
+ result = _translate_messages(messages)
+ assert "id" not in result[0]
+
+ def test_thinking_blocks_sharing_a_signature_become_one_reasoning_item(self):
+ """Summary parts of one upstream reasoning item are regrouped by their signature."""
+ messages = [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "First part.", "signature": "rs_abc123"},
+ {"type": "thinking", "thinking": "Second part.", "signature": "rs_abc123"},
+ {"type": "thinking", "thinking": "A later item.", "signature": "rs_def456"},
+ ],
+ }
+ ]
+ result = _translate_messages(messages)
+ assert result == [
+ {
+ "type": "reasoning",
+ "summary": [
+ {"type": "summary_text", "text": "First part."},
+ {"type": "summary_text", "text": "Second part."},
+ ],
+ },
+ {
+ "type": "reasoning",
+ "summary": [{"type": "summary_text", "text": "A later item."}],
+ },
+ ]
+
+ def test_thinking_and_text_stay_separate(self):
+ """The visible answer stays the only thing in the assistant message."""
+ messages = [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "The user wants Denver."},
+ {"type": "text", "text": "Denver is the best pick."},
+ ],
+ }
+ ]
+ result = _translate_messages(messages)
+ assert [item["type"] for item in result] == ["reasoning", "message"]
+ assert result[1]["content"] == [{"type": "output_text", "text": "Denver is the best pick."}]
def test_assistant_empty_thinking_block_skipped(self):
"""Assistant thinking block with empty thinking text is skipped."""
@@ -1094,7 +1152,7 @@ def _make_function_call_item(call_id: str, name: str, arguments: str) -> MagicMo
return item
-def _make_reasoning_item(summaries: List[str]) -> MagicMock:
+def _make_reasoning_item(summaries: List[str], item_id: str = "rs_test_1") -> MagicMock:
"""Build a mock ResponseReasoningItem."""
from openai.types.responses import ResponseReasoningItem # type: ignore[import]
@@ -1105,6 +1163,7 @@ def _make_reasoning_item(summaries: List[str]) -> MagicMock:
summary_mocks.append(s)
item = MagicMock(spec=ResponseReasoningItem)
+ item.id = item_id
item.summary = summary_mocks
return item
@@ -1178,6 +1237,29 @@ class TestTranslateResponse:
result: Any = _ADAPTER.translate_response(response)
assert result["content"] == []
+ def test_reasoning_item_id_becomes_thinking_signature(self):
+ """The reasoning item id rides back as the signature so the next turn can regroup it."""
+ reasoning = _make_reasoning_item(["Part one.", "Part two."], item_id="rs_abc123")
+ response = _make_mock_response(output=[reasoning])
+ result: Any = _ADAPTER.translate_response(response)
+ assert [block["signature"] for block in result["content"]] == ["rs_abc123", "rs_abc123"]
+
+ def test_dict_reasoning_item_becomes_thinking_block(self):
+ """A reasoning item arriving as a plain dict is kept, not dropped."""
+ response = _make_mock_response(
+ output=[
+ {
+ "type": "reasoning",
+ "id": "rs_dict_1",
+ "summary": [{"type": "summary_text", "text": "Weighing the options."}],
+ }
+ ]
+ )
+ result: Any = _ADAPTER.translate_response(response)
+ assert result["content"] == [
+ {"type": "thinking", "thinking": "Weighing the options.", "signature": "rs_dict_1"}
+ ]
+
def test_usage_mapped_correctly(self):
"""Input/output tokens from ResponseAPIUsage are mapped to AnthropicUsage."""
response = _make_mock_response(