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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(anthropic, bedrock)!: keep a redacted_thinking content item on every Claude route (#47489)
Mateo Wang9e3d3a87f401
diff --git a/litellm/integrations/anthropic_cache_control_hook.py b/litellm/integrations/anthropic_cache_control_hook.pyindex abdbfc79d41..b0deec24c1a 100644--- a/litellm/integrations/anthropic_cache_control_hook.py+++ b/litellm/integrations/anthropic_cache_control_hook.py@@ -342,6 +342,20 @@ EXTERNAL_BREAKPOINTS_STAMP: Final = "_litellm_external_breakpoints"CUSTOM_LLM_PROVIDER_STAMP: Final = "_litellm_custom_llm_provider"+def _accepts_cache_control(part: object) -> bool:+ match part:+ case {"type": "thinking" | "redacted_thinking"}:+ return False+ case dict():+ return True+ case _:+ return False+++def _last_index_accepting_cache_control(parts: Sequence[object]) -> int | None:+ return next((index for index in reversed(range(len(parts))) if _accepts_cache_control(parts[index])), None)++class AnthropicCacheControlHook(CustomPromptManagement):@staticmethoddef _request_value(request_kwargs: object, key: str) -> object:@@ -740,10 +754,11 @@ class AnthropicCacheControlHook(CustomPromptManagement):# 1. if string, insert cache control in the messageif isinstance(message_content, str):message["cache_control"] = control- # 2. list of objects - only apply to last item per Anthropic spec+ # 2. list of objects - only apply to the last item Claude accepts a breakpoint onelif isinstance(message_content, list):- if len(message_content) > 0 and isinstance(message_content[-1], dict):- message_content[-1]["cache_control"] = control # pyright: ignore[reportGeneralTypeIssues] # loose runtime dict+ markable_index: Final = _last_index_accepting_cache_control(message_content)+ if markable_index is not None:+ message_content[markable_index]["cache_control"] = control # pyright: ignore[reportGeneralTypeIssues] # loose runtime dictreturn message@staticmethoddiff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.pyindex b704dfa2675..b89e4d609ad 100644--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py@@ -2325,6 +2325,16 @@ def is_unsignable_thinking_block(block: object) -> bool:return not (isinstance(signature, str) and len(signature) > 0)+def has_blank_redacted_data(block: object) -> bool:+ match block:+ case {"type": "redacted_thinking", "data": str() as data}:+ return not data.strip()+ case {"type": "redacted_thinking"}:+ return True+ case _:+ return False++def native_redacted_thinking_data(data: str) -> str:"""Claude's own `data` string for a redacted_thinking block.diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.pyindex 481ec6a5076..3d865bd1819 100644--- a/litellm/litellm_core_utils/prompt_templates/factory.py+++ b/litellm/litellm_core_utils/prompt_templates/factory.py@@ -6,10 +6,10 @@ import jsonimport mimetypesimport reimport xml.etree.ElementTree as ET-from collections.abc import Container, Iterable, Iterator, Mapping, Sequence+from collections.abc import Callable, Container, Iterable, Iterator, Mapping, Sequencefrom enum import Enumfrom types import MappingProxyType-from typing import Annotated, Any, Final, TypeAlias, TypedDict, cast, overload+from typing import Annotated, Any, Final, TypeAlias, TypedDict, TypeVar, cast, overloadfrom jinja2.sandbox import ImmutableSandboxedEnvironmentfrom pydantic import BaseModel, BeforeValidator, ConfigDict, JsonValue, TypeAdapter, ValidationError, model_validator@@ -61,6 +61,7 @@ from litellm.types.utils import GenericImageParsingChunkfrom .common_utils import (converse_redacted_content,convert_content_list_to_str,+ has_blank_redacted_data,infer_content_type_from_url_and_content,is_encrypted_reasoning_block,is_non_content_values_set,@@ -2550,22 +2551,125 @@ def _pair_tool_calls_with_results(messages: Sequence[AllMessageValues]) -> tupledef _replayable_thinking_blocks(thinking_blocks: list[ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock],+ *,+ drop_params: bool = False,) -> list[ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock]:+ keys_to_drop: Final = _UNSUPPORTED_THINKING_KEYS if drop_params else _STREAM_ONLY_THINKING_KEYSreturn [- _without_stream_index(_with_native_redacted_data(block))+ _without_keys(_with_native_redacted_data(block), keys_to_drop)for block in thinking_blocks- if not is_unsignable_thinking_block(block)+ if not (is_unsignable_thinking_block(block) or (drop_params and has_blank_redacted_data(block)))]-def _without_stream_index(+def _as_thinking_block(item: object) -> ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock | None:+ match item:+ case {"type": "thinking" | "redacted_thinking"}:+ return cast( # cast-ok: the mapping pattern matched a thinking block's type tag+ ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock, item+ )+ case _:+ return None+++def _thinking_identity(item: object) -> tuple[str | None, ...] | None:+ match item:+ case {"type": "redacted_thinking", "data": str() as data}:+ return ("redacted_thinking", native_redacted_thinking_data(data))+ case {"type": "thinking", "signature": str() as signature} if signature:+ return ("thinking", signature)+ case {"type": str() as kind} if kind in ("thinking", "redacted_thinking"):+ fields: Final = cast(Mapping[str, object], item) # cast-ok: the mapping pattern matched+ return _unsigned_thinking_identity(kind, fields.get("thinking"), fields.get("signature"))+ case _:+ return None+++def _unsigned_thinking_identity(kind: str, thinking: object, signature: object) -> tuple[str | None, ...] | None:+ match thinking, signature:+ case (str() | None as text, str() | None as signed):+ return (kind, text, signed)+ case _:+ return None+++_Replayed: Final = TypeVar("_Replayed")+++def _with_missing_thinking_blocks(+ content: Iterable[_Replayed], thinking_blocks: Sequence[_Replayed]+) -> tuple[_Replayed, ...]:+ content_items: Final = tuple(content)+ block_identities: Final = tuple(map(_thinking_identity, thinking_blocks))+ content_positions: Final[Mapping[tuple[object, ...] | None, int]] = MappingProxyType(+ {+ identity: index+ for index, identity in reversed(tuple(enumerate(map(_thinking_identity, content_items))))+ if identity is not None+ }+ )+ anchors: Final = tuple(index for index, identity in enumerate(block_identities) if identity in content_positions)+ if not anchors:+ return (*thinking_blocks, *content_items)+ missing_before: Final = MappingProxyType(+ {+ content_positions[block_identities[end]]: thinking_blocks[start + 1 : end]+ for start, end in zip((-1, *anchors), anchors)+ }+ )+ missing_after: Final = MappingProxyType(+ {content_positions[block_identities[anchors[-1]]]: thinking_blocks[anchors[-1] + 1 :]}+ )+ return tuple(_interleave(content_items, missing_before, missing_after))+++def _without_repeated_thinking(+ items: Sequence[_Replayed], identity: Callable[[_Replayed], tuple[object, ...] | None]+) -> tuple[_Replayed, ...]:+ identities: Final = tuple(map(identity, items))+ first_positions: Final[Mapping[tuple[object, ...], int]] = MappingProxyType(+ {key: index for index, key in reversed(tuple(enumerate(identities))) if key is not None}+ )+ return tuple(+ item for index, (item, key) in enumerate(zip(items, identities)) if key is None or first_positions[key] == index+ )+++def _interleave(+ content: Sequence[_Replayed],+ before: Mapping[int, Sequence[_Replayed]],+ after: Mapping[int, Sequence[_Replayed]],+) -> Iterator[_Replayed]:+ for index, item in enumerate(content):+ yield from before.get(index, ())+ yield item+ yield from after.get(index, ())+++def _thinking_in_replay_order(+ content: str | Iterable[object] | None, thinking_blocks: Sequence[object] | None+) -> tuple[ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock, ...]:+ content_items: Final = content if isinstance(content, list) else ()+ return tuple(+ block+ for item in _with_missing_thinking_blocks(content_items, thinking_blocks or ())+ if (block := _as_thinking_block(item)) is not None+ )+++_STREAM_ONLY_THINKING_KEYS: Final = frozenset({"index"})+_UNSUPPORTED_THINKING_KEYS: Final = frozenset({"index", "cache_control"})+++def _without_keys(block: ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock,+ keys: frozenset[str],) -> ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock:- if "index" not in block:+ if keys.isdisjoint(block):return block- return cast( # cast-ok: dropping one key keeps the block's TypedDict shape+ return cast( # cast-ok: dropping keys keeps the block's TypedDict shapeChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock,- {key: value for key, value in block.items() if key != "index"},+ {key: value for key, value in block.items() if key not in keys},)@@ -2629,6 +2733,7 @@ def anthropic_messages_pt(messages: list[AllMessageValues],model: str,llm_provider: str,+ drop_params: bool = False,) -> _AnthropicMessageList:"""format messages for anthropic@@ -2816,7 +2921,9 @@ def anthropic_messages_pt(_raw_thinking_blocks = assistant_content_block.get("thinking_blocks", None)thinking_blocks = (- _replayable_thinking_blocks(_raw_thinking_blocks) if _raw_thinking_blocks is not None else None+ _replayable_thinking_blocks(_raw_thinking_blocks, drop_params=drop_params)+ if _raw_thinking_blocks is not None+ else None)# Check if tool_calls contain server tool calls (web search, etc.)@@ -2951,42 +3058,28 @@ def anthropic_messages_pt(# SEQUENTIAL MODE: No server tool calls, or no thinking blocks,# or content is a list. Use the original sequential approach.- # When content is a list, check if it already contains thinking- # blocks inline. If so, skip prepending thinking_blocks to avoid- # duplication and preserve the original interleaved order.- # Fixes the gap where list-content messages bypass INTERLEAVED- # MODE and still get thinking blocks prepended out of order._content_is_list = "content" in assistant_content_block and isinstance(assistant_content_block["content"], list)_content_list = assistant_content_block.get("content") if _content_is_list else None- _list_has_thinking = False- if _content_is_list and _content_list is not None:- for _item in _content_list:- if isinstance(_item, dict) and _item.get("type") in (- "thinking",- "redacted_thinking",- ):- _list_has_thinking = True- breakif (- thinking_blocks is not None and not _list_has_thinking+ thinking_blocks is not None and not _content_is_list): # IMPORTANT: ADD THIS FIRST, ELSE ANTHROPIC WILL RAISE AN ERRORassistant_content.extend(thinking_blocks)if _content_is_list and _content_list is not None:- for m in _content_list:+ for m in _with_missing_thinking_blocks(_content_list, thinking_blocks or ()):if not isinstance(m, dict):continue# handle thinking blocks- text_block = cast(str, m.get("text", ""))- if m.get("type", "") == "thinking" and not is_unsignable_thinking_block(m):- anthropic_message: ChatCompletionThinkingBlock | AnthropicMessagesTextParam = cast(- ChatCompletionThinkingBlock, m+ if (thinking_block := _as_thinking_block(m)) is not None:+ assistant_content.extend(+ _replayable_thinking_blocks([thinking_block], drop_params=drop_params))- assistant_content.append(anthropic_message)+ continue+ text_block = cast(str, m.get("text", ""))# handle text- elif (+ if (m.get("type", "") == "text" and len(text_block) > 0): # don't pass empty text blocks. anthropic api raises errors.anthropic_message = AnthropicMessagesTextParam(type="text", text=text_block)@@ -3058,7 +3151,12 @@ def anthropic_messages_pt(msg_i += 1if assistant_content:- new_messages.append({"role": "assistant", "content": assistant_content})+ new_messages.append(+ {+ "role": "assistant",+ "content": list(_without_repeated_thinking(assistant_content, _thinking_identity)),+ }+ )## MID-CONVERSATION SYSTEM MESSAGES (placement is the caller's job) ##while msg_i < len(messages) and messages[msg_i]["role"] == "system":@@ -4190,6 +4288,16 @@ def _convert_to_bedrock_tool_call_result(return content_block+def _reasoning_identity(block: BedrockContentBlock) -> tuple[object, ...] | None:+ match block:+ case {"reasoningContent": {"redactedContent": redacted}}:+ return ("redacted_thinking", redacted)+ case {"reasoningContent": {"reasoningText": {"signature": str() as signature}}} if signature:+ return ("thinking", signature)+ case _:+ return None++def _deduplicate_bedrock_content_blocks(blocks: list[BedrockContentBlock],block_key: str,@@ -4673,6 +4781,7 @@ class BedrockConverseMessagesProcessor:assistant_continue_message: str | ChatCompletionAssistantMessage | None = None,deployment_model: str | None = None,base_model: str | None = None,+ drop_params: bool = False,) -> list[BedrockMessageBlock]:from litellm.llms.bedrock.common_utils import bedrock_converse_accepts_redacted_thinking@@ -4826,33 +4935,21 @@ class BedrockConverseMessagesProcessor:)_assistant_content = assistant_message_block.get("content", None)thinking_blocks = assistant_message_block.get("thinking_blocks")-- if thinking_blocks is not None:- converted_thinking_blocks = (- BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks(- thinking_blocks, to_claude=to_claude- )- )- assistant_content = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content(- thinking_blocks=converted_thinking_blocks,- assistant_parts=assistant_content,+ converted_thinking_blocks = (+ BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks(+ _thinking_in_replay_order(_assistant_content, thinking_blocks), to_claude=to_claude)+ )+ assistant_content = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content(+ thinking_blocks=converted_thinking_blocks,+ assistant_parts=assistant_content,+ )if _assistant_content is not None and isinstance(_assistant_content, list):assistants_parts: list[BedrockContentBlock] = []for element in _assistant_content:if isinstance(element, dict):- if element["type"] == "thinking" or element["type"] == "redacted_thinking":- thinking_block = BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks(- thinking_blocks=[element], to_claude=to_claude- )- assistants_parts = (- BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content(- thinking_blocks=thinking_block,- assistant_parts=assistants_parts,- )- )- elif element["type"] == "text":+ if element["type"] == "text":# Skip completely empty strings to avoid blank content blocksif element.get("text", "").strip():assistants_part = BedrockContentBlock(text=element["text"])@@ -4871,7 +4968,9 @@ class BedrockConverseMessagesProcessor:model=model,deployment_model=deployment_model,)- if _cache_point_block is not None:+ if _cache_point_block is not None and not (+ drop_params and _as_thinking_block(element) is not None+ ):assistants_parts.append(_cache_point_block)assistant_content.extend(assistants_parts)elif _assistant_content is not None and isinstance(_assistant_content, str):@@ -4899,7 +4998,11 @@ class BedrockConverseMessagesProcessor:msg_i += 1- assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse")+ assistant_content = list(+ _without_repeated_thinking(+ _deduplicate_bedrock_content_blocks(assistant_content, "toolUse"), _reasoning_identity+ )+ )assistant_content = _sort_bedrock_assistant_content_blocks(assistant_content)if assistant_content:@@ -5083,6 +5186,7 @@ def _bedrock_converse_messages_pt(assistant_continue_message: str | ChatCompletionAssistantMessage | None = None,deployment_model: str | None = None,base_model: str | None = None,+ drop_params: bool = False,) -> list[BedrockMessageBlock]:"""Converts given messages from OpenAI format to Bedrock format@@ -5244,35 +5348,21 @@ def _bedrock_converse_messages_pt()_assistant_content = assistant_message_block.get("content", None)thinking_blocks = assistant_message_block.get("thinking_blocks")-- if thinking_blocks is not None:- converted_thinking_blocks = (- BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks(- thinking_blocks, to_claude=to_claude- )- )- assistant_content = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content(- thinking_blocks=converted_thinking_blocks,- assistant_parts=assistant_content,+ converted_thinking_blocks = (+ BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks(+ _thinking_in_replay_order(_assistant_content, thinking_blocks), to_claude=to_claude)+ )+ assistant_content = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content(+ thinking_blocks=converted_thinking_blocks,+ assistant_parts=assistant_content,+ )if _assistant_content is not None and isinstance(_assistant_content, list):assistants_parts: list[BedrockContentBlock] = []for element in _assistant_content:if isinstance(element, dict):- if element["type"] == "thinking" or element["type"] == "redacted_thinking":- thinking_block = (- BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks(- thinking_blocks=[element], to_claude=to_claude- )- )- assistants_parts = (- BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content(- thinking_blocks=thinking_block,- assistant_parts=assistants_parts,- )- )- elif element["type"] == "text":+ if element["type"] == "text":# AWS Bedrock doesn't allow empty or whitespace-only text content# Skip completely empty strings to avoid blank content blocksif element.get("text", "").strip():@@ -5292,7 +5382,9 @@ def _bedrock_converse_messages_pt(model=model,deployment_model=deployment_model,)- if _cache_point_block is not None:+ if _cache_point_block is not None and not (+ drop_params and _as_thinking_block(element) is not None+ ):assistants_parts.append(_cache_point_block)assistant_content.extend(assistants_parts)elif _assistant_content is not None and isinstance(_assistant_content, str):@@ -5313,7 +5405,11 @@ def _bedrock_converse_messages_pt(msg_i += 1- assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse")+ assistant_content = list(+ _without_repeated_thinking(+ _deduplicate_bedrock_content_blocks(assistant_content, "toolUse"), _reasoning_identity+ )+ )assistant_content = _sort_bedrock_assistant_content_blocks(assistant_content)if assistant_content:diff --git a/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.py b/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.pyindex fd0096f9f4d..ecf419695d0 100644--- a/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.py+++ b/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.py@@ -49,7 +49,7 @@ from litellm.types.llms.openai import (ChatCompletionUserMessage,)-from .common_utils import is_unsignable_thinking_block+from .common_utils import has_blank_redacted_data, is_unsignable_thinking_blockCONVERTED_SYSTEM_NOTE: Final = ("Operator note (not from the user): the following was originally a mid-conversation system-role reminder."@@ -267,27 +267,22 @@ def _block_index_by_message(blocks: Sequence[tuple[bool, tuple[int, ...]]]) -> Mdef _thinking_block_renders(block: object) -> bool:"""A thinking block the converter keeps: one Anthropic can verify, so never bridged encrypted reasoning."""- return message_field(block, "type") in _THINKING_BLOCK_TYPES and not is_unsignable_thinking_block(block)+ return message_field(block, "type") in _THINKING_BLOCK_TYPES and not (+ is_unsignable_thinking_block(block) or has_blank_redacted_data(block)+ )def _assistant_part_renders(part: object) -> bool:"""A text part always renders: the converter pads empty text with a placeholder."""part_type: Final = message_field(part, "type")- if part_type == "thinking":+ if part_type in _THINKING_BLOCK_TYPES:return _thinking_block_renders(part)return part_type in _RENDERED_ASSISTANT_PART_TYPES or (isinstance(part_type, str) and part_type.endswith("_tool_result"))-def _separate_thinking_blocks_render(message: object, parts: Sequence[object]) -> bool:- """``thinking_blocks`` reach the wire only when no inline thinking part claims the slot.-- The converter skips the separate blocks as soon as the content list carries a- ``thinking`` or ``redacted_thinking`` part, whether or not that part itself renders.- """- if any(message_field(part, "type") in _THINKING_BLOCK_TYPES for part in parts):- return False+def _separate_thinking_blocks_render(message: object) -> bool:return any(_thinking_block_renders(block) for block in parts_of(message_field(message, "thinking_blocks")))@@ -404,7 +399,7 @@ def _assistant_renders(message: object, answered: frozenset[str]) -> bool:parts: Final = parts_of(content)return (any(_assistant_part_renders(part) for part in parts)- or _separate_thinking_blocks_render(message, parts)+ or _separate_thinking_blocks_render(message)or _tool_calls_render(message, answered)or bool(message_field(message, "function_call"))or bool(message_field(message_field(message, "provider_specific_fields"), "compaction_blocks"))diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.pyindex 867dd935a03..9a63afd5cc0 100644--- a/litellm/llms/anthropic/chat/transformation.py+++ b/litellm/llms/anthropic/chat/transformation.py@@ -2267,6 +2267,8 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):anthropic_messages_pt,)+ drop_params: Final = litellm.drop_params is True or litellm_params.get("drop_params") is True+if "tools" not in optional_params and messages is not None and has_tool_call_blocks(messages):optional_params["tools"], _ = self._map_tools(add_dummy_tool(custom_llm_provider="anthropic"))@@ -2293,7 +2295,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):AnthropicConfig._maybe_drop_speed_param(model=model,optional_params=optional_params,- drop_params=litellm.drop_params or litellm_params.get("drop_params") is True,+ drop_params=drop_params,custom_llm_provider=self.custom_llm_provider,)@@ -2351,6 +2353,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):model=model,messages=list(conversation),llm_provider=self._resolved_provider,+ drop_params=drop_params,)except Exception as e:raise AnthropicError(diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.pyindex b505ae47c61..cd3727401ef 100644--- a/litellm/llms/bedrock/chat/converse_transformation.py+++ b/litellm/llms/bedrock/chat/converse_transformation.py@@ -2127,6 +2127,7 @@ class AmazonConverseConfig(BaseConfig):llm_provider="bedrock_converse",user_continue_message=litellm_params.pop("user_continue_message", None),base_model=self._deployment_base_model(_DEPLOYMENT_PARAMS.validate_python(litellm_params)),+ drop_params=litellm.drop_params is True or litellm_params.get("drop_params") is True,),capability_model,)@@ -2207,6 +2208,7 @@ class AmazonConverseConfig(BaseConfig):llm_provider="bedrock_converse",user_continue_message=litellm_params.pop("user_continue_message", None),base_model=self._deployment_base_model(_DEPLOYMENT_PARAMS.validate_python(litellm_params)),+ drop_params=litellm.drop_params is True or litellm_params.get("drop_params") is True,),capability_model,)diff --git a/tests/unit/integrations/test_anthropic_cache_control_hook.py b/tests/unit/integrations/test_anthropic_cache_control_hook.pyindex 22db24f6ffd..c70c7080ab8 100644--- a/tests/unit/integrations/test_anthropic_cache_control_hook.py+++ b/tests/unit/integrations/test_anthropic_cache_control_hook.py@@ -1705,6 +1705,39 @@ def test_cache_control_hook_does_not_overwrite_existing_cache_control():assert _count_cache_control(processed) == 1+ "content, marked_parts",+ [+ ([{"type": "text", "text": "Checking."}, {"type": "redacted_thinking", "data": "abc"}], [0]),+ ([{"type": "redacted_thinking", "data": "abc"}], []),+ ([{"type": "thinking", "thinking": "hm", "signature": "s"}], []),+ ([{"type": "text", "text": "Checking."}, "not a content block"], [0]),+ ],+ ids=["text-before-trailing-redacted-thinking", "redacted-thinking-only", "signed-thinking-only", "text-before-a-string"],+)+def test_assistant_injection_never_marks_a_thinking_part(+ content: list[dict[str, str] | str], marked_parts: list[int]+):+ """Claude 400s a cache_control on a thinking or redacted_thinking block, and Bedrock Converse 400s a cache+ point after reasoning, so the breakpoint goes on the last part that can carry one."""+ messages: Final[list[AllMessageValues]] = [+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": copy.deepcopy(content)},+ {"role": "user", "content": "again"},+ ]++ _, processed, _ = AnthropicCacheControlHook().get_chat_completion_prompt(+ model="anthropic/claude-sonnet-4-6",+ messages=messages,+ non_default_params={"cache_control_injection_points": [{"location": "message", "role": "assistant"}]},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ )++ assert [index for index, part in enumerate(processed[1]["content"]) if "cache_control" in part] == marked_parts++@pytest.mark.asyncioasync def test_cache_control_hook_bedrock_payload_caps_cachepoints_at_four(monkeypatch: pytest.MonkeyPatch):"""End-to-end: outgoing Bedrock payload must not exceed 4 cachePoint blocks.diff --git a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.pyindex 046f448046b..fad1c6178dc 100644--- a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py+++ b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py@@ -541,25 +541,66 @@ def test_bedrock_converse_assistant_with_empty_thinking_block_and_tool_calls():_NATIVE_REDACTED_DATA: Final = "EmwKAhgBEgy3va3pzix/LafPsn4aDFIT2Xlxh0L5L8rLVyIwxtE3rAFBa8cr3qpP"_CONVERSE_REDACTED_DATA: Final = base64.b64encode(_NATIVE_REDACTED_DATA.encode()).decode()+REASONING_PLACEMENTS: Final = pytest.mark.parametrize(+ "placement", ["thinking_blocks", "content", "both", "first-block-in-content", "last-block-in-content"]+)+++def _assistant_with_reasoning(+ placement: str, reasoning: Sequence[Mapping[str, object]], text: str+) -> Mapping[str, object]:+ in_content: Final = {"role": "assistant", "content": [*reasoning, {"type": "text", "text": text}]}+ return {+ "thinking_blocks": {"role": "assistant", "content": text, "thinking_blocks": list(reasoning)},+ "content": in_content,+ "both": {**in_content, "thinking_blocks": list(reasoning)},+ "first-block-in-content": {+ "role": "assistant",+ "content": [*reasoning[:1], {"type": "text", "text": text}],+ "thinking_blocks": list(reasoning),+ },+ "last-block-in-content": {+ "role": "assistant",+ "content": [*reasoning[-1:], {"type": "text", "text": text}],+ "thinking_blocks": list(reasoning),+ },+ }[placement]+++SPLIT_REASONING: Final = pytest.mark.parametrize(+ ("in_content", "in_thinking_blocks"),+ [((0, 2), (0, 1, 2)), ((0, 1, 2), (1,))],+ ids=["middle-block-only-in-thinking-blocks", "outer-blocks-only-in-content"],+)+++COPY_TEXT: Final = pytest.mark.parametrize("copy_text", ["", "First"], ids=["emptied", "trimmed"])+++def _assistant_with_split_reasoning(+ reasoning: Sequence[Mapping[str, object]], in_content: Sequence[int], in_thinking_blocks: Sequence[int], text: str+) -> Mapping[str, object]:+ return {+ "role": "assistant",+ "content": [*(reasoning[index] for index in in_content), {"type": "text", "text": text}],+ "thinking_blocks": [reasoning[index] for index in in_thinking_blocks],+ }@pytest.mark.asyncio@pytest.mark.parametrize("use_async", [False, True])[email protected]("placement", ["thinking_blocks", "content"])+@REASONING_PLACEMENTSasync def test_bedrock_converse_replays_redacted_thinking_as_redacted_content(use_async: bool, placement: str):"""A redacted_thinking block that Bedrock returned must go back as reasoningContent.redactedContent,- in order, ahead of text and toolUse. It used to collapse into an empty unsigned reasoningText and get dropped."""+ in order, ahead of text and toolUse. It used to collapse into an empty unsigned reasoningText and get dropped.+ Sent twice, when the history carries it in content and thinking_blocks, Bedrock 400s that it was modified."""bedrock_reasoning_blocks: Final[list[BedrockConverseReasoningContentBlock]] = [{"reasoningText": {"text": "Let me look this up.", "signature": "sig-abc"}},{"redactedContent": _CONVERSE_REDACTED_DATA},]thinking_blocks: Final = litellm.AmazonConverseConfig()._transform_thinking_blocks(bedrock_reasoning_blocks)assistant_text: Final = "Checking the weather."- assistant_message: Final = (- {"role": "assistant", "content": assistant_text, "thinking_blocks": thinking_blocks}- if placement == "thinking_blocks"- else {"role": "assistant", "content": [*thinking_blocks, {"type": "text", "text": assistant_text}]}- )+ assistant_message: Final = _assistant_with_reasoning(placement, thinking_blocks, assistant_text)messages: Final = [{"role": "user", "content": "What's the weather in Paris?"},{@@ -593,6 +634,231 @@ async def test_bedrock_converse_replays_redacted_thinking_as_redacted_content(us][email protected]("use_async", [False, True])+@COPY_TEXT+async def test_bedrock_converse_sends_a_signed_block_once_when_thinking_blocks_holds_other_text(+ use_async: bool, copy_text: str+):+ bedrock_reasoning_blocks: Final[list[BedrockConverseReasoningContentBlock]] = [+ {"reasoningText": {"text": "First.", "signature": "sig-1"}},+ {"redactedContent": _CONVERSE_REDACTED_DATA},+ ]+ reasoning: Final = litellm.AmazonConverseConfig()._transform_thinking_blocks(bedrock_reasoning_blocks)+ messages: Final = [+ {"role": "user", "content": "hi"},+ {+ "role": "assistant",+ "content": [*reasoning, {"type": "text", "text": "hello"}],+ "thinking_blocks": [{**reasoning[0], "thinking": copy_text}, reasoning[1]],+ },+ {"role": "user", "content": "again"},+ ]+ model: Final = "us.anthropic.claude-sonnet-4-6"++ result: Final = (+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(+ messages=messages, model=model, llm_provider="bedrock"+ )+ if use_async+ else _bedrock_converse_messages_pt(messages=messages, model=model, llm_provider="bedrock")+ )++ assert result[1] == {+ "role": "assistant",+ "content": [*({"reasoningContent": block} for block in bedrock_reasoning_blocks), {"text": "hello"}],+ }+++_WEATHER_TOOL_CALL: Final = {+ "id": "tooluse_weather_1",+ "type": "function",+ "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},+}+++def _block_split_across_assistant_messages(blocks: Sequence[Mapping[str, object]]) -> list[dict[str, object]]:+ return [+ {"role": "user", "content": "What's the weather in Paris?"},+ {"role": "assistant", "content": list(blocks)},+ {"role": "assistant", "content": None, "thinking_blocks": list(blocks), "tool_calls": [_WEATHER_TOOL_CALL]},+ {"role": "tool", "tool_call_id": "tooluse_weather_1", "content": "18C, sunny"},+ ]++[email protected]("use_async", [False, True])+async def test_bedrock_converse_sends_a_block_once_when_two_assistant_messages_carry_it(use_async: bool):+ bedrock_reasoning_blocks: Final[list[BedrockConverseReasoningContentBlock]] = [+ {"reasoningText": {"text": "Let me look this up.", "signature": "sig-abc"}},+ {"redactedContent": _CONVERSE_REDACTED_DATA},+ ]+ reasoning: Final = litellm.AmazonConverseConfig()._transform_thinking_blocks(bedrock_reasoning_blocks)+ messages: Final = _block_split_across_assistant_messages(reasoning)+ model: Final = "us.anthropic.claude-sonnet-4-6"++ result: Final = (+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(+ messages=messages, model=model, llm_provider="bedrock"+ )+ if use_async+ else _bedrock_converse_messages_pt(messages=messages, model=model, llm_provider="bedrock")+ )++ assert result[1] == {+ "role": "assistant",+ "content": [+ *({"reasoningContent": block} for block in bedrock_reasoning_blocks),+ {"toolUse": {"toolUseId": "tooluse_weather_1", "name": "get_weather", "input": {"city": "Paris"}}},+ ],+ }++[email protected]("use_async", [False, True])+@SPLIT_REASONING+async def test_bedrock_converse_keeps_reasoning_order_across_content_and_thinking_blocks(+ use_async: bool, in_content: Sequence[int], in_thinking_blocks: Sequence[int]+):+ """A reasoning block only one of content and thinking_blocks carries goes back in its original place."""+ bedrock_reasoning_blocks: Final[list[BedrockConverseReasoningContentBlock]] = [+ {"reasoningText": {"text": "First.", "signature": "sig-1"}},+ {"redactedContent": _CONVERSE_REDACTED_DATA},+ {"reasoningText": {"text": "Third.", "signature": "sig-3"}},+ ]+ reasoning: Final = litellm.AmazonConverseConfig()._transform_thinking_blocks(bedrock_reasoning_blocks)+ messages: Final = [+ {"role": "user", "content": "hi"},+ _assistant_with_split_reasoning(reasoning, in_content, in_thinking_blocks, "hello"),+ {"role": "user", "content": "again"},+ ]+ model: Final = "us.anthropic.claude-sonnet-4-6"++ result: Final = (+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(+ messages=messages, model=model, llm_provider="bedrock"+ )+ if use_async+ else _bedrock_converse_messages_pt(messages=messages, model=model, llm_provider="bedrock")+ )++ assert result[1] == {+ "role": "assistant",+ "content": [*({"reasoningContent": block} for block in bedrock_reasoning_blocks), {"text": "hello"}],+ }++[email protected]("use_async", [False, True])[email protected]("entry", [None, "not a block"], ids=["none", "string"])+async def test_bedrock_converse_skips_a_thinking_blocks_entry_that_is_not_a_block(use_async: bool, entry: object):+ messages: Final = [+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "hello", "thinking_blocks": [entry]},+ {"role": "user", "content": "again"},+ ]+ model: Final = "us.anthropic.claude-sonnet-4-6"++ result: Final = (+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(+ messages=messages, model=model, llm_provider="bedrock"+ )+ if use_async+ else _bedrock_converse_messages_pt(messages=messages, model=model, llm_provider="bedrock")+ )++ assert result[1] == {"role": "assistant", "content": [{"text": "hello"}]}+++MALFORMED_THINKING: Final = pytest.mark.parametrize(+ "malformed",+ [+ {"type": "thinking", "thinking": {"a": 1}},+ {"type": "thinking", "thinking": ["a"], "signature": ""},+ {"type": "thinking", "thinking": "draft", "signature": ["a"]},+ ],+ ids=["dict-thinking", "list-thinking", "list-signature"],+)++[email protected]("use_async", [False, True])+@REASONING_PLACEMENTS+@MALFORMED_THINKING+async def test_bedrock_converse_replays_redacted_thinking_once_beside_a_malformed_thinking_item(+ use_async: bool, placement: str, malformed: dict[str, object]+):+ messages: Final = [+ {"role": "user", "content": "hi"},+ _assistant_with_reasoning(+ placement, [{"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA}, malformed], "hello"+ ),+ {"role": "user", "content": "again"},+ ]+ model: Final = "us.anthropic.claude-sonnet-4-6"++ result: Final = (+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(+ messages=messages, model=model, llm_provider="bedrock"+ )+ if use_async+ else _bedrock_converse_messages_pt(messages=messages, model=model, llm_provider="bedrock")+ )++ assert result[1]["content"].count({"reasoningContent": {"redactedContent": _CONVERSE_REDACTED_DATA}}) == 1+++@REASONING_PLACEMENTS+@MALFORMED_THINKING+def test_anthropic_messages_pt_replays_redacted_thinking_once_beside_a_malformed_thinking_item(+ placement: str, malformed: dict[str, object]+):+ redacted: Final = {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA}+ messages: Final = [+ {"role": "user", "content": "hi"},+ _assistant_with_reasoning(placement, [redacted, malformed], "hello"),+ {"role": "user", "content": "again"},+ ]++ result: Final = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")++ assert result[1]["content"].count(redacted) == 1++[email protected]("use_async", [False, True])[email protected]("drop_params", [False, True])+async def test_bedrock_converse_drops_a_cache_point_after_reasoning_only_under_drop_params(+ use_async: bool, drop_params: bool+):+ """Bedrock 400s "Cache point cannot be inserted after reasoning block", so drop_params drops the+ breakpoint and without it the request reaches Bedrock as sent."""+ messages: Final = [+ {"role": "user", "content": "hi"},+ {+ "role": "assistant",+ "content": [+ {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA, "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "hello"},+ ],+ },+ {"role": "user", "content": "again"},+ ]+ model: Final = "us.anthropic.claude-sonnet-4-6"++ result: Final = (+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(+ messages=messages, model=model, llm_provider="bedrock", drop_params=drop_params+ )+ if use_async+ else _bedrock_converse_messages_pt(+ messages=messages, model=model, llm_provider="bedrock", drop_params=drop_params+ )+ )++ assert ({"cachePoint": {"type": "default"}} in result[1]["content"]) is not drop_params++_SENT_REDACTED: Final = [{"reasoningContent": {"redactedContent": _CONVERSE_REDACTED_DATA}}]@@ -813,30 +1079,143 @@ def test_anthropic_messages_pt_drops_unsignable_thinking_block(thinking_block):)+@REASONING_PLACEMENTS@pytest.mark.parametrize("data", [_NATIVE_REDACTED_DATA, _CONVERSE_REDACTED_DATA], ids=["native", "legacy-wrapped"])-def test_anthropic_messages_pt_replays_redacted_thinking_as_claude_native_data(data: str):+def test_anthropic_messages_pt_replays_redacted_thinking_as_claude_native_data(data: str, placement: str):"""Histories saved from Converse before its replies were decoded hold the data base64-wrapped, and the- Anthropic API, Vertex and Bedrock Invoke 400 on it with "Invalid `data` in `redacted_thinking` block"."""+ Anthropic API, Vertex and Bedrock Invoke 400 on it with "Invalid `data` in `redacted_thinking` block".+ A redacted block in the content list, the shape the Anthropic SDK replays, used to be dropped."""+ signed: Final = {"type": "thinking", "thinking": "Let me look this up.", "signature": "sig-abc"}+ redacted: Final = {"type": "redacted_thinking", "data": data}+ messages: Final = [+ {"role": "user", "content": "hi"},+ _assistant_with_reasoning(placement, [signed, redacted], "hello"),+ {"role": "user", "content": "again"},+ ]++ result: Final = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")++ assert result[1] == {+ "role": "assistant",+ "content": [+ signed,+ {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA},+ {"type": "text", "text": "hello"},+ ],+ }+++@SPLIT_REASONING+def test_anthropic_messages_pt_keeps_reasoning_order_across_content_and_thinking_blocks(+ in_content: Sequence[int], in_thinking_blocks: Sequence[int]+):+ """A thinking block only one of content and thinking_blocks carries goes back in its original place."""+ reasoning: Final = (+ {"type": "thinking", "thinking": "First.", "signature": "sig-1"},+ {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA},+ {"type": "thinking", "thinking": "Third.", "signature": "sig-3"},+ )+ messages: Final = [+ {"role": "user", "content": "hi"},+ _assistant_with_split_reasoning(reasoning, in_content, in_thinking_blocks, "hello"),+ {"role": "user", "content": "again"},+ ]++ result: Final = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")++ assert result[1] == {"role": "assistant", "content": [*reasoning, {"type": "text", "text": "hello"}]}+++@COPY_TEXT+def test_anthropic_messages_pt_sends_a_signed_block_once_when_thinking_blocks_holds_other_text(copy_text: str):+ signed: Final = {"type": "thinking", "thinking": "First.", "signature": "sig-1"}+ redacted: Final = {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA}messages: Final = [{"role": "user", "content": "hi"},{"role": "assistant",- "content": "hello",- "thinking_blocks": [{"type": "redacted_thinking", "data": data, "cache_control": {"type": "ephemeral"}}],+ "content": [signed, redacted, {"type": "text", "text": "hello"}],+ "thinking_blocks": [{**signed, "thinking": copy_text}, redacted],},{"role": "user", "content": "again"},]result: Final = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")+ assert result[1] == {"role": "assistant", "content": [signed, redacted, {"type": "text", "text": "hello"}]}++++def test_anthropic_messages_pt_sends_a_block_once_when_two_assistant_messages_carry_it():+ signed: Final = {"type": "thinking", "thinking": "Let me look this up.", "signature": "sig-abc"}+ redacted: Final = {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA}++ result: Final = anthropic_messages_pt(+ messages=_block_split_across_assistant_messages([signed, redacted]),+ model="claude-sonnet-4-6",+ llm_provider="anthropic",+ )+assert result[1] == {"role": "assistant","content": [- {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA, "cache_control": {"type": "ephemeral"}},- {"type": "text", "text": "hello"},+ signed,+ redacted,+ {"type": "tool_use", "id": "tooluse_weather_1", "name": "get_weather", "input": {"city": "Paris"}},],}+@REASONING_PLACEMENTS[email protected]("drop_params", [False, True])+def test_anthropic_messages_pt_drops_cache_control_from_thinking_blocks_only_under_drop_params(+ placement: str, drop_params: bool+):+ """Claude 400s "thinking.cache_control: Extra inputs are not permitted" on a thinking or redacted_thinking+ block, so drop_params drops the breakpoint and without it the request reaches Claude as sent. The streamed+ list-position `index` is LiteLLM's own field and never reaches Claude."""+ breakpoint_mark: Final = {"cache_control": {"type": "ephemeral"}}+ signed: Final = {"type": "thinking", "thinking": "Let me look this up.", "signature": "sig-abc"}+ redacted: Final = {"type": "redacted_thinking", "data": _NATIVE_REDACTED_DATA}+ messages: Final = [+ {"role": "user", "content": "hi"},+ _assistant_with_reasoning(+ placement, [{**signed, **breakpoint_mark, "index": 0}, {**redacted, **breakpoint_mark, "index": 1}], "hello"+ ),+ {"role": "user", "content": "again"},+ ]++ result: Final = anthropic_messages_pt(+ messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic", drop_params=drop_params+ )++ sent_reasoning: Final = (+ [signed, redacted] if drop_params else [{**signed, **breakpoint_mark}, {**redacted, **breakpoint_mark}]+ )+ assert result[1] == {"role": "assistant", "content": [*sent_reasoning, {"type": "text", "text": "hello"}]}+++@REASONING_PLACEMENTS[email protected]("drop_params", [False, True])[email protected]("data", ["", " ", None], ids=["empty", "whitespace", "null"])+def test_anthropic_messages_pt_drops_a_blank_redacted_thinking_block_only_under_drop_params(+ data: str | None, placement: str, drop_params: bool+):+ """Claude 400s "Invalid `data` in `redacted_thinking` block" on blank data, so drop_params drops the block+ and without it the request reaches Claude as sent."""+ blank: Final = {"type": "redacted_thinking", "data": data}+ messages: Final = [+ {"role": "user", "content": "hi"},+ _assistant_with_reasoning(placement, [blank], "hello"),+ {"role": "user", "content": "again"},+ ]++ result: Final = anthropic_messages_pt(+ messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic", drop_params=drop_params+ )++ sent_reasoning: Final = [] if drop_params else [blank]+ assert result[1] == {"role": "assistant", "content": [*sent_reasoning, {"type": "text", "text": "hello"}]}+def test_anthropic_messages_pt_keeps_signed_thinking_block():"""A genuine Anthropic round-trip still holds its original signature, so thatdiff --git a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_mid_conversation_system.py b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_mid_conversation_system.pyindex 91d7acd331e..aab57b87a90 100644--- a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_mid_conversation_system.py+++ b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_mid_conversation_system.py@@ -308,16 +308,8 @@ EMPTY_ASSISTANT = pytest.mark.parametrize("content": None,"thinking_blocks": [{"type": "redacted_thinking", "data": encrypted_reasoning_signature("abc")}],},- {- "role": "assistant",- "content": [{"type": "thinking", "thinking": "unsigned"}],- "thinking_blocks": [{"type": "thinking", "thinking": "hm", "signature": "s"}],- },- {- "role": "assistant",- "content": [{"type": "redacted_thinking", "data": "x"}],- "thinking_blocks": [{"type": "redacted_thinking", "data": "x"}],- },+ {"role": "assistant", "content": [{"type": "redacted_thinking", "data": ""}]},+ {"role": "assistant", "content": None, "thinking_blocks": [{"type": "redacted_thinking", "data": " "}]},litellm.Message(role="assistant", content=None),{"role": "assistant", "content": None, "tool_calls": [_TOOL_SEARCH_USE]},],@@ -327,8 +319,8 @@ EMPTY_ASSISTANT = pytest.mark.parametrize("unsigned-thinking-part","encrypted-thinking-part","encrypted-redacted-thinking-block",- "unsigned-inline-part-hides-signed-block",- "inline-redacted-part-hides-redacted-block",+ "blank-data-redacted-part",+ "blank-data-redacted-block","pydantic-none","unanswered-tool-search-use",],@@ -464,6 +456,16 @@ def test_flagged_placement_keeps_a_system_whose_empty_assistant_follower_ends_th"thinking_blocks": [{"type": "thinking", "thinking": "hm", "signature": "s"}],},{"role": "assistant", "content": None, "thinking_blocks": [{"type": "redacted_thinking", "data": "x"}]},+ {+ "role": "assistant",+ "content": [{"type": "redacted_thinking", "data": "x"}],+ "thinking_blocks": [{"type": "redacted_thinking", "data": "x"}],+ },+ {+ "role": "assistant",+ "content": [{"type": "thinking", "thinking": "unsigned"}],+ "thinking_blocks": [{"type": "thinking", "thinking": "hm", "signature": "s"}],+ },{"role": "assistant", "content": [{"type": "thinking", "thinking": "hm", "signature": "s"}]},{"role": "assistant", "content": [{"type": "thinking", "thinking": "", "signature": "s"}]},{"role": "assistant", "content": None, "function_call": {"name": "f", "arguments": "{}"}},@@ -485,6 +487,8 @@ def test_flagged_placement_keeps_a_system_whose_empty_assistant_follower_ends_th"tool-calls","signed-thinking-block","redacted-thinking-block",+ "redacted-part-beside-the-same-redacted-block",+ "signed-block-beside-an-unsigned-part","signed-thinking-part","signed-empty-thinking-part","function-call",