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(bedrock)!: keep reasoning, thinking blocks and the json_mode finish_reason on fake streams (#46863)

Mateo Wang7ddc9f1c96c1
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index 95d062a190c..78fb82c98e7 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -1128,32 +1128,24 @@ class CustomStreamWrapper:
"""
- if self.merge_reasoning_content_in_choices is True:
- reasoning_content: Final = getattr(model_response.choices[0].delta, "reasoning_content", None)
- if reasoning_content:
- self._emitted_disqualifying_content = True
- if self.sent_first_thinking_block is False:
- # Ensure content is not None before concatenation
- if model_response.choices[0].delta.content is None:
- model_response.choices[0].delta.content = ""
- model_response.choices[0].delta.content += "<think>" + reasoning_content
- self.sent_first_thinking_block = True
- elif (
- self.sent_first_thinking_block is True
- and hasattr(model_response.choices[0].delta, "reasoning_content")
- and model_response.choices[0].delta.reasoning_content
- ):
- model_response.choices[0].delta.content = reasoning_content
- elif (
- self.sent_first_thinking_block is True
- and not self.sent_last_thinking_block
- and model_response.choices[0].delta.content
- ):
- model_response.choices[0].delta.content = "</think>" + (model_response.choices[0].delta.content or "")
- self.sent_last_thinking_block = True
-
- if hasattr(model_response.choices[0].delta, "reasoning_content"):
- del model_response.choices[0].delta.reasoning_content
+ if self.merge_reasoning_content_in_choices is not True:
+ return
+ delta: Final = model_response.choices[0].delta
+ reasoning_content: Final = getattr(delta, "reasoning_content", None)
+ content: Final = delta.content or ""
+ if reasoning_content:
+ self._emitted_disqualifying_content = True
+ closes_thinking: Final = bool(content) and not self.sent_last_thinking_block
+ opening: Final = "" if self.sent_first_thinking_block else "<think>"
+ delta.content = opening + reasoning_content + ("</think>" + content if closes_thinking else "")
+ self.sent_first_thinking_block = True
+ self.sent_last_thinking_block = self.sent_last_thinking_block or closes_thinking
+ elif self.sent_first_thinking_block and not self.sent_last_thinking_block and content:
+ delta.content = "</think>" + content
+ self.sent_last_thinking_block = True
+
+ if hasattr(delta, "reasoning_content"):
+ del delta.reasoning_content
def _dispatch_provider_chunk(
self,
diff --git a/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.py
index 18db0f28338..52b836c789a 100644
--- a/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.py
@@ -24,6 +24,7 @@ from typing_extensions import assert_never
from litellm._logging import verbose_logger
from litellm._uuid import uuid
from litellm.exceptions import ContextWindowExceededError, MidStreamFallbackError
+from litellm.litellm_core_utils.core_helpers import as_str_mapping
from litellm.litellm_core_utils.hidden_params import set_hidden_params
from litellm.llms.anthropic.pass_through.safeguards import StreamedSafeguardResults
from litellm.llms.anthropic.pass_through.utils import anthropic_sse_frame
@@ -39,6 +40,7 @@ from litellm.types.llms.anthropic import (
UsageDelta,
UsageIteration,
)
+from litellm.types.llms.openai import ChatCompletionRedactedThinkingBlock, ChatCompletionThinkingBlock
from litellm.types.utils import AdapterCompletionStreamWrapper, ChatCompletionDeltaToolCall, Delta, Function
if TYPE_CHECKING:
@@ -50,6 +52,7 @@ if TYPE_CHECKING:
_STREAMING_DELTA_TYPES: Final = frozenset(get_args(StreamingContentBlockDeltaType))
_SSE_EVENT: Final = TypeAdapter(Mapping[str, object])
+_THINKING_BLOCK: Final = TypeAdapter(ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock)
class _UsageDeltaWithIterations(UsageDelta, total=False):
@@ -106,6 +109,14 @@ def _delta_payload_field(delta_type: StreamingContentBlockDeltaType) -> str:
assert_never(delta_type)
+def _first_thinking_block_index(chunk: "ModelResponseStream") -> int | None:
+ delta: Final = _optional_attr(chunk.choices[0], "delta") if chunk.choices else None
+ blocks: Final = _optional_attr_sequence(delta, "thinking_blocks")
+ first_block: Final = as_str_mapping(blocks[0]) if blocks else None
+ index: Final = first_block.get("index") if first_block is not None else None
+ return index if isinstance(index, int) else None
+
+
def _optional_str_attr(obj: object, name: str) -> str | None:
value: Final = _optional_attr(obj, name)
return value if isinstance(value, str) else None
@@ -373,13 +384,44 @@ class _CombinedChunkSplitter:
finish_delta.thinking_blocks = None
return [content_chunk, finish_chunk]
+ @staticmethod
+ def _with_thinking_block(
+ chunk: "ModelResponseStream",
+ block: ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock,
+ *,
+ keep_role: bool,
+ ) -> "ModelResponseStream":
+ piece: Final = copy.deepcopy(chunk)
+ role: Final = getattr(piece.choices[0].delta, "role", None) if keep_role else None
+ thinking: Final = block.get("thinking") if block["type"] == "thinking" else None
+ piece.choices[0].delta = Delta(role=role, reasoning_content=thinking or None, thinking_blocks=[block])
+ return piece
+
+ @staticmethod
+ def _split_thinking_blocks(chunk: "ModelResponseStream") -> "tuple[ModelResponseStream, ...]":
+ """Anthropic streams one content block per thinking block, so a delta carrying several is split per block."""
+ choices: Final = _optional_attr_sequence(chunk, "choices")
+ if len(choices) != 1:
+ return (chunk,)
+ delta: Final = _optional_attr(choices[0], "delta")
+ blocks: Final = _optional_attr_sequence(delta, "thinking_blocks")
+ if len(blocks) < 2 or _optional_attr(delta, "content") or _optional_attr(delta, "tool_calls"):
+ return (chunk,)
+ return tuple(
+ _CombinedChunkSplitter._with_thinking_block(
+ chunk, _THINKING_BLOCK.validate_python(block), keep_role=position == 0
+ )
+ for position, block in enumerate(blocks)
+ )
+
def _expand(self, chunk: "ModelResponseStream") -> "tuple[ModelResponseStream, ...]":
split_chunks: Final = tuple(
split_chunk
for combined_chunk in self._split(chunk)
for split_chunk in self._split_by_payload_kind(combined_chunk) # comprehension-ok: flattens nested splits
)
- return tuple(itertools.chain.from_iterable(self._route_tool_calls(split_chunk) for split_chunk in split_chunks))
+ block_chunks: Final = tuple(itertools.chain.from_iterable(map(self._split_thinking_blocks, split_chunks)))
+ return tuple(itertools.chain.from_iterable(map(self._route_tool_calls, block_chunks)))
def __iter__(self) -> "Iterator[ModelResponseStream]":
return self
@@ -458,7 +500,8 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
sent_first_chunk: bool = False
sent_content_block_start: bool = False
sent_content_block_finish: bool = False
- current_content_block_type: Literal["text", "tool_use", "thinking"] = "text"
+ current_content_block_type: Literal["text", "tool_use", "thinking", "redacted_thinking"] = "text"
+ current_thinking_block_index: int | None = None
sent_last_message: bool = False
holding_chunk: ContentBlockDelta | None = None
holding_stop_reason_chunk: MessageBlockDelta | None = None
@@ -1254,13 +1297,14 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
Also gates re-emission after a block transition: when an upstream
chunk both *triggers* a new content block (its type differs from the
active block) and *carries* delta content, that content belongs to
- the new block. The synthesized ``content_block_start`` only ever
- carries an empty body — see
- ``_translate_streaming_openai_chunk_to_anthropic_content_block``,
- which returns an empty ``TextBlock``/``ToolUseBlock``/thinking block —
- so the trigger chunk's delta must be re-queued or the first token of
- the new block (the first non-empty text/thinking delta, or bundled
- tool arguments) is silently dropped.
+ the new block. The synthesized ``content_block_start`` from
+ ``_translate_streaming_openai_chunk_to_anthropic_content_block``
+ carries an empty text, tool-use or unsigned thinking body, and only a
+ signed thinking block's text rides on the start because its delta is
+ a ``signature_delta``. So the trigger chunk's delta must be re-queued
+ or the first token of the new block (the first non-empty text or
+ unsigned thinking delta, or bundled tool arguments) is silently
+ dropped.
Delta types outside ``StreamingContentBlockDeltaType`` — the closed
set the translate layer can produce — are treated as empty. The
@@ -1352,11 +1396,24 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
original_name: Final = self.tool_name_mapping.get(truncated_name, truncated_name)
tool_block["name"] = original_name
+ thinking_block_index: Final = _first_thinking_block_index(chunk)
+ previous_thinking_block_index: Final = self.current_thinking_block_index
+ if thinking_block_index is not None or block_type != self.current_content_block_type:
+ self.current_thinking_block_index = thinking_block_index
+
if block_type != self.current_content_block_type:
self.current_content_block_type = block_type
self.current_content_block_start = content_block_start
return True
+ if (
+ thinking_block_index is not None
+ and previous_thinking_block_index is not None
+ and thinking_block_index != previous_thinking_block_index
+ ):
+ self.current_content_block_start = content_block_start
+ return True
+
# For parallel tool calls, we'll necessarily have a new content block
# if we get a function name since it signals a new tool call
if block_type == "tool_use":
diff --git a/litellm/llms/anthropic/pass_through/adapters/transformation.py b/litellm/llms/anthropic/pass_through/adapters/transformation.py
index d1560c5b2ed..3aad0be1913 100644
--- a/litellm/llms/anthropic/pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/pass_through/adapters/transformation.py
@@ -1627,7 +1627,7 @@ class LiteLLMAnthropicMessagesAdapter:
def translate_streaming_openai_chunk_to_anthropic_content_block(
self, choices: list[OpenAIStreamingChoice | StreamingChoices]
) -> tuple[
- Literal["text", "tool_use", "thinking"],
+ Literal["text", "tool_use", "thinking", "redacted_thinking"],
"ContentBlockContentBlockDict",
]:
from litellm._uuid import uuid
@@ -1664,6 +1664,10 @@ class LiteLLMAnthropicMessagesAdapter:
thinking_blocks = choice.delta.thinking_blocks or []
if len(thinking_blocks) > 0:
thinking_block = thinking_blocks[0]
+ if thinking_block["type"] == "redacted_thinking":
+ return "redacted_thinking", ChatCompletionRedactedThinkingBlock(
+ type="redacted_thinking", data=thinking_block.get("data") or ""
+ )
if thinking_block["type"] == "thinking":
thinking = thinking_block.get("thinking") or ""
signature = thinking_block.get("signature") or ""
@@ -1672,7 +1676,7 @@ class LiteLLMAnthropicMessagesAdapter:
assert isinstance(signature, str)
return "thinking", ChatCompletionThinkingBlock(
- type="thinking", thinking=thinking, signature=signature
+ type="thinking", thinking=thinking if signature else "", signature=signature
)
# OpenAI-compatible reasoning backends (e.g. vLLM/SGLang reasoning
# parsers) populate ``reasoning_content`` without ``thinking_blocks``.
diff --git a/litellm/llms/base_llm/base_model_iterator.py b/litellm/llms/base_llm/base_model_iterator.py
index aede8aedc60..611051bb2dd 100644
--- a/litellm/llms/base_llm/base_model_iterator.py
+++ b/litellm/llms/base_llm/base_model_iterator.py
@@ -6,16 +6,38 @@ import litellm
if TYPE_CHECKING:
import httpx
+from litellm.types.llms.openai import ChatCompletionRedactedThinkingBlock, ChatCompletionThinkingBlock
from litellm.types.utils import (
Choices,
Delta,
GenericStreamingChunk,
+ Message,
ModelResponse,
ModelResponseStream,
StreamingChoices,
)
+def _indexed_thinking_block(
+ block: ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock, index: int
+) -> ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock:
+ if block["type"] == "redacted_thinking":
+ return {**block, "index": index}
+ return {**block, "index": index}
+
+
+def _streaming_delta(message: Message) -> Delta:
+ thinking_blocks: Final = message.thinking_blocks if hasattr(message, "thinking_blocks") else None
+ return Delta(
+ **message.model_dump(exclude={"thinking_blocks"}),
+ thinking_blocks=(
+ None
+ if thinking_blocks is None
+ else [_indexed_thinking_block(block, index) for index, block in enumerate(thinking_blocks)]
+ ),
+ )
+
+
def convert_model_response_to_streaming(
model_response: ModelResponse,
) -> ModelResponseStream:
@@ -40,9 +62,7 @@ def convert_model_response_to_streaming(
streaming_choices.append(
StreamingChoices(
index=choice.index,
- delta=Delta(
- **cast(Choices, choice).message.model_dump(),
- ),
+ delta=_streaming_delta(cast(Choices, choice).message),
finish_reason=choice.finish_reason,
)
)
diff --git a/litellm/llms/bedrock/chat/converse_handler.py b/litellm/llms/bedrock/chat/converse_handler.py
index 35d08d4b2c2..5a64e3fb78e 100644
--- a/litellm/llms/bedrock/chat/converse_handler.py
+++ b/litellm/llms/bedrock/chat/converse_handler.py
@@ -1,5 +1,5 @@
import json
-from collections.abc import Iterator
+from collections.abc import Iterator, Mapping
from typing import Final
import httpx
@@ -10,6 +10,7 @@ from litellm.anthropic_beta_headers_manager import (
)
from litellm.litellm_core_utils.get_litellm_params import stored_control_options
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObject
+from litellm.llms.base_llm import base_model_iterator
from litellm.llms.custom_httpx.http_handler import (
AsyncHTTPHandler,
HTTPHandler,
@@ -21,7 +22,7 @@ from litellm.utils import CustomStreamWrapper
from ..base_aws_llm import BaseAWSLLM, Credentials, bedrock_bearer_token, pop_aws_auth_params, run_aws_signing
from ..common_utils import BedrockError, error_response_text, get_all_bedrock_regions
-from .invoke_handler import AWSEventStreamDecoder, MockResponseIterator, make_call
+from .invoke_handler import AWSEventStreamDecoder, make_call
def make_sync_call(
@@ -36,7 +37,8 @@ def make_sync_call(
fake_stream: bool = False,
stream_chunk_size: int | None = None,
timeout: float | httpx.Timeout | None = None,
-) -> tuple[MockResponseIterator | Iterator[object], httpx.Headers]:
+ optional_params: Mapping[str, object] | None = None,
+) -> tuple[base_model_iterator.MockResponseIterator | Iterator[object], httpx.Headers]:
if client is None:
client = get_httpx_client() # Create a new client if none provided
@@ -64,14 +66,15 @@ def make_sync_call(
model_response=litellm.ModelResponse(),
stream=True,
logging_obj=logging_obj,
- optional_params={},
+ optional_params=dict(optional_params or {}),
api_key="",
data=data,
messages=messages,
encoding=litellm.encoding,
+ json_mode=json_mode,
)
- completion_stream: MockResponseIterator | Iterator[object] = MockResponseIterator(
- model_response=model_response, json_mode=json_mode
+ completion_stream: base_model_iterator.MockResponseIterator | Iterator[object] = (
+ base_model_iterator.MockResponseIterator(model_response=model_response)
)
else:
decoder: Final = AWSEventStreamDecoder(model=model, json_mode=json_mode)
@@ -158,6 +161,7 @@ class BedrockConverseLLM(BaseAWSLLM):
json_mode=json_mode,
stream_chunk_size=stream_chunk_size,
timeout=timeout,
+ optional_params=optional_params,
)
streaming_response: Final = CustomStreamWrapper(
completion_stream=completion_stream,
@@ -290,7 +294,7 @@ class BedrockConverseLLM(BaseAWSLLM):
stream_chunk_size: Final = stored_control_options(litellm_params).stream_chunk_size if stream is True else None
unencoded_model_id: Final = optional_params.pop("model_id", None)
fake_stream = optional_params.pop("fake_stream", False)
- json_mode: Final = optional_params.get("json_mode", False)
+ json_mode: Final = optional_params.get("json_mode") is True
if unencoded_model_id is not None:
modelId = self.encode_model_id(model_id=unencoded_model_id)
else:
@@ -463,6 +467,7 @@ class BedrockConverseLLM(BaseAWSLLM):
fake_stream=fake_stream,
stream_chunk_size=stream_chunk_size,
timeout=timeout,
+ optional_params=optional_params,
)
streaming_response: Final = CustomStreamWrapper(
completion_stream=completion_stream,
diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.py
index 6ad400661be..7553dacd35d 100644
--- a/litellm/llms/bedrock/chat/invoke_handler.py
+++ b/litellm/llms/bedrock/chat/invoke_handler.py
@@ -1,7 +1,7 @@
import json
import types
from collections.abc import AsyncIterator, Iterator, Mapping
-from typing import TYPE_CHECKING, Final, cast
+from typing import TYPE_CHECKING, Final
import httpx
from pydantic import TypeAdapter, ValidationError
@@ -20,6 +20,7 @@ from litellm.llms.anthropic.chat.handler import (
ModelResponseIterator as AnthropicModelResponseIterator,
)
from litellm.llms.anthropic.chat.transformation import JsonModeRequest
+from litellm.llms.base_llm import base_model_iterator
from litellm.llms.base_llm.base_utils import ResponseFormatSchema
from litellm.llms.custom_httpx.http_handler import (
AsyncHTTPHandler,
@@ -32,12 +33,8 @@ from litellm.types.llms.openai import (
ChatCompletionRedactedThinkingBlock,
ChatCompletionThinkingBlock,
ChatCompletionToolCallChunk,
- ChatCompletionToolCallFunctionChunk,
- ChatCompletionUsageBlock,
)
from litellm.types.utils import (
- ChatCompletionMessageToolCall,
- Choices,
Delta,
ModelResponse,
ModelResponseStream,
@@ -228,7 +225,10 @@ async def make_call(
bedrock_invoke_provider: litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL | None = None,
stream_chunk_size: int | None = None,
timeout: float | httpx.Timeout | None = None,
-) -> "tuple[MockResponseIterator | AsyncIterator[GChunk | ModelResponseStream | dict], httpx.Headers]":
+ optional_params: Mapping[str, object] | None = None,
+) -> tuple[
+ base_model_iterator.MockResponseIterator | AsyncIterator[GChunk | ModelResponseStream | dict], httpx.Headers
+]:
try:
if client is None:
client = get_async_httpx_client(
@@ -264,15 +264,16 @@ async def make_call(
model_response=litellm.ModelResponse(),
stream=True,
logging_obj=logging_obj,
- optional_params={},
+ optional_params=dict(optional_params or {}),
api_key="",
data=data,
messages=messages,
encoding=litellm.encoding,
+ json_mode=json_mode,
)
- completion_stream: MockResponseIterator | AsyncIterator[GChunk | ModelResponseStream | dict] = (
- MockResponseIterator(model_response=model_response, json_mode=json_mode)
- )
+ completion_stream: (
+ base_model_iterator.MockResponseIterator | AsyncIterator[GChunk | ModelResponseStream | dict]
+ ) = base_model_iterator.MockResponseIterator(model_response=model_response)
else:
decoder: Final = _stream_decoder(
bedrock_invoke_provider,
@@ -324,7 +325,7 @@ def make_sync_call(
bedrock_invoke_provider: litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL | None = None,
stream_chunk_size: int | None = None,
timeout: float | httpx.Timeout | None = None,
-) -> "tuple[MockResponseIterator | Iterator[GChunk | ModelResponseStream | dict], httpx.Headers]":
+) -> tuple[base_model_iterator.MockResponseIterator | Iterator[GChunk | ModelResponseStream | dict], httpx.Headers]:
try:
if client is None:
client = get_httpx_client(
@@ -364,10 +365,11 @@ def make_sync_call(
data=data,
messages=messages,
encoding=litellm.encoding,
+ json_mode=json_mode,
)
- completion_stream: MockResponseIterator | Iterator[GChunk | ModelResponseStream | dict] = (
- MockResponseIterator(model_response=model_response, json_mode=json_mode)
- )
+ completion_stream: (
+ base_model_iterator.MockResponseIterator | Iterator[GChunk | ModelResponseStream | dict]
+ ) = base_model_iterator.MockResponseIterator(model_response=model_response)
else:
decoder: Final = _stream_decoder(
bedrock_invoke_provider,
@@ -991,98 +993,3 @@ class AmazonOpenAICompatibleStreamDecoder(AWSEventStreamDecoder):
def _chunk_parser(self, chunk_data: dict[str, object]) -> ModelResponseStream:
return self.openai_model_response_iterator.chunk_parser(chunk=chunk_data)
-
-
-class MockResponseIterator: # for returning ai21 streaming responses
- def __init__(self, model_response, json_mode: bool | None = False):
- self.model_response = model_response
- self.json_mode = json_mode
- self.is_done = False
-
- # Sync iterator
- def __iter__(self):
- return self
-
- def _handle_json_mode_chunk(
- self, text: str, tool_calls: list[ChatCompletionToolCallChunk] | None
- ) -> tuple[str, ChatCompletionToolCallChunk | None]:
- """
- If JSON mode is enabled, convert the tool call to a message.
-
- Bedrock returns the JSON schema as part of the tool call
- OpenAI returns the JSON schema as part of the content, this handles placing it in the content
-
- Args:
- text: str
- tool_use: Optional[ChatCompletionToolCallChunk]
- Returns:
- Tuple[str, Optional[ChatCompletionToolCallChunk]]
-
- text: The text to use in the content
- tool_use: The ChatCompletionToolCallChunk to use in the chunk response
- """
- tool_use: ChatCompletionToolCallChunk | None = None
- if self.json_mode is True and tool_calls is not None:
- message: Final = litellm.AnthropicConfig().convert_tool_response_to_message(tool_calls=tool_calls)
- if message is not None:
- text = message.content or ""
- tool_use = None
- elif tool_calls is not None and len(tool_calls) > 0:
- tool_use = tool_calls[0]
- return text, tool_use
-
- def _chunk_parser(self, chunk_data: ModelResponse) -> GChunk:
- try:
- chunk_usage: Final[Usage] = getattr(chunk_data, "usage")
- text = chunk_data.choices[0].message.content or ""
- tool_use = None
- _model_response_tool_call: Final = cast(
- list[ChatCompletionMessageToolCall] | None,
- cast(Choices, chunk_data.choices[0]).message.tool_calls,
- )
- if self.json_mode is True:
- text, tool_use = self._handle_json_mode_chunk(
- text=text,
- tool_calls=chunk_data.choices[0].message.tool_calls,
- )
- elif _model_response_tool_call is not None:
- tool_use = ChatCompletionToolCallChunk(
- id=_model_response_tool_call[0].id,
- type="function",
- function=ChatCompletionToolCallFunctionChunk(
- name=_model_response_tool_call[0].function.name,
- arguments=_model_response_tool_call[0].function.arguments,
- ),
- index=0,
- )
- processed_chunk: Final = GChunk(
- text=text,
- tool_use=tool_use,
- is_finished=True,
- finish_reason=map_finish_reason(finish_reason=chunk_data.choices[0].finish_reason or ""),
- usage=ChatCompletionUsageBlock(
- prompt_tokens=chunk_usage.prompt_tokens,
- completion_tokens=chunk_usage.completion_tokens,
- total_tokens=chunk_usage.total_tokens,
- ),
- index=0,
- )
- return processed_chunk
- except Exception as e:
- raise ValueError(f"Failed to decode chunk: {chunk_data}. Error: {e}")
-
- def __next__(self):
- if self.is_done:
- raise StopIteration
- self.is_done = True
- return self._chunk_parser(self.model_response)
-
- # Async iterator
- def __aiter__(self):
- return self
-
- async def __anext__(self):
- if self.is_done:
- raise StopAsyncIteration
- self.is_done = True
- return self._chunk_parser(self.model_response)
diff --git a/litellm/llms/openai/openai.py b/litellm/llms/openai/openai.py
index 27346ee936e..79c69b5ceb4 100644
--- a/litellm/llms/openai/openai.py
+++ b/litellm/llms/openai/openai.py
@@ -30,9 +30,8 @@ from litellm.files.types import FileContentStreamingResult
from litellm.litellm_core_utils.core_helpers import set_provider_response_headers_in_hidden_params
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.litellm_core_utils.logging_utils import speech_request_body, track_llm_api_timing
-from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
+from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator, MockResponseIterator
from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException
-from litellm.llms.bedrock.chat.invoke_handler import MockResponseIterator
from litellm.types.utils import (
EmbeddingResponse,
ImageResponse,
diff --git a/litellm/llms/openai_like/chat/handler.py b/litellm/llms/openai_like/chat/handler.py
index 62a84ad3f15..2c74ef19e7d 100644
--- a/litellm/llms/openai_like/chat/handler.py
+++ b/litellm/llms/openai_like/chat/handler.py
@@ -14,7 +14,7 @@ from typing_extensions import ReadOnly
import litellm
from litellm import LlmProviders
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
-from litellm.llms.bedrock.chat.invoke_handler import MockResponseIterator
+from litellm.llms.base_llm.base_model_iterator import MockResponseIterator
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
from litellm.llms.databricks.streaming_utils import ModelResponseIterator
from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig
diff --git a/litellm/llms/snowflake/chat/transformation.py b/litellm/llms/snowflake/chat/transformation.py
index bf2a7d7da15..6a480904a3e 100644
--- a/litellm/llms/snowflake/chat/transformation.py
+++ b/litellm/llms/snowflake/chat/transformation.py
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Any, Final, Protocol, TypedDict
import httpx
from typing_extensions import ReadOnly
+from litellm.litellm_core_utils.core_helpers import as_str_mapping
from litellm.litellm_core_utils.prompt_templates.factory import (
anthropic_process_openai_file_message,
convert_to_anthropic_tool_result,
@@ -184,10 +185,11 @@ def _signed_thinking_blocks(msg: object) -> list[dict[str, object]]: # mutable-
blocks: Final = msg.get("thinking_blocks") if isinstance(msg, dict) else getattr(msg, "thinking_blocks", None)
if not isinstance(blocks, list):
return []
+ mappings: Final = tuple(filter(None, map(as_str_mapping, blocks)))
return [
- dict(block)
- for block in blocks
- if isinstance(block, Mapping) and (block.get("signature") or block.get("type") == "redacted_thinking")
+ {key: value for key, value in block.items() if key != "index"}
+ for block in mappings
+ if block.get("signature") or block.get("type") == "redacted_thinking"
]
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
index 418bdb3d6db..5c9e5cac5ab 100644
--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py
+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
@@ -100,6 +100,11 @@ def _delta_carries_output(delta: ChatCompletionDelta) -> bool:
return any(fields) or _delta_has_signed_thinking_block(delta)
+def _delta_carries_reasoning_and_answer(delta: ChatCompletionDelta) -> bool:
+ has_reasoning: Final = bool(getattr(delta, "reasoning_content", None)) or _delta_has_signed_thinking_block(delta)
+ return has_reasoning and bool(delta.content or delta.tool_calls)
+
+
class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
"""
Async iterator for processing streaming responses from the Responses API.
@@ -566,6 +571,26 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self._buffered_chunk = None
return buffered
+ def _reasoning_part_first(self, chunk: ModelResponseStream) -> ModelResponseStream:
+ if not chunk.choices or not _delta_carries_reasoning_and_answer(chunk.choices[0].delta):
+ return chunk
+ first_choice: Final = chunk.choices[0]
+ delta: Final = first_choice.delta
+ answer_delta: Final = delta.model_copy(update={"reasoning_content": None, "thinking_blocks": None})
+ self._buffered_chunk = chunk.model_copy(
+ update={"choices": [first_choice.model_copy(update={"delta": answer_delta}), *chunk.choices[1:]]}
+ )
+ reasoning_delta: Final = ChatCompletionDelta(
+ reasoning_content=getattr(delta, "reasoning_content", None),
+ thinking_blocks=delta.thinking_blocks if hasattr(delta, "thinking_blocks") else None,
+ )
+ return chunk.model_copy(
+ update={
+ "provider_specific_fields": None,
+ "choices": [first_choice.model_copy(update={"delta": reasoning_delta, "finish_reason": None})],
+ }
+ )
+
def _with_encoded_response_id(self, response: ResponsesAPIResponse) -> ResponsesAPIResponse:
return ResponsesAPIRequestUtils.update_responses_api_response_id_with_model_id(
responses_api_response=response,
@@ -1052,6 +1077,41 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self._queue_message_item_added_events()
return
+ def _queue_reasoning_done_events_on_reasoning_end(self, chunk: ModelResponseStream) -> None:
+ if not self._reasoning_active or self._reasoning_done_emitted:
+ return
+ delta: Final = chunk.choices[0].delta if chunk.choices else None
+ if delta and getattr(delta, "reasoning_content", None):
+ self._accumulated_reasoning_content_parts.append(delta.reasoning_content)
+ if not self._is_reasoning_end(chunk):
+ return
+ reasoning_content: Final = "".join(self._accumulated_reasoning_content_parts)
+ self._cached_reasoning_item_id = (
+ self._reasoning_item_id or self._cached_reasoning_item_id or mint_reasoning_item_id()
+ )
+ reasoning_item_id: Final = self._cached_reasoning_item_id
+ self._sequence_number += 1
+ text_done_event: Final = self.create_reasoning_summary_text_done_event(
+ reasoning_item_id=reasoning_item_id,
+ reasoning_content=reasoning_content,
+ sequence_number=self._sequence_number,
+ )
+ self._sequence_number += 1
+ part_done_event: Final = self.create_reasoning_summary_part_done_event(
+ reasoning_item_id=reasoning_item_id,
+ reasoning_content=reasoning_content,
+ sequence_number=self._sequence_number,
+ )
+ self._sequence_number += 1
+ reasoning_output_item_done_event: Final = self.create_reasoning_output_item_done_event(
+ reasoning_item_id=reasoning_item_id,
+ reasoning_content=reasoning_content,
+ sequence_number=self._sequence_number,
+ )
+ self._pending_response_events.extend([text_done_event, part_done_event, reasoning_output_item_done_event])
+ self._reasoning_done_emitted = True
+ self._reasoning_active = False
+
async def __anext__(
self,
) -> ResponsesAPIStreamingResponse | ResponseCompletedEvent | BaseLiteLLMOpenAIResponseObject:
@@ -1078,7 +1138,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
raise StopAsyncIteration
chunk = await self.litellm_custom_stream_wrapper.__anext__()
if chunk is not None:
- chunk = cast(ModelResponseStream, chunk)
+ chunk = self._reasoning_part_first(cast(ModelResponseStream, chunk))
for src in (
getattr(chunk, "provider_specific_fields", None),
getattr(
@@ -1095,55 +1155,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self.collected_chat_completion_chunks.append(
self._snapshot_chunk_for_stream_chunk_builder(chunk)
)
- if self._reasoning_active and not self._reasoning_done_emitted:
- # Incrementally accumulate reasoning content instead of
- # calling stream_chunk_builder on every chunk (O(n²))
- delta = chunk.choices[0].delta if chunk.choices else None
- if delta and hasattr(delta, "reasoning_content") and delta.reasoning_content:
- self._accumulated_reasoning_content_parts.append(delta.reasoning_content)
- if self._is_reasoning_end(chunk):
- reasoning_content = "".join(self._accumulated_reasoning_content_parts)
-
- # Ensure we have a valid reasoning_item_id
- self._cached_reasoning_item_id = (
- self._reasoning_item_id
- or self._cached_reasoning_item_id
- or mint_reasoning_item_id()
- )
- reasoning_item_id = self._cached_reasoning_item_id
-
- # Create text.done event first with its own sequence number
- self._sequence_number += 1
- text_done_event = self.create_reasoning_summary_text_done_event(
- reasoning_item_id=reasoning_item_id,
- reasoning_content=reasoning_content,
- sequence_number=self._sequence_number,
- )
-
- # Create part.done event second with its own sequence number
- self._sequence_number += 1
- part_done_event = self.create_reasoning_summary_part_done_event(
- reasoning_item_id=reasoning_item_id,
- reasoning_content=reasoning_content,
- sequence_number=self._sequence_number,
- )
-
- self._sequence_number += 1
- reasoning_output_item_done_event = self.create_reasoning_output_item_done_event(
- reasoning_item_id=reasoning_item_id,
- reasoning_content=reasoning_content,
- sequence_number=self._sequence_number,
- )
- self._pending_response_events.extend(
- [
- text_done_event,
- part_done_event,
- reasoning_output_item_done_event,
- ]
- )
- self._reasoning_done_emitted = True
- self._reasoning_active = False
-
+ self._queue_reasoning_done_events_on_reasoning_end(chunk)
response_api_chunk = self._transform_chat_completion_chunk_to_response_api_chunk(chunk)
if response_api_chunk:
self._pending_response_events.append(response_api_chunk)
@@ -1182,11 +1194,11 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
try:
buffered_chunk = self._take_buffered_chunk()
if buffered_chunk is not None:
- chunk = buffered_chunk
+ chunk = self._reasoning_part_first(buffered_chunk)
elif self._upstream_exhausted:
raise StopIteration
else:
- chunk = self.litellm_custom_stream_wrapper.__next__()
+ chunk = self._reasoning_part_first(self.litellm_custom_stream_wrapper.__next__())
for src in (
getattr(chunk, "provider_specific_fields", None),
getattr(
@@ -1206,6 +1218,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self.collected_chat_completion_chunks.append(
self._snapshot_chunk_for_stream_chunk_builder(cast(ModelResponseStream, chunk))
)
+ self._queue_reasoning_done_events_on_reasoning_end(chunk)
response_api_chunk = self._transform_chat_completion_chunk_to_response_api_chunk(chunk)
if response_api_chunk:
self._pending_response_events.append(response_api_chunk)
diff --git a/litellm/types/llms/anthropic.py b/litellm/types/llms/anthropic.py
index c3d257117ed..6aeead7679f 100644
--- a/litellm/types/llms/anthropic.py
+++ b/litellm/types/llms/anthropic.py
@@ -536,7 +536,9 @@ class ContentBlockStartText(TypedDict):
content_block: TextBlock
-ContentBlockContentBlockDict = ToolUseBlock | TextBlock | ChatCompletionThinkingBlock
+ContentBlockContentBlockDict = (
+ ToolUseBlock | TextBlock | ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock
+)
ContentBlockStart = ContentBlockStartToolUse | ContentBlockStartText
diff --git a/tests/integration/sdk/test_responses_bridge_sync_reasoning_sdk.py b/tests/integration/sdk/test_responses_bridge_sync_reasoning_sdk.py
new file mode 100644
index 00000000000..99f5fa941f7
--- /dev/null
+++ b/tests/integration/sdk/test_responses_bridge_sync_reasoning_sdk.py
@@ -0,0 +1,130 @@
+import json
+import uuid
+from collections.abc import Iterable, Mapping, Sequence
+from typing import Final
+
+import pytest
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+import litellm
+from litellm.responses.litellm_completion_transformation.streaming_iterator import LiteLLMCompletionStreamingIterator
+
+_BACKEND: Final = "qwen3-sync-bridge-audit"
+_API_KEY: Final = "synthetic-hosted-vllm-key"
+_ANSWER: Final = "It is sunny in Paris."
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_ITEM_EVENTS: Final = frozenset({"response.output_item.added", "response.output_item.done"})
+
+
+class _Frozen(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+
+class _Item(_Frozen):
+ type: str
+
+
+class _Event(_Frozen):
+ type: str
+ item: _Item | None = None
+ output_index: int | None = None
+ delta: JsonValue = None
+
+
+def _frame(identity: str, delta: Mapping[str, JsonValue], finish_reason: str | None = None) -> bytes:
+ usage: Final = (
+ {"usage": {"prompt_tokens": 30, "completion_tokens": 12, "total_tokens": 42}} if finish_reason else {}
+ )
+ body: Final = {
+ "id": identity,
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": _BACKEND,
+ "choices": [{"index": 0, "delta": dict(delta), "finish_reason": finish_reason}],
+ **usage,
+ }
+ return b"data: " + json.dumps(body).encode() + b"\n\n"
+
+
+def _sse(deltas: Sequence[Mapping[str, JsonValue]]) -> Reply:
+ identity: Final = f"chatcmpl-sync-bridge-{uuid.uuid4().hex}"
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(
+ _frame(identity, {"role": "assistant", "content": ""}),
+ *(_frame(identity, delta) for delta in deltas),
+ _frame(identity, {}, "stop"),
+ b"data: [DONE]\n\n",
+ ),
+ )
+
+
+def _streamed_chat_posts(wire: Wire) -> list[JsonValue]:
+ posted: Final = [request for request in wire.drain() if request.method == "POST"]
+ assert [request.target for request in posted] == ["/v1/chat/completions"]
+ return [_JSON_OBJECT.validate_json(request.body).get("stream") for request in posted]
+
+
+def _events(stream: Iterable[object]) -> tuple[_Event, ...]:
+ return tuple(_Event.model_validate(_JSON_OBJECT.validate_python(_dumped(event))) for event in stream)
+
+
+def _dumped(event: object) -> object:
+ assert isinstance(event, BaseModel), type(event)
+ return event.model_dump(mode="json")
+
+
+def _delta_text(events: Sequence[_Event], event_type: str) -> str:
+ return "".join(str(event.delta) for event in events if event.type == event_type)
+
+
+ "deltas",
+ [
+ pytest.param(
+ ({"reasoning_content": "REASONING"}, {"content": _ANSWER}),
+ id="reasoning-then-answer-chunks",
+ ),
+ pytest.param(({"reasoning_content": "REASONING", "content": _ANSWER},), id="reasoning-and-answer-in-one-chunk"),
+ ],
+)
+def test_sync_responses_stream_closes_the_reasoning_item_before_the_message_opens(
+ deltas: tuple[dict[str, JsonValue], ...],
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ reasoning: Final = f"Sync bridge reasoning {marker}."
+ scripted: Final = tuple(
+ {key: reasoning if key == "reasoning_content" else value for key, value in delta.items()} for delta in deltas
+ )
+
+ def respond(request: Request) -> Reply:
+ return Reply(body=b'{"object":"list","data":[]}') if request.method == "GET" else _sse(scripted)
+
+ with wire_server(respond) as wire:
+ stream: Final = litellm.responses(
+ model=f"hosted_vllm/{_BACKEND}",
+ input=f"Weather in Paris? {marker}",
+ stream=True,
+ api_base=wire.url + "/v1",
+ api_key=_API_KEY,
+ use_chat_completions_api=True,
+ num_retries=0,
+ )
+ assert isinstance(stream, LiteLLMCompletionStreamingIterator), type(stream)
+ events: Final = _events(stream)
+
+ assert _streamed_chat_posts(wire) == [True]
+ lifecycle: Final = [
+ (event.type, event.item.type, event.output_index)
+ for event in events
+ if event.type in _ITEM_EVENTS and event.item is not None
+ ]
+ assert lifecycle == [
+ ("response.output_item.added", "reasoning", 0),
+ ("response.output_item.done", "reasoning", 0),
+ ("response.output_item.added", "message", 1),
+ ("response.output_item.done", "message", 1),
+ ], [event.type for event in events]
+ assert _delta_text(events, "response.reasoning_summary_text.delta") == reasoning
+ assert _delta_text(events, "response.output_text.delta") == _ANSWER
diff --git a/tests/integration/streaming/test_fake_stream_reasoning_wire.py b/tests/integration/streaming/test_fake_stream_reasoning_wire.py
new file mode 100644
index 00000000000..e46208365dd
--- /dev/null
+++ b/tests/integration/streaming/test_fake_stream_reasoning_wire.py
@@ -0,0 +1,874 @@
+import base64
+import json
+import math
+import os
+import uuid
+from collections.abc import Callable, Generator, Mapping, Sequence
+from contextlib import contextmanager
+from dataclasses import dataclass
+from importlib.resources import files
+from itertools import chain
+from typing import Final
+from urllib.parse import unquote
+
+import anthropic
+import openai
+import pytest
+from integration._support.client import Gateway, Scenario, eventually
+from integration._support.database import read_rows
+from integration._support.upstream import (
+ _aws_event_frame, # pyright: ignore[reportPrivateUsage] # the scripted Bedrock peer's only event-stream encoder
+)
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+from redis import Redis
+
+_TOKEN: Final = "synthetic-bedrock-bearer"
+_NATIVE_REDACTED: Final = base64.b64encode(b"\x12\x1esynthetic redacted reasoning payload").decode()
+_CONVERSE_REDACTED: Final = base64.b64encode(_NATIVE_REDACTED.encode()).decode()
+_SIGNATURE: Final = "EqoBCkgIBxABGAIiQsyntheticSignature"
+_ANSWER: Final[dict[str, JsonValue]] = {"city": "Tokyo", "population_millions": 14.0}
+_THINKING_TOKENS: Final = 87
+_EVENT_STREAM: Final = "application/vnd.amazon.eventstream"
+_NO_CACHE: Final[dict[str, JsonValue]] = {"no-cache": True}
+_THINKING: Final[dict[str, JsonValue]] = {"type": "enabled", "budget_tokens": 1024}
+_SCHEMA: Final[dict[str, JsonValue]] = {
+ "type": "object",
+ "properties": {"city": {"type": "string"}, "population_millions": {"type": "number"}},
+ "required": ["city", "population_millions"],
+ "additionalProperties": False,
+}
+_RESPONSE_FORMAT: Final[dict[str, JsonValue]] = {
+ "type": "json_schema",
+ "json_schema": {"name": "city_fact", "schema": _SCHEMA},
+}
+_CONVERSE_USAGE: Final[dict[str, JsonValue]] = {
+ "inputTokens": 40,
+ "outputTokens": 120,
+ "cacheReadInputTokens": 50,
+ "totalTokens": 210,
+}
+_LLAMA_MODEL_ID: Final = "us.meta.llama3-3-70b-instruct-v1:0"
+_VLLM_BACKEND: Final = "qwen3-fake-stream-audit"
+_VLLM_KEY: Final = "synthetic-hosted-vllm-key"
+_AZURE_DEPLOYMENT: Final = "reasoning-deployment"
+_AZURE_API_VERSION: Final = "2025-03-01-preview"
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_DISCOVERY_PROBE: Final = ("GET", "/v1/models")
+
+
+def _tool(name: str) -> dict[str, JsonValue]:
+ return {
+ "type": "function",
+ "function": {
+ "name": name,
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+ },
+ }
+
+
+class _Frozen(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+
+class _CostEntry(_Frozen):
+ litellm_provider: str | None = None
+ supports_native_structured_output: bool | None = None
+ supports_reasoning: bool | None = None
+
+
+class _ToolFunction(_Frozen):
+ name: str | None = None
+ arguments: str | None = None
+
+
+class _ToolCall(_Frozen):
+ index: int = 0
+ function: _ToolFunction
+
+
+class _PromptDetails(_Frozen):
+ cached_tokens: int | None = None
+
+
+class _CompletionDetails(_Frozen):
+ reasoning_tokens: int | None = None
+
+
+class _Usage(_Frozen):
+ prompt_tokens: int
+ completion_tokens: int
+ total_tokens: int
+ prompt_tokens_details: _PromptDetails | None = None
+ completion_tokens_details: _CompletionDetails | None = None
+
+
+class _Message(_Frozen):
+ content: str | None = None
+ reasoning_content: str | None = None
+ thinking_blocks: tuple[dict[str, JsonValue], ...] | None = None
+ tool_calls: tuple[_ToolCall, ...] | None = None
+
+
+class _Choice(_Frozen):
+ message: _Message
+ finish_reason: str | None = None
+
+
+class _Completion(_Frozen):
+ choices: tuple[_Choice, ...]
+ usage: _Usage
+
+
+class _StreamChoice(_Frozen):
+ delta: _Message
+ finish_reason: str | None = None
+
+
+class _Chunk(_Frozen):
+ choices: tuple[_StreamChoice, ...] = ()
+ usage: _Usage | None = None
+
+
+class _ConverseMessage(_Frozen):
+ role: str
+ content: tuple[dict[str, JsonValue], ...]
+
+
+class _ConverseRequest(_Frozen):
+ messages: tuple[_ConverseMessage, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class _Answer:
+ content: str
+ reasoning: str
+ thinking_blocks: tuple[dict[str, JsonValue], ...]
+ tool_calls: tuple[tuple[str, JsonValue], ...]
+ finish_reason: str | None
+ usage: _Usage | None
+
+
+_COST_MAP: Final = TypeAdapter(dict[str, _CostEntry])
+
+
+def _fakes_structured_output_stream(model: str, entry: _CostEntry) -> bool:
+ return (
+ model.startswith("us.anthropic.claude")
+ and entry.litellm_provider == "bedrock_converse"
+ and entry.supports_native_structured_output is False
+ and entry.supports_reasoning is True
+ )
+
+
+def _claude_without_native_structured_output() -> str:
+ entries: Final = _COST_MAP.validate_json(
+ (files("litellm") / "model_prices_and_context_window_backup.json").read_bytes()
+ )
+ return next(model for model, entry in entries.items() if _fakes_structured_output_stream(model, entry))
+
+
+def _converse_reply(content: Sequence[JsonValue], stop_reason: str) -> Reply:
+ return Reply(
+ body=json.dumps(
+ {
+ "output": {"message": {"role": "assistant", "content": list(content)}},
+ "stopReason": stop_reason,
+ "usage": _CONVERSE_USAGE,
+ "additionalModelResponseFields": {
+ "usage": {"output_tokens_details": {"thinking_tokens": _THINKING_TOKENS}}
+ },
+ "metrics": {"latencyMs": 1},
+ }
+ ).encode()
+ )
+
+
+def _reasoned_json_answer(reasoning: str) -> list[JsonValue]:
+ return [
+ {"reasoningContent": {"reasoningText": {"text": reasoning, "signature": _SIGNATURE}}},
+ {"reasoningContent": {"redactedContent": _CONVERSE_REDACTED}},
+ {"toolUse": {"toolUseId": "tooluse_json_1", "name": "json_tool_call", "input": _ANSWER}},
+ ]
+
+
+def _is_replay(request: Request) -> bool:
+ return any(message.role == "assistant" for message in _ConverseRequest.model_validate_json(request.body).messages)
+
+
+def _converse_peer(reasoning: str) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ assert unquote(request.target).endswith("/converse"), request.target
+ if _is_replay(request):
+ return _converse_reply([{"text": "replayed"}], "end_turn")
+ return _converse_reply(_reasoned_json_answer(reasoning), "tool_use")
+
+ return respond
+
+
+def _converse_targets(wire: Wire) -> list[str]:
+ return [unquote(request.target).rsplit("/", 1)[-1] for request in wire.drain()]
+
+
+def _claude_model(scenario: Scenario, wire: Wire) -> str:
+ return scenario.model(
+ model=f"bedrock/converse/{_claude_without_native_structured_output()}",
+ api_key=_TOKEN,
+ aws_region_name="us-east-1",
+ aws_bedrock_runtime_endpoint=wire.url,
+ )
+
+
+def _openai_client(gateway: Gateway) -> openai.OpenAI:
+ return openai.OpenAI(base_url=str(gateway.client.base_url) + "/v1", api_key=gateway.key, max_retries=0)
+
+
+def _parsed_arguments(arguments: str | None) -> JsonValue:
+ return _JSON_OBJECT.validate_json(arguments or "{}")
+
+
+def _completion_answer(completion: _Completion) -> _Answer:
+ choice: Final = completion.choices[0]
+ return _Answer(
+ content=choice.message.content or "",
+ reasoning=choice.message.reasoning_content or "",
+ thinking_blocks=choice.message.thinking_blocks or (),
+ tool_calls=tuple(
+ (call.function.name or "", _parsed_arguments(call.function.arguments))
+ for call in choice.message.tool_calls or ()
+ ),
+ finish_reason=choice.finish_reason,
+ usage=completion.usage,
+ )
+
+
+def _joined_call(calls: Sequence[_ToolCall], index: int) -> tuple[str, JsonValue]:
+ pieces: Final = tuple(call.function for call in calls if call.index == index)
+ return (
+ "".join(piece.name or "" for piece in pieces),
+ _parsed_arguments("".join(piece.arguments or "" for piece in pieces)),
+ )
+
+
+def _streamed_answer(chunks: Sequence[_Chunk]) -> _Answer:
+ choices: Final = tuple(chain.from_iterable(chunk.choices for chunk in chunks))
+ deltas: Final = tuple(choice.delta for choice in choices)
+ calls: Final = tuple(chain.from_iterable(delta.tool_calls or () for delta in deltas))
+ finishes: Final = tuple(choice.finish_reason for choice in choices if choice.finish_reason)
+ usages: Final = tuple(chunk.usage for chunk in chunks if chunk.usage is not None)
+ return _Answer(
+ content="".join(delta.content or "" for delta in deltas),
+ reasoning="".join(delta.reasoning_content or "" for delta in deltas),
+ thinking_blocks=tuple(chain.from_iterable(delta.thinking_blocks or () for delta in deltas)),
+ tool_calls=tuple(_joined_call(calls, index) for index in sorted({call.index for call in calls})),
+ finish_reason=finishes[-1] if finishes else None,
+ usage=usages[-1] if usages else None,
+ )
+
+
+def _chat(gateway: Gateway, body: Mapping[str, JsonValue]) -> _Answer:
+ completion: Final = _openai_client(gateway).chat.completions.create(
+ model=str(body["model"]),
+ messages=[{"role": "user", "content": str(body["question"])}],
+ extra_body={key: value for key, value in body.items() if key not in ("model", "question")},
+ )
+ return _completion_answer(_Completion.model_validate(completion.model_dump(mode="json")))
+
+
+def _chat_stream(gateway: Gateway, body: Mapping[str, JsonValue]) -> _Answer:
+ stream: Final = _openai_client(gateway).chat.completions.create(
+ model=str(body["model"]),
+ messages=[{"role": "user", "content": str(body["question"])}],
+ stream=True,
+ stream_options={"include_usage": True},
+ extra_body={key: value for key, value in body.items() if key not in ("model", "question")},
+ )
+ return _streamed_answer(tuple(_Chunk.model_validate(chunk.model_dump(mode="json")) for chunk in stream))
+
+
+def _unindexed(blocks: Sequence[dict[str, JsonValue]]) -> tuple[dict[str, JsonValue], ...]:
+ return tuple({key: value for key, value in block.items() if key != "index"} for block in blocks)
+
+
+def _json_question(model: str, marker: str, cache: Mapping[str, JsonValue] = _NO_CACHE) -> dict[str, JsonValue]:
+ return {
+ "model": model,
+ "question": f"How many people live in Tokyo, in millions? {marker}",
+ "response_format": _RESPONSE_FORMAT,
+ "thinking": _THINKING,
+ "max_tokens": 2048,
+ "cache": dict(cache),
+ }
+
+
+def test_fake_streamed_json_schema_chat_answer_matches_the_non_streamed_answer(gateway: Gateway) -> None:
+ marker: Final = uuid.uuid4().hex
+ reasoning: Final = f"Tokyo proper has about 14 million people, marker {marker}."
+ with wire_server(_converse_peer(reasoning)) as wire, gateway.scenario() as scenario:
+ model: Final = _claude_model(scenario, wire)
+ question: Final = _json_question(model, marker)
+
+ answer: Final = _chat(gateway, question)
+ streamed: Final = _chat_stream(gateway, question)
+
+ assert _converse_targets(wire) == ["converse", "converse"]
+ assert (answer.reasoning, answer.finish_reason, answer.tool_calls) == (reasoning, "stop", ())
+ assert _JSON_OBJECT.validate_json(answer.content) == _ANSWER
+ assert answer.thinking_blocks == (
+ {"type": "thinking", "thinking": reasoning, "signature": _SIGNATURE},
+ {"type": "redacted_thinking", "data": _NATIVE_REDACTED},
+ )
+ assert (streamed.reasoning, streamed.finish_reason, streamed.tool_calls) == (reasoning, "stop", ())
+ assert _JSON_OBJECT.validate_json(streamed.content) == _ANSWER
+ assert _unindexed(streamed.thinking_blocks) == answer.thinking_blocks
+ assert streamed.usage == answer.usage
+ assert answer.usage is not None and answer.usage.completion_tokens_details is not None
+ assert answer.usage.completion_tokens_details.reasoning_tokens == _THINKING_TOKENS
+
+ replayed: Final = gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "thinking": _THINKING,
+ "max_tokens": 2048,
+ "cache": _NO_CACHE,
+ "messages": [
+ {"role": "user", "content": str(question["question"])},
+ {
+ "role": "assistant",
+ "content": streamed.content,
+ "thinking_blocks": list(streamed.thinking_blocks),
+ },
+ {"role": "user", "content": "And Osaka?"},
+ ],
+ },
+ )
+ assert replayed.status_code == 200, replayed.text
+ sent: Final = _ConverseRequest.model_validate_json(wire.drain()[-1].body)
+ assert next(message for message in sent.messages if message.role == "assistant").content == (
+ {"reasoningContent": {"reasoningText": {"text": reasoning, "signature": _SIGNATURE}}},
+ {"reasoningContent": {"redactedContent": _CONVERSE_REDACTED}},
+ {"text": streamed.content},
+ )
+
+
+def _spend_rows(model: str, count: int) -> list[dict[str, JsonValue]]:
+ return eventually(
+ lambda: read_rows(
+ 'SELECT spend, prompt_tokens, completion_tokens FROM "LiteLLM_SpendLogs" WHERE model_group=%s', (model,)
+ ),
+ lambda found: len(found) >= count,
+ seconds=70,
+ )
+
+
+def test_fake_streamed_cached_prompt_is_billed_like_the_non_streamed_answer(gateway: Gateway) -> None:
+ marker: Final = uuid.uuid4().hex
+ with wire_server(_converse_peer(f"Billing check {marker}.")) as wire, gateway.scenario() as scenario:
+ model: Final = _claude_model(scenario, wire)
+ question: Final = _json_question(model, marker)
+ _chat(gateway, question)
+ _chat_stream(gateway, question)
+
+ rows: Final = _spend_rows(model, 2)
+ assert _converse_targets(wire) == ["converse", "converse"]
+ assert len(rows) == 2, rows
+ first, second = rows
+ assert (first["prompt_tokens"], first["completion_tokens"]) == (
+ second["prompt_tokens"],
+ second["completion_tokens"],
+ )
+ assert float(str(first["spend"])) > 0
+ assert math.isclose(float(str(second["spend"])), float(str(first["spend"])), rel_tol=1e-9), rows
+
+
+def _cache_holds(needle: str) -> bool:
+ with Redis(host=os.environ["REDIS_HOST"], port=int(os.environ["REDIS_PORT"])) as store:
+ return any(needle.encode() in _bytes(store.get(key)) for key in store.scan_iter(count=1000, _type="STRING"))
+
+
+def _bytes(value: object) -> bytes:
+ return value if isinstance(value, bytes) else b""
+
+
+def test_cached_fake_stream_replays_the_answer_without_reaching_bedrock(gateway: Gateway) -> None:
+ marker: Final = uuid.uuid4().hex
+ reasoning: Final = f"Cached reasoning {marker}."
+ with wire_server(_converse_peer(reasoning)) as wire, gateway.scenario() as scenario:
+ model: Final = _claude_model(scenario, wire)
+ question: Final = _json_question(model, marker, cache={})
+
+ first: Final = _chat_stream(gateway, question)
+ assert first.reasoning == reasoning
+ eventually(lambda: _cache_holds(marker), bool, seconds=30)
+ assert _converse_targets(wire) == ["converse"]
+
+ replay: Final = _chat_stream(gateway, question)
+
+ assert _converse_targets(wire) == []
+ assert (replay.content, replay.finish_reason, replay.tool_calls) == (first.content, "stop", ())
+ assert _unindexed(replay.thinking_blocks) in ((), _unindexed(first.thinking_blocks))
+
+
+def _responses_reasoning_and_answer(
+ events: Sequence[dict[str, JsonValue]],
+) -> tuple[list[tuple[str, str, JsonValue]], str, str]:
+ lifecycle: Final = [
+ (str(event["type"]), str(_JSON_OBJECT.validate_python(event["item"])["type"]), event["output_index"])
+ for event in events
+ if event["type"] in ("response.output_item.added", "response.output_item.done")
+ ]
+ summary: Final = "".join(
+ str(event["delta"]) for event in events if event["type"] == "response.reasoning_summary_text.delta"
+ )
+ text: Final = "".join(str(event["delta"]) for event in events if event["type"] == "response.output_text.delta")
+ return lifecycle, summary, text
+
+
+_REASONING_THEN_MESSAGE: Final = [
+ ("response.output_item.added", "reasoning", 0),
+ ("response.output_item.done", "reasoning", 0),
+ ("response.output_item.added", "message", 1),
+ ("response.output_item.done", "message", 1),
+]
+
+
+def _raw_responses_events(gateway: Gateway, body: Mapping[str, JsonValue]) -> list[dict[str, JsonValue]]:
+ with gateway.client.stream(
+ "POST",
+ "/v1/responses",
+ json={**body, "stream": True, "store": False, "cache": _NO_CACHE},
+ headers={"Authorization": f"Bearer {gateway.key}"},
+ ) as response:
+ assert response.status_code == 200, response.read()
+ return [
+ _JSON_OBJECT.validate_json(line.removeprefix("data: "))
+ for line in response.iter_lines()
+ if line.startswith("data: {")
+ ]
+
+
+def _completed_usage(events: Sequence[dict[str, JsonValue]]) -> dict[str, JsonValue]:
+ completed: Final = [event for event in events if event["type"] == "response.completed"]
+ assert len(completed) == 1, [event["type"] for event in events]
+ return _JSON_OBJECT.validate_python(_JSON_OBJECT.validate_python(completed[0]["response"])["usage"])
+
+
+def test_fake_streamed_json_schema_responses_stream_closes_the_reasoning_before_the_answer(gateway: Gateway) -> None:
+ marker: Final = uuid.uuid4().hex
+ reasoning: Final = f"Responses reasoning {marker}."
+ with wire_server(_converse_peer(reasoning)) as wire, gateway.scenario() as scenario:
+ model: Final = _claude_model(scenario, wire)
+ events: Final = _raw_responses_events(
+ gateway,
+ {
+ "model": model,
+ "input": f"How many people live in Tokyo, in millions? {marker}",
+ "reasoning": {"effort": "high"},
+ "max_output_tokens": 2048,
+ "text": {"format": {"type": "json_schema", "name": "city_fact", "schema": _SCHEMA}},
+ },
+ )
+
+ lifecycle, summary, text = _responses_reasoning_and_answer(events)
+ assert _converse_targets(wire) == ["converse"]
+ assert lifecycle == _REASONING_THEN_MESSAGE, [event["type"] for event in events]
+ assert summary == reasoning
+ assert _JSON_OBJECT.validate_json(text) == _ANSWER
+ usage: Final = _completed_usage(events)
+ assert _JSON_OBJECT.validate_python(usage["input_tokens_details"])["cached_tokens"] == 50
+ assert _JSON_OBJECT.validate_python(usage["output_tokens_details"])["reasoning_tokens"] == _THINKING_TOKENS
+
+
+def _anthropic_client(gateway: Gateway) -> anthropic.Anthropic:
+ return anthropic.Anthropic(base_url=str(gateway.client.base_url), api_key=gateway.key, max_retries=0)
+
+
+def _block_fields(block: anthropic.types.ContentBlock) -> tuple[str, str, str]:
+ match block.type:
+ case "thinking":
+ return (block.type, block.thinking, block.signature)
+ case "redacted_thinking":
+ return (block.type, block.data, "")
+ case "text":
+ return (block.type, block.text, "")
+ case _:
+ return (block.type, "", "")
+
+
+def _message_blocks(message: anthropic.types.Message) -> list[tuple[str, str, str]]:
+ return [_block_fields(block) for block in message.content]
+
+
+def test_fake_streamed_json_schema_messages_stream_opens_one_block_per_thinking_block(gateway: Gateway) -> None:
+ marker: Final = uuid.uuid4().hex
+ reasoning: Final = f"Messages reasoning {marker}."
+ with wire_server(_converse_peer(reasoning)) as wire, gateway.scenario() as scenario:
+ model: Final = _claude_model(scenario, wire)
+ with _anthropic_client(gateway).messages.stream(
+ model=model,
+ max_tokens=2048,
+ thinking={"type": "enabled", "budget_tokens": 1024},
+ messages=[{"role": "user", "content": f"How many people live in Tokyo, in millions? {marker}"}],
+ extra_body={"output_format": {"type": "json_schema", "schema": _SCHEMA}, "cache": _NO_CACHE},
+ ) as stream:
+ final: Final = stream.get_final_message()
+
+ assert _converse_targets(wire) == ["converse"]
+ blocks: Final = _message_blocks(final)
+ assert blocks[:2] == [
+ ("thinking", reasoning, _SIGNATURE),
+ ("redacted_thinking", _NATIVE_REDACTED, ""),
+ ], blocks
+ assert [block[0] for block in blocks[2:]] == ["text"], blocks
+ assert _JSON_OBJECT.validate_json(blocks[2][1]) == _ANSWER
+ assert final.stop_reason == "end_turn"
+
+
+def _frame(event_type: str, payload: Mapping[str, JsonValue]) -> bytes:
+ return _aws_event_frame(event_type, payload, "sc", "u")
+
+
+def _converse_stream_with_thinking(reasoning_parts: Sequence[str], answer: str) -> Reply:
+ return Reply(
+ content_type=_EVENT_STREAM,
+ body=b"".join(
+ (
+ _frame("messageStart", {"role": "assistant"}),
+ *(
+ _frame(
+ "contentBlockDelta",
+ {"delta": {"reasoningContent": {"text": part}}, "contentBlockIndex": 0},
+ )
+ for part in reasoning_parts
+ ),
+ _frame(
+ "contentBlockDelta",
+ {"delta": {"reasoningContent": {"signature": _SIGNATURE}}, "contentBlockIndex": 0},
+ ),
+ _frame("contentBlockStop", {"contentBlockIndex": 0}),
+ _frame("contentBlockDelta", {"delta": {"text": answer}, "contentBlockIndex": 1}),
+ _frame("contentBlockStop", {"contentBlockIndex": 1}),
+ _frame("messageStop", {"stopReason": "end_turn"}),
+ _frame("metadata", {"usage": {"inputTokens": 11, "outputTokens": 9, "totalTokens": 20}}),
+ )
+ ),
+ )
+
+
+def test_native_converse_stream_thinking_reaches_the_anthropic_sdk_once_with_its_signature(gateway: Gateway) -> None:
+ marker: Final = uuid.uuid4().hex
+ parts: Final = ("Native thinking ", f"marker {marker}.")
+ answer: Final = "It is sunny in Paris."
+
+ def respond(request: Request) -> Reply:
+ assert unquote(request.target).endswith("/converse-stream"), request.target
+ return _converse_stream_with_thinking(parts, answer)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = _claude_model(scenario, wire)
+ with _anthropic_client(gateway).messages.stream(
+ model=model,
+ max_tokens=2048,
+ thinking={"type": "enabled", "budget_tokens": 1024},
+ messages=[{"role": "user", "content": f"Weather in Paris? {marker}"}],
+ extra_body={"cache": _NO_CACHE},
+ ) as stream:
+ final: Final = stream.get_final_message()
+
+ assert _converse_targets(wire) == ["converse-stream"]
+ assert _message_blocks(final) == [("thinking", "".join(parts), _SIGNATURE), ("text", answer, "")]
+
+
+def _llama_peer(content: list[JsonValue], stop_reason: str) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ assert unquote(request.target).endswith("/converse"), request.target
+ return Reply(
+ body=json.dumps(
+ {
+ "output": {"message": {"role": "assistant", "content": content}},
+ "stopReason": stop_reason,
+ "usage": {"inputTokens": 175, "outputTokens": 23, "totalTokens": 198},
+ "metrics": {"latencyMs": 1},
+ }
+ ).encode()
+ )
+
+ return respond
+
+
+_PARIS: Final[dict[str, JsonValue]] = {"city": "Paris"}
+
+
+ "content, stop_reason, expected_calls",
+ [
+ pytest.param(
+ [
+ {"toolUse": {"toolUseId": "tooluse_weather", "name": "get_weather", "input": _PARIS}},
+ {"toolUse": {"toolUseId": "tooluse_time", "name": "get_time", "input": _PARIS}},
+ ],
+ "tool_use",
+ (("get_weather", _PARIS), ("get_time", _PARIS)),
+ id="two-tool-use-blocks",
+ ),
+ pytest.param(
+ [{"text": json.dumps({"type": "function", "name": "get_weather", "parameters": _PARIS})}],
+ "end_turn",
+ (("get_weather", _PARIS),),
+ id="tool-call-written-as-text",
+ ),
+ ],
+)
+def test_fake_streamed_llama_tool_calls_match_the_non_streamed_answer(
+ gateway: Gateway,
+ content: list[JsonValue],
+ stop_reason: str,
+ expected_calls: tuple[tuple[str, JsonValue], ...],
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ with wire_server(_llama_peer(content, stop_reason)) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"bedrock/converse/{_LLAMA_MODEL_ID}",
+ api_key=_TOKEN,
+ aws_region_name="us-east-1",
+ aws_bedrock_runtime_endpoint=wire.url,
+ )
+ question: Final[dict[str, JsonValue]] = {
+ "model": model,
+ "question": f"Weather and time in Paris? {marker}",
+ "tools": [_tool("get_weather"), _tool("get_time")],
+ "cache": _NO_CACHE,
+ }
+
+ answer: Final = _chat(gateway, question)
+ streamed: Final = _chat_stream(gateway, question)
+
+ assert _converse_targets(wire) == ["converse", "converse"]
+ assert (answer.tool_calls, answer.finish_reason) == (expected_calls, "tool_calls")
+ assert (streamed.tool_calls, streamed.finish_reason, streamed.content) == (
+ answer.tool_calls,
+ "tool_calls",
+ answer.content,
+ )
+
+
+def _azure_o_series_reply() -> bytes:
+ return json.dumps(
+ {
+ "id": f"chatcmpl-{uuid.uuid4().hex}",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "o4-mini",
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": "tool_calls",
+ "message": {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_weather",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": json.dumps(_PARIS)},
+ },
+ {
+ "id": "call_time",
+ "type": "function",
+ "function": {"name": "get_time", "arguments": json.dumps(_PARIS)},
+ },
+ ],
+ },
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 85,
+ "completion_tokens": 1955,
+ "total_tokens": 2040,
+ "prompt_tokens_details": {"cached_tokens": 64},
+ "completion_tokens_details": {"reasoning_tokens": 1920},
+ },
+ }
+ ).encode()
+
+
+def test_azure_o_series_fake_stream_keeps_every_tool_call_and_token_detail(gateway: Gateway) -> None:
+ marker: Final = uuid.uuid4().hex
+ with wire_server(lambda _: Reply(body=_azure_o_series_reply())) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"azure/o_series/{_AZURE_DEPLOYMENT}",
+ api_base=wire.url,
+ api_key="synthetic-azure-key",
+ api_version=_AZURE_API_VERSION,
+ )
+ streamed: Final = _chat_stream(
+ gateway,
+ {
+ "model": model,
+ "question": f"Weather and time in Paris? {marker}",
+ "tools": [_tool("get_weather"), _tool("get_time")],
+ "cache": _NO_CACHE,
+ },
+ )
+
+ received: Final = wire.drain()
+ assert [unquote(request.target).split("?")[0] for request in received] == [
+ f"/openai/deployments/{_AZURE_DEPLOYMENT}/chat/completions"
+ ]
+ assert _JSON_OBJECT.validate_json(received[0].body).get("stream") is not True
+ assert (streamed.tool_calls, streamed.finish_reason) == (
+ (("get_weather", _PARIS), ("get_time", _PARIS)),
+ "tool_calls",
+ )
+ assert streamed.usage is not None
+ assert streamed.usage.prompt_tokens_details == _PromptDetails(cached_tokens=64)
+ assert streamed.usage.completion_tokens_details == _CompletionDetails(reasoning_tokens=1920)
+
+
+def _vllm_frame(identity: str, delta: Mapping[str, JsonValue], finish_reason: str | None = None) -> bytes:
+ usage: Final = (
+ {"usage": {"prompt_tokens": 30, "completion_tokens": 12, "total_tokens": 42}} if finish_reason else {}
+ )
+ body: Final = {
+ "id": identity,
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": _VLLM_BACKEND,
+ "choices": [{"index": 0, "delta": dict(delta), "finish_reason": finish_reason}],
+ **usage,
+ }
+ return b"data: " + json.dumps(body).encode() + b"\n\n"
+
+
+def _vllm_sse(deltas: Sequence[Mapping[str, JsonValue]], finish_reason: str) -> Reply:
+ identity: Final = f"chatcmpl-audit-{uuid.uuid4().hex}"
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(
+ _vllm_frame(identity, {"role": "assistant", "content": ""}),
+ *(_vllm_frame(identity, delta) for delta in deltas),
+ _vllm_frame(identity, {}, finish_reason),
+ b"data: [DONE]\n\n",
+ ),
+ )
+
+
+def _is_discovery_probe(request: Request) -> bool:
+ return (request.method, request.target) == _DISCOVERY_PROBE
+
+
+@contextmanager
+def _vllm_server(reply: Reply) -> Generator[Wire, None, None]:
+ with wire_server(
+ lambda request: Reply(body=b'{"object":"list","data":[]}') if _is_discovery_probe(request) else reply
+ ) as wire:
+ yield wire
+
+
+def _streamed_chats(wire: Wire) -> list[JsonValue]:
+ posted: Final = [request for request in wire.drain() if not _is_discovery_probe(request)]
+ assert [(request.method, request.target) for request in posted] == [("POST", "/v1/chat/completions")]
+ return [_JSON_OBJECT.validate_json(request.body).get("stream") for request in posted]
+
+
+ "deltas, merged",
+ [
+ pytest.param(
+ ({"reasoning_content": "R1 "}, {"reasoning_content": "R2 ", "content": "A1 "}, {"content": "A2"}),
+ "<think>R1 R2 </think>A1 A2",
+ id="answer-starts-in-the-last-reasoning-chunk",
+ ),
+ pytest.param(
+ ({"reasoning_content": "R ", "content": "A "}, {"content": "B"}),
+ "<think>R </think>A B",
+ id="reasoning-and-answer-in-the-first-chunk",
+ ),
+ pytest.param(
+ ({"reasoning_content": "R1 "}, {"reasoning_content": "R2 "}, {"content": "A1 "}, {"content": "A2"}),
+ "<think>R1 R2 </think>A1 A2",
+ id="reasoning-and-answer-in-separate-chunks",
+ ),
+ ],
+)
+def test_merged_reasoning_content_closes_the_think_tag_before_the_answer(
+ gateway: Gateway, deltas: tuple[dict[str, JsonValue], ...], merged: str
+) -> None:
+ with _vllm_server(_vllm_sse(deltas, "stop")) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"hosted_vllm/{_VLLM_BACKEND}",
+ api_base=wire.url + "/v1",
+ api_key=_VLLM_KEY,
+ merge_reasoning_content_in_choices=True,
+ )
+ streamed: Final = _chat_stream(
+ gateway, {"model": model, "question": f"Hello {uuid.uuid4().hex}", "cache": _NO_CACHE}
+ )
+
+ assert _streamed_chats(wire) == [True]
+ assert (streamed.content, streamed.reasoning, streamed.finish_reason) == (merged, "", "stop")
+
+
+_VLLM_TOOL_CALL: Final[dict[str, JsonValue]] = {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_bridge_weather",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": json.dumps(_PARIS)},
+ }
+ ]
+}
+
+
+ "answer_delta, finish_reason, answer_item",
+ [
+ pytest.param({"content": "It is sunny."}, "stop", "message", id="text"),
+ pytest.param(_VLLM_TOOL_CALL, "tool_calls", "function_call", id="tool-call"),
+ ],
+)
+def test_responses_stream_closes_the_reasoning_item_before_an_answer_from_the_same_chunk(
+ gateway: Gateway, answer_delta: dict[str, JsonValue], finish_reason: str, answer_item: str
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ reasoning: Final = f"Bridge reasoning {marker}."
+ reply: Final = _vllm_sse(({"reasoning_content": reasoning, **answer_delta},), finish_reason)
+ with _vllm_server(reply) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"hosted_vllm/{_VLLM_BACKEND}",
+ api_base=wire.url + "/v1",
+ api_key=_VLLM_KEY,
+ use_chat_completions_api=True,
+ )
+ events: Final = _raw_responses_events(
+ gateway,
+ {
+ "model": model,
+ "input": f"Weather in Paris? {marker}",
+ "tools": [
+ {
+ "type": "function",
+ "name": "get_weather",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ }
+ ],
+ },
+ )
+
+ lifecycle, summary, text = _responses_reasoning_and_answer(events)
+ assert _streamed_chats(wire) == [True]
+ assert lifecycle == [
+ ("response.output_item.added", "reasoning", 0),
+ ("response.output_item.done", "reasoning", 0),
+ ("response.output_item.added", answer_item, 1),
+ ("response.output_item.done", answer_item, 1),
+ ], [event["type"] for event in events]
+ assert summary == reasoning
+ assert text == str(answer_delta.get("content", ""))
diff --git a/tests/unit/litellm_core_utils/test_streaming_handler.py b/tests/unit/litellm_core_utils/test_streaming_handler.py
index fa649b48a51..93f700b1c2a 100644
--- a/tests/unit/litellm_core_utils/test_streaming_handler.py
+++ b/tests/unit/litellm_core_utils/test_streaming_handler.py
@@ -6143,72 +6143,6 @@ def test_unit_test_perplexity_citations_chunk():
assert "citations" in response_chunk
-def test_mock_response_iterator_tool_use():
- """
- Relevant Issue: https://github.com/BerriAI/litellm/issues/7364
- """
- from litellm.llms.bedrock.chat.invoke_handler import MockResponseIterator
- from litellm.types.utils import (
- ChatCompletionMessageToolCall,
- Choices,
- CompletionTokensDetailsWrapper,
- Function,
- Message,
- PromptTokensDetailsWrapper,
- Usage,
- )
-
- litellm.set_verbose = False
- response = ModelResponse(
- id="chatcmpl-Ai8KRI5vJPZXQ9SQvEJfTVuVqkyEZ",
- created=1735081811,
- model="o1-2024-12-17",
- object="chat.completion",
- system_fingerprint="fp_e6d02d4a78",
- choices=[
- Choices(
- finish_reason="tool_calls",
- index=0,
- message=Message(
- content=None,
- role="assistant",
- tool_calls=[
- ChatCompletionMessageToolCall(
- function=Function(
- arguments='{"location":"San Francisco, CA","unit":"fahrenheit"}',
- name="get_current_weather",
- ),
- id="call_BfRX2S7YCKL0BtxbWMl89ZNk",
- type="function",
- )
- ],
- function_call=None,
- ),
- )
- ],
- usage=Usage(
- completion_tokens=1955,
- prompt_tokens=85,
- total_tokens=2040,
- completion_tokens_details=CompletionTokensDetailsWrapper(
- accepted_prediction_tokens=0,
- audio_tokens=0,
- reasoning_tokens=1920,
- rejected_prediction_tokens=0,
- text_tokens=None,
- ),
- prompt_tokens_details=PromptTokensDetailsWrapper(
- audio_tokens=0, cached_tokens=0, text_tokens=None, image_tokens=None
- ),
- ),
- service_tier=None,
- )
- completion_stream = MockResponseIterator(model_response=response)
- response_chunk = completion_stream._chunk_parser(chunk_data=response)
-
- assert response_chunk["tool_use"] is not None
-
-
def test_is_delta_empty():
from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
from litellm.types.utils import Delta
diff --git a/tests/unit/llms/anthropic/pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py b/tests/unit/llms/anthropic/pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
index 2f0a7ad070b..9e0bd5c60b8 100644
--- a/tests/unit/llms/anthropic/pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
+++ b/tests/unit/llms/anthropic/pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
@@ -287,7 +287,7 @@ def test_translate_streaming_openai_chunk_to_anthropic_thinking_content_block():
assert block_type == "thinking"
assert content_block_start == {
"type": "thinking",
- "thinking": "I need to summar",
+ "thinking": "",
"signature": "",
}
diff --git a/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_combined_chunk.py b/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_combined_chunk.py
index 9a6940ff12b..b73df255cad 100644
--- a/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_combined_chunk.py
+++ b/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_combined_chunk.py
@@ -12,7 +12,11 @@ content survives.
import asyncio
import json
from types import SimpleNamespace
-from typing import AsyncIterator
+from typing import AsyncIterator, Final
+
+import anthropic
+import httpx
+import pytest
from litellm.llms.anthropic.pass_through.adapters.streaming_iterator import (
AnthropicStreamWrapper,
@@ -273,3 +277,93 @@ def test_thinking_then_signature_chunk_does_not_crash_stream():
assert "message_stop" in sse
assert "Done" in sse
+
+
+def _fake_stream_with_thinking(thinking_blocks: list[dict[str, str]]) -> MockResponseIterator:
+ model_response: Final = ModelResponse()
+ model_response.choices = [
+ Choices(
+ index=0,
+ message=Message(
+ role="assistant",
+ content='{"a": 1}',
+ reasoning_content="".join(block.get("thinking", "") for block in thinking_blocks),
+ thinking_blocks=thinking_blocks,
+ ),
+ finish_reason="stop",
+ )
+ ]
+ model_response.usage = Usage(prompt_tokens=5, completion_tokens=7, total_tokens=12)
+ return MockResponseIterator(model_response=model_response)
+
+
+def _anthropic_sdk_final_content(
+ completion_stream: "MockResponseIterator | AsyncIterator[ModelResponseStream]",
+) -> list[dict[str, object]]:
+ sse: Final = _collect_async(AnthropicStreamWrapper(completion_stream=completion_stream, model="claude"))
+ transport: Final = httpx.MockTransport(
+ lambda request: httpx.Response(200, content=sse.encode(), headers={"content-type": "text/event-stream"})
+ )
+ client: Final = anthropic.Anthropic(api_key="transport-only", http_client=httpx.Client(transport=transport))
+ with client.messages.stream(
+ model="claude", max_tokens=16, messages=[{"role": "user", "content": "hi"}]
+ ) as stream:
+ return [block.model_dump(exclude_none=True) for block in stream.get_final_message().content]
+
+
+ "thinking_blocks",
+ [
+ [
+ {"type": "thinking", "thinking": "first", "signature": "SIG_A"},
+ {"type": "thinking", "thinking": "second", "signature": "SIG_B"},
+ ],
+ [
+ {"type": "redacted_thinking", "data": "OPAQUE"},
+ {"type": "thinking", "thinking": "visible", "signature": "SIG_C"},
+ ],
+ [
+ {"type": "thinking", "thinking": "unsigned", "signature": ""},
+ {"type": "thinking", "thinking": "signed", "signature": "SIG_D"},
+ ],
+ ],
+ ids=["two_signed_thinking_blocks", "redacted_then_signed_thinking", "unsigned_then_signed_thinking"],
+)
+def test_fake_stream_gives_each_thinking_block_its_own_content_block(thinking_blocks: list[dict[str, str]]):
+ content: Final = _anthropic_sdk_final_content(_fake_stream_with_thinking(thinking_blocks))
+
+ assert content == [*thinking_blocks, {"type": "text", "text": '{"a": 1}'}]
+
+
+def _native_thinking_chunk(thinking: str, index: int, signature: str | None = None) -> ModelResponseStream:
+ block: Final = {"type": "thinking", "thinking": thinking, "index": index, **({"signature": signature} if signature else {})}
+ return ModelResponseStream(
+ choices=[StreamingChoices(index=0, delta=Delta(reasoning_content=thinking or None, thinking_blocks=[block]))]
+ )
+
+
+async def _native_stream_with_two_thinking_blocks() -> "AsyncIterator[ModelResponseStream]":
+ for chunk in (
+ _native_thinking_chunk("ab", 0),
+ _native_thinking_chunk("cd", 0),
+ _native_thinking_chunk("", 0, "SIG_A"),
+ _native_thinking_chunk("ef", 1),
+ _native_thinking_chunk("gh", 1),
+ _native_thinking_chunk("", 1, "SIG_B"),
+ ModelResponseStream(choices=[StreamingChoices(index=0, delta=Delta(content="hi"))]),
+ ModelResponseStream(
+ choices=[StreamingChoices(index=0, delta=Delta(), finish_reason="stop")],
+ usage=Usage(prompt_tokens=1, completion_tokens=1, total_tokens=2),
+ ),
+ ):
+ yield chunk
+
+
+def test_native_stream_thinking_blocks_keep_their_text_once():
+ content: Final = _anthropic_sdk_final_content(_native_stream_with_two_thinking_blocks())
+
+ assert content == [
+ {"type": "thinking", "thinking": "abcd", "signature": "SIG_A"},
+ {"type": "thinking", "thinking": "efgh", "signature": "SIG_B"},
+ {"type": "text", "text": "hi"},
+ ]
diff --git a/tests/unit/llms/base_llm/test_base_model_iterator.py b/tests/unit/llms/base_llm/test_base_model_iterator.py
index 936bf06bc18..204b458cadc 100644
--- a/tests/unit/llms/base_llm/test_base_model_iterator.py
+++ b/tests/unit/llms/base_llm/test_base_model_iterator.py
@@ -11,9 +11,9 @@ import httpx
import pytest
from pydantic import BaseModel
-from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
+from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator, convert_model_response_to_streaming
from litellm.llms.openai.chat.gpt_transformation import OpenAIChatCompletionStreamingHandler
-from litellm.types.utils import GenericStreamingChunk
+from litellm.types.utils import Choices, GenericStreamingChunk, Message, ModelResponse
class TestBaseModelResponseIterator:
@@ -314,3 +314,25 @@ def test_close_releases_the_attached_http_response():
iterator.http_response = response
iterator.close()
assert response.is_closed
+
+
+def test_fake_stream_chunk_indexes_thinking_blocks_by_position_without_touching_the_response():
+ """The OpenAI SDK's `.stream()` accumulator merges streamed `thinking_blocks` entries by `index`, so a fake stream
+ numbers them the way a real stream does, redacted blocks included"""
+ thinking_blocks: Final = [
+ {"type": "thinking", "thinking": "Step 1.", "signature": "sig-a"},
+ {"type": "redacted_thinking", "data": "opaque"},
+ {"type": "thinking", "thinking": "Step 2.", "signature": "sig-b"},
+ ]
+ response: Final = ModelResponse(
+ choices=[Choices(message=Message(content="Paris", thinking_blocks=thinking_blocks), finish_reason="stop")]
+ )
+
+ chunk: Final = convert_model_response_to_streaming(response)
+
+ assert chunk.choices[0].delta.thinking_blocks == [
+ {"type": "thinking", "thinking": "Step 1.", "signature": "sig-a", "index": 0},
+ {"type": "redacted_thinking", "data": "opaque", "index": 1},
+ {"type": "thinking", "thinking": "Step 2.", "signature": "sig-b", "index": 2},
+ ]
+ assert [block.get("index") for block in response.choices[0].message.thinking_blocks] == [None, None, None]
diff --git a/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py b/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py
index c025a368e51..dec32b3325e 100644
--- a/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py
+++ b/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import asyncio
from datetime import datetime, timedelta, timezone
+from itertools import chain
from typing import Final
from unittest.mock import MagicMock, patch
@@ -302,3 +303,230 @@ async def test_async_converse_streaming_fails_at_the_request_timeout_not_the_ups
def test_sync_converse_streaming_fails_at_the_request_timeout_not_the_upstreams_pace() -> None:
with pytest.raises(litellm.Timeout):
litellm.completion(client=slow_upstream_sync_client(), **_converse_streaming_kwargs())
+
+
+RECORDED_REASONING: Final = "Tokyo proper has about 14 million people."
+RECORDED_THINKING_TOKENS: Final = 309
+JSON_MODE_THINKING_CONVERSE_RESPONSE: Final = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [
+ {
+ "reasoningContent": {
+ "reasoningText": {
+ "text": RECORDED_REASONING,
+ "signature": "EqoBCkgIBxABGAIiQL1",
+ }
+ }
+ },
+ {
+ "toolUse": {
+ "toolUseId": "tooluse_kZJMlvQmRJ6eAyJE5GIl7Q",
+ "name": "json_tool_call",
+ "input": {"city": "Tokyo", "population_millions": 14.0},
+ }
+ },
+ ],
+ }
+ },
+ "stopReason": "tool_use",
+ "usage": {"inputTokens": 473, "outputTokens": 390, "totalTokens": 863},
+ "additionalModelResponseFields": {
+ "usage": {"output_tokens_details": {"thinking_tokens": RECORDED_THINKING_TOKENS}}
+ },
+}
+
+
+def _answer_with_json_mode_thinking_response(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=JSON_MODE_THINKING_CONVERSE_RESPONSE, request=request)
+
+
+def _bedrock_claude_without_native_structured_output() -> str:
+ return next(
+ f"bedrock/{model}"
+ for model, info in litellm.model_cost.items()
+ if info.get("litellm_provider") == "bedrock_converse"
+ and model.startswith("us.anthropic.claude")
+ and info.get("supports_native_structured_output") is False
+ and info.get("supports_reasoning") is True
+ )
+
+
+def _json_mode_thinking_kwargs() -> dict[str, object]:
+ return {
+ "model": _bedrock_claude_without_native_structured_output(),
+ "messages": [{"role": "user", "content": "How many people live in Tokyo, in millions?"}],
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "city_fact",
+ "schema": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}, "population_millions": {"type": "number"}},
+ "required": ["city", "population_millions"],
+ },
+ },
+ },
+ "thinking": {"type": "enabled", "budget_tokens": 1024},
+ "aws_access_key_id": "fake",
+ "aws_secret_access_key": "fake",
+ "aws_region_name": "us-east-1",
+ }
+
+
+def _answer_fields(response: ModelResponse) -> tuple[object, ...]:
+ choice: Final = response.choices[0]
+ return (
+ choice.finish_reason,
+ choice.message.content,
+ choice.message.tool_calls,
+ getattr(choice.message, "reasoning_content", None),
+ getattr(choice.message, "thinking_blocks", None),
+ getattr(response.usage.completion_tokens_details, "reasoning_tokens", None),
+ )
+
+
+def _streamed_thinking_blocks(chunks: list[litellm.ModelResponseStream]) -> list[object]:
+ deltas: Final = [chunk.choices[0].delta for chunk in chunks if chunk.choices]
+ block_lists: Final = [getattr(delta, "thinking_blocks", None) or [] for delta in deltas]
+ return list(chain.from_iterable(block_lists))
+
+
+def test_fake_streamed_json_mode_answer_keeps_the_reasoning_of_the_non_streamed_answer() -> None:
+ """Without native structured output, json_schema plus streaming fakes the stream from one Converse call. That fake
+ stream dropped the reasoning, the signed thinking blocks and the reasoning tokens, and ended on tool_calls"""
+ transport: Final = httpx.MockTransport(_answer_with_json_mode_thinking_response)
+ client: Final = HTTPHandler(client=httpx.Client(transport=transport))
+ kwargs: Final = _json_mode_thinking_kwargs()
+
+ answer: Final = litellm.completion(client=client, **kwargs)
+ chunks: Final = list(
+ litellm.completion(client=client, stream=True, stream_options={"include_usage": True}, **kwargs)
+ )
+ rebuilt: Final = litellm.stream_chunk_builder(chunks, messages=kwargs["messages"])
+
+ finish_reason, _, _, reasoning_content, _, reasoning_tokens = _answer_fields(answer)
+ assert (finish_reason, reasoning_content, reasoning_tokens) == (
+ "stop",
+ RECORDED_REASONING,
+ RECORDED_THINKING_TOKENS,
+ )
+ assert _answer_fields(rebuilt) == _answer_fields(answer)
+ assert _streamed_thinking_blocks(chunks) == [
+ {**block, "index": index} for index, block in enumerate(answer.choices[0].message.thinking_blocks)
+ ]
+
+
+async def test_async_fake_streamed_json_mode_answer_keeps_the_reasoning_of_the_non_streamed_answer() -> None:
+ client: Final = AsyncHTTPHandler(transport=httpx.MockTransport(_answer_with_json_mode_thinking_response))
+ kwargs: Final = _json_mode_thinking_kwargs()
+
+ answer: Final = await litellm.acompletion(client=client, **kwargs)
+ stream: Final = await litellm.acompletion(
+ client=client, stream=True, stream_options={"include_usage": True}, **kwargs
+ )
+ chunks: Final = [chunk async for chunk in stream]
+ rebuilt: Final = litellm.stream_chunk_builder(chunks, messages=kwargs["messages"])
+
+ finish_reason, _, _, reasoning_content, _, reasoning_tokens = _answer_fields(answer)
+ assert (finish_reason, reasoning_content, reasoning_tokens) == (
+ "stop",
+ RECORDED_REASONING,
+ RECORDED_THINKING_TOKENS,
+ )
+ assert _answer_fields(rebuilt) == _answer_fields(answer)
+ assert _streamed_thinking_blocks(chunks) == [
+ {**block, "index": index} for index, block in enumerate(answer.choices[0].message.thinking_blocks)
+ ]
+
+
+LLAMA_TEXT_TOOL_CALL_CONVERSE_RESPONSE: Final = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [{"text": '{"type": "function", "name": "get_weather", "parameters": {"city": "Paris"}}'}],
+ }
+ },
+ "stopReason": "end_turn",
+ "usage": {"inputTokens": 175, "outputTokens": 23, "totalTokens": 198},
+}
+
+
+def _answer_with_llama_text_tool_call(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=LLAMA_TEXT_TOOL_CALL_CONVERSE_RESPONSE, request=request)
+
+
+def _llama_tool_kwargs() -> dict[str, object]:
+ return {
+ "model": "bedrock/us.meta.llama3-3-70b-instruct-v1:0",
+ "messages": [{"role": "user", "content": "What is the weather in Paris right now?"}],
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+ }
+ ],
+ "aws_access_key_id": "fake",
+ "aws_secret_access_key": "fake",
+ "aws_region_name": "us-east-1",
+ }
+
+
+def _tool_answer(response: ModelResponse) -> tuple[object, ...]:
+ choice: Final = response.choices[0]
+ return (
+ choice.finish_reason,
+ choice.message.content,
+ [(call.function.name, call.function.arguments) for call in choice.message.tool_calls or []],
+ )
+
+
+def test_fake_streamed_text_tool_call_arrives_as_the_tool_call_of_the_non_streamed_answer() -> None:
+ client: Final = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_answer_with_llama_text_tool_call)))
+ kwargs: Final = _llama_tool_kwargs()
+
+ answer: Final = litellm.completion(client=client, **kwargs)
+ chunks: Final = list(litellm.completion(client=client, stream=True, **kwargs))
+
+ assert _tool_answer(answer) == ("tool_calls", None, [("get_weather", '{"city": "Paris"}')])
+ assert _tool_answer(litellm.stream_chunk_builder(chunks, messages=kwargs["messages"])) == _tool_answer(answer)
+
+
+async def test_async_fake_streamed_text_tool_call_arrives_as_the_tool_call_of_the_non_streamed_answer() -> None:
+ client: Final = AsyncHTTPHandler(transport=httpx.MockTransport(_answer_with_llama_text_tool_call))
+ kwargs: Final = _llama_tool_kwargs()
+
+ answer: Final = await litellm.acompletion(client=client, **kwargs)
+ stream: Final = await litellm.acompletion(client=client, stream=True, **kwargs)
+ chunks: Final = [chunk async for chunk in stream]
+
+ assert _tool_answer(answer) == ("tool_calls", None, [("get_weather", '{"city": "Paris"}')])
+ assert _tool_answer(litellm.stream_chunk_builder(chunks, messages=kwargs["messages"])) == _tool_answer(answer)
+
+
+def test_fake_streamed_json_mode_answer_closes_merged_reasoning_before_the_answer() -> None:
+ """A fake stream sends reasoning and answer in one chunk, so merging reasoning into content must open and close
+ the think block around the reasoning in that chunk, before the answer"""
+ client: Final = HTTPHandler(
+ client=httpx.Client(transport=httpx.MockTransport(_answer_with_json_mode_thinking_response))
+ )
+ kwargs: Final = _json_mode_thinking_kwargs()
+
+ answer: Final = litellm.completion(client=client, **kwargs)
+ chunks: Final = list(
+ litellm.completion(client=client, stream=True, merge_reasoning_content_in_choices=True, **kwargs)
+ )
+
+ assert "".join(chunk.choices[0].delta.content or "" for chunk in chunks) == (
+ f"<think>{answer.choices[0].message.reasoning_content}</think>{answer.choices[0].message.content}"
+ )
diff --git a/tests/unit/llms/openai/test_openai.py b/tests/unit/llms/openai/test_openai.py
index e37fd4b6ae5..d7ca9319f3a 100644
--- a/tests/unit/llms/openai/test_openai.py
+++ b/tests/unit/llms/openai/test_openai.py
@@ -10,7 +10,7 @@ from unittest.mock import Mock, patch
import httpx
import pytest
import respx
-from openai import AsyncOpenAI, OpenAI
+from openai import AsyncOpenAI, AzureOpenAI, OpenAI
from openai._types import Response as SDKResponse
from pydantic import BaseModel, ConfigDict, JsonValue
@@ -221,6 +221,79 @@ async def test_acompletion_returns_prompt_cache_details_over_injected_transport(
assert prompt_tokens_details.cached_tokens == 7
+_REASONING_TOOL_CALL_REPLY: Final = {
+ "id": "chatcmpl-fake-stream",
+ "object": "chat.completion",
+ "created": 0,
+ "model": "o4-mini",
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": "tool_calls",
+ "message": {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_weather",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},
+ },
+ {
+ "id": "call_time",
+ "type": "function",
+ "function": {"name": "get_time", "arguments": '{"city": "Paris"}'},
+ },
+ ],
+ },
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 85,
+ "completion_tokens": 1955,
+ "total_tokens": 2040,
+ "prompt_tokens_details": {"cached_tokens": 64},
+ "completion_tokens_details": {"reasoning_tokens": 1920},
+ },
+}
+
+
+def test_azure_o_series_fake_stream_keeps_every_tool_call_and_token_detail():
+ request_bodies: Final[list[dict[str, object]]] = []
+
+ def respond(request: httpx.Request) -> httpx.Response:
+ request_bodies.append(json.loads(request.content))
+ return httpx.Response(200, json=_REASONING_TOOL_CALL_REPLY)
+
+ client: Final = AzureOpenAI(
+ api_key="transport-only",
+ api_version="2025-03-01-preview",
+ azure_endpoint="https://fake-stream.openai.azure.com",
+ http_client=httpx.Client(transport=httpx.MockTransport(respond)),
+ )
+ chunks: Final = list(
+ litellm.completion(
+ model="azure/o_series/reasoning-deployment",
+ api_key="transport-only",
+ api_version="2025-03-01-preview",
+ api_base="https://fake-stream.openai.azure.com",
+ client=client,
+ messages=[{"role": "user", "content": "weather and time in Paris?"}],
+ stream=True,
+ stream_options={"include_usage": True},
+ num_retries=0,
+ )
+ )
+ rebuilt: Final = litellm.stream_chunk_builder(chunks)
+
+ assert [body.get("stream") for body in request_bodies] == [None]
+ assert rebuilt is not None
+ assert rebuilt.choices[0].finish_reason == "tool_calls"
+ assert [call.function.name for call in rebuilt.choices[0].message.tool_calls] == ["get_weather", "get_time"]
+ assert rebuilt.usage.prompt_tokens_details.cached_tokens == 64
+ assert rebuilt.usage.completion_tokens_details.reasoning_tokens == 1920
+
+
@respx.mock
def test_completion_defaults_missing_message_role_and_preserves_omitted_fields() -> None:
route: Final = respx.post("https://api.openai.com/v1/chat/completions").mock(
diff --git a/tests/unit/llms/openai_like/chat/test_openai_like_chat_handler.py b/tests/unit/llms/openai_like/chat/test_openai_like_chat_handler.py
new file mode 100644
index 00000000000..75b60b2dd6c
--- /dev/null
+++ b/tests/unit/llms/openai_like/chat/test_openai_like_chat_handler.py
@@ -0,0 +1,75 @@
+import json
+from typing import Final
+
+from unittest.mock import Mock
+
+import httpx
+
+from litellm.llms.custom_httpx.http_handler import HTTPHandler
+from litellm.llms.openai_like.chat.handler import make_sync_call
+
+_FAKE_STREAMED_REPLY: Final = {
+ "id": "chatcmpl-fake-stream",
+ "object": "chat.completion",
+ "created": 0,
+ "model": "openai/gpt-oss-120b",
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": "tool_calls",
+ "message": {
+ "role": "assistant",
+ "content": None,
+ "reasoning_content": "Look up both values for Paris.",
+ "tool_calls": [
+ {
+ "id": "call_weather",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},
+ },
+ {
+ "id": "call_time",
+ "type": "function",
+ "function": {"name": "get_time", "arguments": '{"city": "Paris"}'},
+ },
+ ],
+ },
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 85,
+ "completion_tokens": 1955,
+ "total_tokens": 2040,
+ "prompt_tokens_details": {"cached_tokens": 64},
+ "completion_tokens_details": {"reasoning_tokens": 1920},
+ },
+}
+
+
+def test_fake_stream_keeps_reasoning_every_tool_call_and_token_detail():
+ request_bodies: Final[list[dict[str, object]]] = []
+
+ def respond(request: httpx.Request) -> httpx.Response:
+ request_bodies.append(json.loads(request.content))
+ return httpx.Response(200, json=_FAKE_STREAMED_REPLY)
+
+ chunks: Final = list(
+ make_sync_call(
+ client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(respond))),
+ api_base="https://openai-like.example/v1/chat/completions",
+ headers={},
+ data=json.dumps({"model": "openai/gpt-oss-120b", "messages": []}),
+ model="openai/gpt-oss-120b",
+ messages=[],
+ logging_obj=Mock(),
+ fake_stream=True,
+ )
+ )
+
+ assert len(request_bodies) == 1
+ assert len(chunks) == 1
+ delta: Final = chunks[0].choices[0].delta
+ assert delta.reasoning_content == "Look up both values for Paris."
+ assert [call.function.name for call in delta.tool_calls] == ["get_weather", "get_time"]
+ assert chunks[0].usage.prompt_tokens_details.cached_tokens == 64
+ assert chunks[0].usage.completion_tokens_details.reasoning_tokens == 1920
diff --git a/tests/unit/llms/snowflake/chat/test_snowflake_chat_transformation.py b/tests/unit/llms/snowflake/chat/test_snowflake_chat_transformation.py
index 5687a319f06..f9d12b7eeea 100644
--- a/tests/unit/llms/snowflake/chat/test_snowflake_chat_transformation.py
+++ b/tests/unit/llms/snowflake/chat/test_snowflake_chat_transformation.py
@@ -8,7 +8,7 @@ import os
import copy
import uuid
import json
-from typing import Any, Dict, List
+from typing import Any, Dict, Final, List
from unittest.mock import AsyncMock, patch, Mock, MagicMock
@@ -595,6 +595,26 @@ class TestSnowflakeCortexClaudeFixes:
assert blocks[0] == {"type": "thinking", "thinking": "391", "signature": "Eto"}
assert [b["type"] for b in blocks] == ["thinking", "tool_use"]
+ def test_signed_thinking_blocks_replay_without_their_stream_index(self):
+ body: Final = self._transform(
+ [
+ {"role": "user", "content": "hi"},
+ {
+ "role": "assistant",
+ "content": "391",
+ "thinking_blocks": [
+ {"type": "thinking", "thinking": "391", "signature": "Eto", "index": 0},
+ {"type": "redacted_thinking", "data": "opaque", "index": 1},
+ ],
+ },
+ ]
+ )
+ blocks: Final = body["messages"][1]["content"]
+ assert blocks[:2] == [
+ {"type": "thinking", "thinking": "391", "signature": "Eto"},
+ {"type": "redacted_thinking", "data": "opaque"},
+ ]
+
def test_signed_thinking_blocks_lead_a_plain_text_assistant_turn(self):
"""A thinking response without a tool call must also round-trip on the next request."""
body = self._transform(
diff --git a/tests/unit/responses/litellm_completion_transformation/test_streaming_iterator_transformation.py b/tests/unit/responses/litellm_completion_transformation/test_streaming_iterator_transformation.py
index 4117c303940..1a3430224d1 100644
--- a/tests/unit/responses/litellm_completion_transformation/test_streaming_iterator_transformation.py
+++ b/tests/unit/responses/litellm_completion_transformation/test_streaming_iterator_transformation.py
@@ -11,6 +11,7 @@ spend tracking stores, so a follow-up previous_response_id still finds the conve
"""
import json
+from collections.abc import Callable
from typing import Final
from unittest.mock import AsyncMock, MagicMock
@@ -978,6 +979,44 @@ def _reasoning_chunk(reasoning: str, finish_reason: str | None = None) -> ModelR
)
+def _with_reasoning(chunk: ModelResponseStream, reasoning: str) -> ModelResponseStream:
+ choice: Final = chunk.choices[0]
+ delta: Final = Delta(**{**choice.delta.model_dump(), "reasoning_content": reasoning})
+ return chunk.model_copy(
+ update={"choices": [StreamingChoices(index=0, delta=delta, finish_reason=choice.finish_reason)]}
+ )
+
+
+def _reasoning_then_text_chunks() -> tuple[ModelResponseStream, ...]:
+ return (_reasoning_chunk("let me think"), _chunk("Hello"), _chunk("!", finish_reason="stop"))
+
+
+def _reasoning_and_text_in_one_chunk() -> tuple[ModelResponseStream, ...]:
+ return (_with_reasoning(_chunk("Hello!", finish_reason="stop"), "let me think"),)
+
+
+def _signed_thinking_and_text_in_one_chunk() -> tuple[ModelResponseStream, ...]:
+ chunk: Final = _chunk("Hello!", finish_reason="stop")
+ signed_block: Final = {"type": "thinking", "thinking": "", "signature": "sig_only"}
+ delta: Final = Delta(**{**chunk.choices[0].delta.model_dump(), "thinking_blocks": [signed_block]})
+ return (
+ chunk.model_copy(update={"choices": [StreamingChoices(index=0, delta=delta, finish_reason="stop")]}),
+ )
+
+
+StreamChunks = Callable[[], tuple[ModelResponseStream, ...]]
+
+REASONING_THEN_TEXT_STREAMS: Final = pytest.mark.parametrize(
+ "stream_chunks",
+ [_reasoning_then_text_chunks, _reasoning_and_text_in_one_chunk],
+ ids=["reasoning_then_text_chunks", "reasoning_and_text_in_one_chunk"],
+)
+
+
+def _event_text(events: list[BaseLiteLLMOpenAIResponseObject], event_type: ResponsesAPIStreamEvents) -> str:
+ return "".join(event.delta for event in events if getattr(event, "type", None) == event_type)
+
+
def _annotation_only_chunk() -> ModelResponseStream:
citation: Final = {"start_index": 0, "end_index": 2, "url": "https://example.com", "title": "Example"}
return ModelResponseStream(
@@ -1134,16 +1173,13 @@ async def test_signature_only_thinking_streams_a_replayable_reasoning_item(sync_
assert json.loads(reasoning_items[0].encrypted_content)[0]["signature"] == "sig_only"
+@REASONING_THEN_TEXT_STREAMS
@pytest.mark.parametrize("sync_mode", [True, False])
@pytest.mark.asyncio
-async def test_reasoning_then_text_announces_message_item_before_text_events(sync_mode: bool):
- iterator: Final = _build_iterator(
- [
- _reasoning_chunk("let me think"),
- _chunk("Hello"),
- _chunk("!", finish_reason="stop"),
- ]
- )
+async def test_reasoning_then_text_announces_message_item_before_text_events(
+ stream_chunks: StreamChunks, sync_mode: bool
+):
+ iterator: Final = _build_iterator(stream_chunks())
events: Final = await _collect_events(iterator, sync_mode)
@@ -1171,23 +1207,22 @@ async def test_reasoning_then_text_announces_message_item_before_text_events(syn
elif event_type == ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE and _is_message_item(event):
assert event.item.id in announced_message_ids
assert saw_text_delta
- assert "".join(
- event.delta for event in events if getattr(event, "type", None) == ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA
- ) == "Hello!"
+ assert _event_text(events, ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA) == "Hello!"
+ assert _event_text(events, ResponsesAPIStreamEvents.REASONING_SUMMARY_TEXT_DELTA) == "let me think"
assert announced_indexes_by_item_type["message"] != announced_indexes_by_item_type["reasoning"]
+ "stream_chunks",
+ [_reasoning_then_text_chunks, _reasoning_and_text_in_one_chunk, _signed_thinking_and_text_in_one_chunk],
+ ids=["reasoning_then_text_chunks", "reasoning_and_text_in_one_chunk", "signed_thinking_and_text_in_one_chunk"],
+)
[email protected]("sync_mode", [True, False])
@pytest.mark.asyncio
-async def test_reasoning_item_closes_before_message_item_opens():
- iterator: Final = _build_iterator(
- [
- _reasoning_chunk("let me think"),
- _chunk("Hello"),
- _chunk("!", finish_reason="stop"),
- ]
- )
+async def test_reasoning_item_closes_before_message_item_opens(stream_chunks: StreamChunks, sync_mode: bool):
+ iterator: Final = _build_iterator(stream_chunks())
- events: Final = await _collect_events(iterator, sync_mode=False)
+ events: Final = await _collect_events(iterator, sync_mode)
item_lifecycle: Final = [
(event.type, event.item.type)
@@ -1201,6 +1236,7 @@ async def test_reasoning_item_closes_before_message_item_opens():
(ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED, "message"),
(ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE, "message"),
]
+ assert _event_text(events, ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA) == "Hello!"
@pytest.mark.parametrize("sync_mode", [True, False])
@@ -1231,6 +1267,27 @@ async def test_tool_then_reasoning_then_text_gives_message_its_own_output_index(
assert len(output_indexes_by_item_id) == len(set(output_indexes_by_item_id.values()))
[email protected]("sync_mode", [True, False])
+async def test_reasoning_item_closes_before_a_tool_call_from_the_same_chunk_opens(sync_mode: bool):
+ iterator: Final = _build_iterator([_with_reasoning(_tool_call_chunk(finish_reason="tool_calls"), "let me think")])
+
+ events: Final = await _collect_events(iterator, sync_mode)
+
+ item_lifecycle: Final = [
+ (event.type, event.item.type)
+ for event in events
+ if getattr(event, "type", None)
+ in (ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED, ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE)
+ ]
+ assert item_lifecycle == [
+ (ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED, "reasoning"),
+ (ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE, "reasoning"),
+ (ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED, "function_call"),
+ (ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE, "function_call"),
+ ]
+
+
@pytest.mark.parametrize("sync_mode", [True, False])
@pytest.mark.asyncio
async def test_tool_only_stream_puts_the_function_call_at_output_index_zero(sync_mode: bool):