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(responses): propagate cache_control through responses->chat completion bridge (#32511)
Tobias Mayrd03923e6a9d6
diff --git a/litellm/integrations/anthropic_cache_control_hook.py b/litellm/integrations/anthropic_cache_control_hook.pyindex ed7593c4961..126d84a0e10 100644--- a/litellm/integrations/anthropic_cache_control_hook.py+++ b/litellm/integrations/anthropic_cache_control_hook.py@@ -799,12 +799,16 @@ class AnthropicCacheControlHook(CustomPromptManagement):The hook sees neither the tools nor the request kwargs, so the target dialectand the client's breakpoint count outside the message list ride on the points.- Builds copies because config-owned point dicts are shared across requests.+ A zero count replaces an earlier layer's stamp (the chat bridge runs behind the+ Responses layer, whose outside marks sit in the bridge's own message list) and is+ otherwise left off. Builds copies because config-owned point dicts are shared+ across requests."""with_dialect: Final = AnthropicCacheControlHook._stamped_with_dialect(points, model, custom_llm_provider, api_base, prompt_cache_options)- if external_breakpoints == 0:+ stamped_earlier: Final = any(EXTERNAL_BREAKPOINTS_STAMP in point for point in with_dialect)+ if external_breakpoints == 0 and not stamped_earlier:return with_dialectreturn AnthropicCacheControlHook._stamped(with_dialect, EXTERNAL_BREAKPOINTS_STAMP, external_breakpoints)diff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.pyindex 9722f9dccb2..678913ad261 100644--- a/litellm/llms/bedrock/common_utils.py+++ b/litellm/llms/bedrock/common_utils.py@@ -1191,8 +1191,10 @@ def bedrock_model_accepts_cache_points(model: str | None) -> bool:never silently degrade. ``litellm.utils.supports_prompt_caching`` is not reusable here:it returns False for unmapped models, the opposite polarity."""- if model is None:- return True+ return model is None or bedrock_declared_cache_point_support(model) is not False+++def bedrock_declared_cache_point_support(model: str) -> bool | None:if _OPENAI_FAMILY_MODEL_RE.search(model):return Falsemap_keys: Final = (model, get_bedrock_base_model(model))@@ -1209,7 +1211,7 @@ def bedrock_model_accepts_cache_points(model: str | None) -> bool:if explicit_marker_support is not None:return explicit_marker_supportif not any(key in litellm.model_cost for key in map_keys):- return True+ return Nonereturn any(entry.get("supports_prompt_caching") is Truefor key in map_keysdiff --git a/litellm/llms/openrouter/chat/transformation.py b/litellm/llms/openrouter/chat/transformation.pyindex 9aef15f15a3..9aaf552e79a 100644--- a/litellm/llms/openrouter/chat/transformation.py+++ b/litellm/llms/openrouter/chat/transformation.py@@ -40,6 +40,11 @@ class CacheControlSupportedModels(str, Enum):ZAI = "z-ai"+def openrouter_model_supports_cache_control(model: str) -> bool:+ model_lower: Final = model.lower()+ return any(supported_model.value in model_lower for supported_model in CacheControlSupportedModels)++class OpenrouterConfig(OpenAIGPTConfig):def get_supported_openai_params(self, model: str) -> list:"""@@ -82,8 +87,7 @@ class OpenrouterConfig(OpenAIGPTConfig):Returns:bool: True if model supports cache_control (Claude or Gemini models)"""- model_lower: Final = model.lower()- return any(supported_model.value in model_lower for supported_model in CacheControlSupportedModels)+ return openrouter_model_supports_cache_control(model)def remove_cache_control_flag_from_messages_and_tools(self,diff --git a/litellm/llms/snowflake/chat/transformation.py b/litellm/llms/snowflake/chat/transformation.pyindex a6c060732c5..bf2a7d7da15 100644--- a/litellm/llms/snowflake/chat/transformation.py+++ b/litellm/llms/snowflake/chat/transformation.py@@ -96,7 +96,7 @@ def _decoded_messages(response: _MessagesResponse) -> _AnthropicMessagesResponsereturn response.json()-def _is_claude_model(model: str) -> bool:+def is_snowflake_claude_model(model: str) -> bool:"""Return True if model name (after stripping snowflake/ prefix) is a Claude model."""name: Final = model.lower().removeprefix("snowflake/")return any(name.startswith(p) for p in _CLAUDE_MODEL_PREFIXES)@@ -222,7 +222,7 @@ class SnowflakeConfig(SnowflakeBaseConfig, OpenAIGPTConfig):"tools","tool_choice",]- if _is_claude_model(model):+ if is_snowflake_claude_model(model):params.append("thinking")return params@@ -236,7 +236,7 @@ class SnowflakeConfig(SnowflakeBaseConfig, OpenAIGPTConfig):stream: bool | None = None,) -> str:api_base = self._get_api_base(api_base, optional_params)- if _is_claude_model(model):+ if is_snowflake_claude_model(model):return f"{api_base}/cortex/v1/messages"return f"{api_base}/cortex/v1/chat/completions"@@ -259,7 +259,7 @@ class SnowflakeConfig(SnowflakeBaseConfig, OpenAIGPTConfig):api_key=api_key,api_base=api_base,)- if _is_claude_model(model):+ if is_snowflake_claude_model(model):headers["anthropic-version"] = ANTHROPIC_VERSIONreturn headers@@ -406,7 +406,7 @@ class SnowflakeConfig(SnowflakeBaseConfig, OpenAIGPTConfig):stream: Final[bool] = optional_params.pop("stream", False) or Falseextra_body: Final = optional_params.pop("extra_body", {})- if _is_claude_model(model):+ if is_snowflake_claude_model(model):return self._transform_request_anthropic(model, messages, optional_params, stream, extra_body)return self._transform_request_openai(model, messages, optional_params, stream, extra_body)@@ -422,7 +422,9 @@ class SnowflakeConfig(SnowflakeBaseConfig, OpenAIGPTConfig):litellm_params: dict[str, object], # mutable-ok: BaseConfig signatureheaders: dict[str, object], # mutable-ok: BaseConfig signature) -> dict[str, object]: # mutable-ok: BaseConfig signature- inlined_messages: Final = await async_inline_remote_media(messages) if _is_claude_model(model) else messages+ inlined_messages: Final = (+ await async_inline_remote_media(messages) if is_snowflake_claude_model(model) else messages+ )return self.transform_request(model, inlined_messages, optional_params, litellm_params, headers)def _transform_request_openai(@@ -529,7 +531,7 @@ class SnowflakeConfig(SnowflakeBaseConfig, OpenAIGPTConfig):api_key: str | None = None,json_mode: bool | None = None,) -> ModelResponse:- if _is_claude_model(model):+ if is_snowflake_claude_model(model):return self._transform_response_anthropic(model, raw_response, model_response, logging_obj, request_data, messages)diff --git a/litellm/responses/litellm_completion_transformation/handler.py b/litellm/responses/litellm_completion_transformation/handler.pyindex 477d3a64339..0ab2052abb0 100644--- a/litellm/responses/litellm_completion_transformation/handler.py+++ b/litellm/responses/litellm_completion_transformation/handler.py@@ -5,6 +5,8 @@ Handler for transforming responses api requests to litellm.completion requestsfrom collections.abc import Coroutine, Mappingfrom typing import Final+from pydantic import TypeAdapter+import litellmfrom litellm.responses.additional_tools import hoist_additional_toolsfrom litellm.responses.litellm_completion_transformation.streaming_iterator import (@@ -21,6 +23,8 @@ from litellm.types.llms.openai import ()from litellm.types.utils import ModelResponse+_REQUEST_KWARGS_ADAPTER: Final = TypeAdapter(dict[str, object])+class LiteLLMCompletionTransformationHandler:def response_api_handler(@@ -107,6 +111,7 @@ class LiteLLMCompletionTransformationHandler:previous_response_id=previous_response_id,litellm_completion_request=litellm_completion_request,instructions=responses_api_request.get("instructions"),+ request_kwargs=_REQUEST_KWARGS_ADAPTER.validate_python(kwargs),)acompletion_args: Final = {}diff --git a/litellm/responses/litellm_completion_transformation/session_handler.py b/litellm/responses/litellm_completion_transformation/session_handler.pyindex 0d9e1a7dd38..732c32ff2cb 100644--- a/litellm/responses/litellm_completion_transformation/session_handler.py+++ b/litellm/responses/litellm_completion_transformation/session_handler.py@@ -51,6 +51,7 @@ class ResponsesSessionHandler:@staticmethodasync def get_chat_completion_message_history_for_previous_response_id(previous_response_id: str,+ item_cache_control: bool = False,) -> ChatCompletionSession:"""Return the chat completion message history for a previous response id@@ -86,6 +87,7 @@ class ResponsesSessionHandler:spend_log=spend_log,proxy_server_request_dict=proxy_server_request_dict,chat_completion_message_history=chat_completion_message_history,+ item_cache_control=item_cache_control,))@@ -117,6 +119,7 @@ class ResponsesSessionHandler:| ChatCompletionResponseMessage| Message],+ item_cache_control: bool = False,):"""Extend the chat completion message history with the spend log payload@@ -148,6 +151,7 @@ class ResponsesSessionHandler:input=response_input_param,responses_api_request={},replay_reasoning=True,+ item_cache_control=item_cache_control,))diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex c2cc876970c..d7235bd3ca8 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -5,8 +5,10 @@ Handles transforming from Responses API -> LiteLLM completion (Chat Completionimport jsonimport reimport uuid-from collections.abc import Iterable, Iterator, Mapping, Sequence+from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping, Sequencefrom dataclasses import dataclass+from functools import partial+from itertools import accumulate, chain, islicefrom types import MappingProxyTypefrom typing import (TYPE_CHECKING,@@ -15,6 +17,7 @@ from typing import (Literal,Protocol,TypeAlias,+ TypeVar,cast,runtime_checkable,)@@ -33,9 +36,12 @@ from openai.types.responses.tool_param import FunctionToolParamfrom pydantic import TypeAdapter, ValidationErrorfrom typing_extensions import ReadOnly, TypedDict+import litellmfrom litellm._logging import verbose_loggerfrom litellm.caching import InMemoryCachefrom litellm.constants import REDACTED_BY_LITELLM, REDACTED_TOOL_CALL_ARGUMENTS_PLACEHOLDER+from litellm.integrations.anthropic_cache_control_hook import MAX_CACHE_CONTROL_BLOCKS, AnthropicCacheControlHook+from litellm.litellm_core_utils.core_helpers import normalize_drop_paramsfrom litellm.litellm_core_utils.get_supported_openai_params import (get_supported_openai_params,)@@ -45,6 +51,11 @@ from litellm.litellm_core_utils.hidden_params import (set_hidden_params,)from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.anthropic.common_utils import supports_anthropic_cache_control+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM+from litellm.llms.bedrock.common_utils import bedrock_declared_cache_point_support+from litellm.llms.openrouter.chat.transformation import openrouter_model_supports_cache_control+from litellm.llms.snowflake.chat.transformation import is_snowflake_claude_modelfrom litellm.responses.litellm_completion_transformation.session_handler import (ResponsesSessionHandler,)@@ -52,6 +63,7 @@ from litellm.types.llms.base import CachedTokensDetailsfrom litellm.types.llms.openai import (AllMessageValues,ChatCompletionAssistantMessage,+ ChatCompletionCachedContent,ChatCompletionImageObject,ChatCompletionImageUrlObject,ChatCompletionRedactedThinkingBlock,@@ -186,6 +198,7 @@ TOOL_CALLS_CACHE: Final = InMemoryCache()_ANY_KEY_DICT_ADAPTER: Final = TypeAdapter(dict[object, object])_STR_KEY_DICT_ADAPTER: Final = TypeAdapter(dict[str, object])_OBJECT_LIST_ADAPTER: Final = TypeAdapter(list[object])+_CACHED_CONTENT_ADAPTER: Final = TypeAdapter(ChatCompletionCachedContent)_DICT_ITEMS_LIST_ADAPTER: Final = TypeAdapter(list[dict[object, object]])_TEXT_ADAPTER: Final = TypeAdapter(str)_RESPONSES_API_TOOL_CHOICE_ADAPTER: Final = TypeAdapter(ToolChoice)@@ -213,6 +226,14 @@ class _ResponsesToolCallItem(Protocol):def get(self, key: str, /) -> object: ...+class _MarkedToolCallChunk(ChatCompletionToolCallChunk):+ cache_control: ReadOnly[ChatCompletionCachedContent]+++class _MarkedToolMessage(ChatCompletionToolMessage):+ cache_control: ReadOnly[ChatCompletionCachedContent]++class _ToolFunctionDefinition(TypedDict, total=False):name: ReadOnly[str]description: ReadOnly[str]@@ -230,6 +251,258 @@ def _input_item_role(input_item: Mapping[str, object]) -> str:return cast(str, input_item.get("role") or "user") # cast-ok: client-supplied role forwarded verbatim, unvalidated+def _input_item_cache_control(input_item: Mapping[str, object]) -> ChatCompletionCachedContent | None:+ cache_control: Final = input_item.get("cache_control")+ if not cache_control:+ return None+ return cast( # cast-ok: forwarded as the client sent it, like a message mark on chat completions+ ChatCompletionCachedContent, cache_control+ )+++def _validated_cache_control(value: object) -> ChatCompletionCachedContent | None:+ try:+ return _CACHED_CONTENT_ADAPTER.validate_python(value)+ except ValidationError:+ return None+++def _dropped_cache_control(_: object) -> None:+ return None+++def drops_unsupported_params(drop_params: object) -> bool:+ return litellm.drop_params is True or normalize_drop_params(drop_params) is True+++def _without_cache_control_key(item: object) -> object:+ if not isinstance(item, dict):+ return item+ return {key: value for key, value in _STR_KEY_DICT_ADAPTER.validate_python(item).items() if key != "cache_control"}+++def without_item_cache_control(input: str | ResponseInputParam) -> str | ResponseInputParam:+ if not isinstance(input, list):+ return input+ return cast( # cast-ok: the same input items, each minus its own cache_control key+ ResponseInputParam, [_without_cache_control_key(item) for item in input]+ )+++_PROVIDERS_KEEPING_MESSAGE_CACHE_CONTROL: Final = frozenset(("anthropic", "dashscope", "minimax", "sap", "zai"))+++def _bedrock_target_keeps_item_marks(model: str, drop_params: bool) -> bool:+ declared: Final = bedrock_declared_cache_point_support(model)+ return declared is True or (declared is None and not drop_params)+++def _target_keeps_item_marks(model: str, custom_llm_provider: str | None, drop_params: bool) -> bool:+ if supports_anthropic_cache_control(model, custom_llm_provider):+ return True+ if custom_llm_provider in _PROVIDERS_KEEPING_MESSAGE_CACHE_CONTROL:+ return True+ if custom_llm_provider == "openrouter":+ return openrouter_model_supports_cache_control(model)+ if custom_llm_provider == "snowflake":+ return is_snowflake_claude_model(model)+ if custom_llm_provider == "databricks":+ return "claude" in model.lower()+ return custom_llm_provider == "bedrock" and _bedrock_target_keeps_item_marks(model, drop_params)+++def _refuses_marks_on_tool_blocks(model: str, custom_llm_provider: str | None) -> bool:+ return custom_llm_provider == "bedrock" and BaseAWSLLM.get_bedrock_invoke_provider(model) == "nova"+++def _with_cache_control_on_last_block(+ blocks: Sequence[object], cache_control: ChatCompletionCachedContent | None+) -> Sequence[object]:+ if cache_control is None or not blocks or not isinstance(blocks[-1], dict):+ return blocks+ last_block: Final = _STR_KEY_DICT_ADAPTER.validate_python(blocks[-1])+ if last_block.get("cache_control") is not None:+ return blocks+ return [*blocks[:-1], {**last_block, "cache_control": cache_control}]+++def _content_blocks_carrying(content: object, cache_control: ChatCompletionCachedContent | None) -> Sequence[object]:+ if isinstance(content, str):+ return (+ ChatCompletionTextObject(type="text", text=content)+ if cache_control is None+ else ChatCompletionTextObject(type="text", text=content, cache_control=cache_control),+ )+ return _with_cache_control_on_last_block(_OBJECT_LIST_ADAPTER.validate_python(content), cache_control)+++_MARK_CARRYING_MESSAGE_FIELDS: Final = ("content", "tool_calls")+++def _mark_carrying_blocks(fields: Mapping[str, object]) -> Sequence[object]:+ lists: Final = tuple(fields.get(key) for key in _MARK_CARRYING_MESSAGE_FIELDS)+ return tuple(+ chain.from_iterable(_OBJECT_LIST_ADAPTER.validate_python(value) for value in lists if isinstance(value, list))+ )+++def _block_carries_cache_control(block: object) -> bool:+ return isinstance(block, dict) and _STR_KEY_DICT_ADAPTER.validate_python(block).get("cache_control") is not None+++def _cache_control_count(message: object) -> int:+ if not isinstance(message, dict):+ return 0+ fields: Final = _STR_KEY_DICT_ADAPTER.validate_python(message)+ block_marks: Final = sum(1 for block in _mark_carrying_blocks(fields) if _block_carries_cache_control(block))+ return int(fields.get("cache_control") is not None) + block_marks+++_CacheControlRewrite: TypeAlias = Callable[[object], ChatCompletionCachedContent | None]+++def _fields_with_cache_control(fields: Mapping[str, object], rewrite: _CacheControlRewrite) -> Mapping[str, object]:+ others: Final = {key: value for key, value in fields.items() if key != "cache_control"}+ if "cache_control" not in fields:+ return others+ cache_control: Final = rewrite(fields["cache_control"])+ return others if cache_control is None else {**others, "cache_control": cache_control}+++def _block_with_cache_control(block: object, rewrite: _CacheControlRewrite) -> object:+ if not isinstance(block, dict):+ return block+ return _fields_with_cache_control(_STR_KEY_DICT_ADAPTER.validate_python(block), rewrite)+++_MessageT = TypeVar("_MessageT")+++def _with_cache_control(message: _MessageT, rewrite: _CacheControlRewrite) -> _MessageT:+ if not isinstance(message, dict):+ return message+ fields: Final = _STR_KEY_DICT_ADAPTER.validate_python(message)+ blocks_rewritten: Final = {+ key: (+ [_block_with_cache_control(block, rewrite) for block in _OBJECT_LIST_ADAPTER.validate_python(value)]+ if key in _MARK_CARRYING_MESSAGE_FIELDS and isinstance(value, list)+ else value+ )+ for key, value in fields.items()+ }+ return cast( # cast-ok: the same message shape with each cache marker rewritten or dropped+ _MessageT, _fields_with_cache_control(blocks_rewritten, rewrite)+ )+++def _kept_within_budget(state: tuple[int, bool], marks: int) -> tuple[int, bool]:+ remaining, _ = state+ if marks > remaining:+ return remaining, False+ return remaining - marks, True+++def _messages_within_cache_control_limit(messages: Sequence[_MessageT], reserved_marks: int) -> Sequence[_MessageT]:+ budget: Final = max(MAX_CACHE_CONTROL_BLOCKS - reserved_marks, 0)+ newest_first: Final = tuple(reversed(messages))+ budget_after_each: Final = accumulate(+ (_cache_control_count(message) for message in newest_first), _kept_within_budget, initial=(budget, True)+ )+ kept_flags: Final = tuple(kept for _, kept in islice(budget_after_each, 1, None))+ kept_newest_first: Final = tuple(+ message if kept else _with_cache_control(message, _dropped_cache_control)+ for message, kept in zip(newest_first, kept_flags)+ )+ return tuple(reversed(kept_newest_first))+++_SYSTEM_MESSAGE_FIELDS: Final = frozenset(("content", "cache_control"))+++def _marked_developer_message_fields(message: object) -> Mapping[str, object] | None:+ if not isinstance(message, dict):+ return None+ fields: Final = _STR_KEY_DICT_ADAPTER.validate_python(message)+ return fields if fields.get("role") == "developer" and "cache_control" in fields else None+++def _developer_message_as_system_message(message: _MessageT) -> _MessageT:+ fields: Final = _marked_developer_message_fields(message)+ if fields is None:+ return message+ return cast( # cast-ok: the system message the chat route maps a developer message to, mark included+ _MessageT, {"role": "system", **{key: value for key, value in fields.items() if key in _SYSTEM_MESSAGE_FIELDS}}+ )+++def _message_fields(message: object) -> Mapping[str, object] | None:+ return _STR_KEY_DICT_ADAPTER.validate_python(message) if isinstance(message, dict) else None+++def _without_tool_block_marks(message: _MessageT) -> _MessageT:+ fields: Final = _message_fields(message)+ if fields is None:+ return message+ if fields.get("role") == "tool":+ return _with_cache_control(message, _dropped_cache_control)+ tool_calls: Final = fields.get("tool_calls")+ if not isinstance(tool_calls, list):+ return message+ return cast( # cast-ok: the same assistant message with its tool calls unmarked+ _MessageT,+ {+ **fields,+ "tool_calls": [+ _block_with_cache_control(tool_call, _dropped_cache_control)+ for tool_call in _OBJECT_LIST_ADAPTER.validate_python(tool_calls)+ ],+ },+ )+++@dataclass(frozen=True, slots=True)+class _ItemMarkRules:+ drop_params: bool+ refuses_tool_block_marks: bool+ external_marks: int++ def sanitized(self, message: _MessageT) -> _MessageT:+ valid: Final = _with_cache_control(message, _validated_cache_control)+ return _without_tool_block_marks(valid) if self.refuses_tool_block_marks else valid++ def checked(self, message: _MessageT) -> _MessageT:+ return self.sanitized(message) if self.drop_params else message+++def _item_mark_rules(+ model: str, custom_llm_provider: str | None, tools: Iterable[object], request_kwargs: Mapping[str, object]+) -> _ItemMarkRules:+ return _ItemMarkRules(+ drop_params=drops_unsupported_params(request_kwargs.get("drop_params")),+ refuses_tool_block_marks=_refuses_marks_on_tool_blocks(model, custom_llm_provider),+ external_marks=AnthropicCacheControlHook.count_external_cache_breakpoints(+ tools, request_kwargs.get("cache_control"), request_kwargs+ ),+ )+++def _request_messages_for_cache_points(messages: Sequence[_MessageT], rules: _ItemMarkRules) -> Sequence[_MessageT]:+ as_system: Final = tuple(_developer_message_as_system_message(message) for message in messages)+ if not rules.drop_params:+ return as_system+ return _messages_within_cache_control_limit(tuple(map(rules.checked, as_system)), rules.external_marks)+++def _replayed_messages_for_cache_points(+ replayed_messages: Sequence[_MessageT], current_messages: Sequence[object], rules: _ItemMarkRules+) -> Sequence[_MessageT]:+ as_system: Final = tuple(_developer_message_as_system_message(message) for message in replayed_messages)+ current_marks: Final = sum(_cache_control_count(message) for message in current_messages)+ return _messages_within_cache_control_limit(+ tuple(map(rules.sanitized, as_system)), current_marks + rules.external_marks+ )++class ChatCompletionSession(TypedDict, total=False):messages: list[AllMessageValues@@ -482,11 +755,27 @@ class LiteLLMCompletionResponsesConfig:api_base=kwargs.get("api_base"),)+ request_kwargs: Final = _STR_KEY_DICT_ADAPTER.validate_python(kwargs)+ keeps_item_marks: Final = _target_keeps_item_marks(+ model, custom_llm_provider, drops_unsupported_params(request_kwargs.get("drop_params"))+ )+ bridged_messages: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=input,+ responses_api_request=responses_api_request,+ replay_reasoning=True,+ item_cache_control=keeps_item_marks,+ )+litellm_completion_request: dict = {- "messages": LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(- input=input,- responses_api_request=responses_api_request,- replay_reasoning=True,+ "messages": (+ list(+ _request_messages_for_cache_points(+ bridged_messages,+ _item_mark_rules(model, custom_llm_provider, tools, request_kwargs),+ )+ )+ if keeps_item_marks+ else bridged_messages),"model": model,"tool_choice": LiteLLMCompletionResponsesConfig._transform_tool_choice(@@ -535,6 +824,7 @@ class LiteLLMCompletionResponsesConfig:input: str | ResponseInputParam,responses_api_request: ResponsesAPIOptionalRequestParams | dict,replay_reasoning: bool = False,+ item_cache_control: bool = False,) -> list[AllMessageValues| GenericChatCompletionMessage@@ -549,11 +839,13 @@ class LiteLLMCompletionResponsesConfig:sent to a model: prior-turn ``reasoning`` items are then rebuilt asassistant ``reasoning_content`` and signed ``thinking_blocks`` so theprovider gets its own chain-of-thought back instead of reading it as- visible text.+ visible text. ``item_cache_control`` belongs to the same callers, when+ the target keeps an input item's ``cache_control`` on the message.Callers that only inspect the messages (token counting, rate limiting,- guardrail scanning) leave it off, because they need every piece of text- in the request to stay readable as message ``content``.+ guardrail scanning) leave both off, because they need every piece of text+ in the request to stay readable as message ``content``, with no item mark+ a strict message schema could refuse."""messages: list[AllMessageValues@@ -571,7 +863,7 @@ class LiteLLMCompletionResponsesConfig:messages.extend(LiteLLMCompletionResponsesConfig._transform_response_input_param_to_chat_completion_message(- input=input,+ input=input if item_cache_control else without_item_cache_control(input),replay_reasoning=replay_reasoning,))@@ -583,19 +875,44 @@ class LiteLLMCompletionResponsesConfig:previous_response_id: str,litellm_completion_request: dict,instructions: str | None,+ session_lookup: Callable[[str], Awaitable[ChatCompletionSession]] | None = None,+ request_kwargs: Mapping[str, object] = MappingProxyType({}),) -> dict:"""Async hook to get the chain of previous input and output pairs and return a list of Chat Completion messages"""- chat_completion_session = ChatCompletionSession(messages=[], litellm_session_id=None)- if previous_response_id:- chat_completion_session = (- await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(- previous_response_id=previous_response_id,- )- )+ request_fields: Final = _STR_KEY_DICT_ADAPTER.validate_python(litellm_completion_request)+ requested_provider: Final = request_fields.get("custom_llm_provider")+ model: Final = str(request_fields.get("model") or "")+ provider: Final = requested_provider if isinstance(requested_provider, str) else None+ keeps_item_marks: Final = _target_keeps_item_marks(+ model, provider, drops_unsupported_params(request_kwargs.get("drop_params"))+ )+ lookup: Final = session_lookup or partial(+ ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id,+ item_cache_control=keeps_item_marks,+ )+ chat_completion_session: Final = (+ await lookup(previous_response_id)+ if previous_response_id+ else ChatCompletionSession(messages=[], litellm_session_id=None)+ )_messages: Final = litellm_completion_request.get("messages") or []- session_messages: Final = chat_completion_session.get("messages") or []+ replayed_messages: Final = chat_completion_session.get("messages") or []+ session_messages: Final = (+ _replayed_messages_for_cache_points(+ replayed_messages,+ _OBJECT_LIST_ADAPTER.validate_python(_messages),+ _item_mark_rules(+ model,+ provider,+ _OBJECT_LIST_ADAPTER.validate_python(request_fields.get("tools") or []),+ request_kwargs,+ ),+ )+ if keeps_item_marks+ else replayed_messages+ )instructions_end: Final = 1 if instructions else 0carried_instructions: Final = None if instructions else chat_completion_session.get("instructions")leading_system_messages: Final = (@@ -609,7 +926,7 @@ class LiteLLMCompletionResponsesConfig:# Store original _messages before combining for safety checkoriginal_new_messages: Final = _messages.copy() if _messages else []- combined_messages = leading_system_messages + session_messages + _messages[instructions_end:]+ combined_messages = [*leading_system_messages, *session_messages, *_messages[instructions_end:]]# Fix: Ensure tool_results have corresponding tool_calls in previous assistant message# Pass tools parameter to help reconstruct tool_calls if not in cache@@ -631,7 +948,7 @@ class LiteLLMCompletionResponsesConfig:elif session_messages:# If we had session messages but they got filtered out,# restore them- combined_messages = session_messages+ combined_messages = list(session_messages)else:# Both are empty - this likely means function_call_output had empty/invalid call_id# Provide a helpful error message@@ -955,22 +1272,23 @@ class LiteLLMCompletionResponsesConfig:if new_content is None:return Noneprevious_content: Final = last_message.get("content")+ previous_cache_control: Final = _input_item_cache_control(last_message)+ new_cache_control: Final = _input_item_cache_control(new_message)content: Final = (new_content- if not previous_content+ if not previous_content and isinstance(new_content, str)else [- block- for value in (previous_content, new_content)- for block in (- (ChatCompletionTextObject(type="text", text=value),)- if isinstance(value, str)- else _OBJECT_LIST_ADAPTER.validate_python(value)- )+ *(_content_blocks_carrying(previous_content, previous_cache_control) if previous_content else ()),+ *_content_blocks_carrying(new_content, new_cache_control),])+ message_cache_control: Final = (+ None if isinstance(content, list) else new_cache_control or previous_cache_control+ )merged: Final = {- **last_message,+ **{key: value for key, value in last_message.items() if key != "cache_control"},"content": content,+ **({} if message_cache_control is None else {"cache_control": message_cache_control}),}return cast( # cast-ok: preserves the assistant fields and content blocksChatCompletionAssistantMessage, merged@@ -1468,14 +1786,24 @@ class LiteLLMCompletionResponsesConfig:# Since guardrails skip None content anyway, we return empty list to exclude it from structured messagesif content is None:return []- return [- GenericChatCompletionMessage(- role=_input_item_role(input_item),- content=LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(- content- ),- )- ]+ return [LiteLLMCompletionResponsesConfig._transform_responses_api_message_item(input_item, content)]++ @staticmethod+ def _transform_responses_api_message_item(+ input_item: Mapping[str, object], content: object+ ) -> GenericChatCompletionMessage:+ role: Final = _input_item_role(input_item)+ content_value: Final = (+ LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(content)+ )+ cache_control: Final = _input_item_cache_control(input_item)+ if cache_control is None:+ return GenericChatCompletionMessage(role=role, content=content_value)+ if isinstance(content_value, str):+ return GenericChatCompletionMessage(role=role, content=content_value, cache_control=cache_control)+ return GenericChatCompletionMessage(+ role=role, content=list(_with_cache_control_on_last_block(content_value, cache_control))+ )@staticmethoddef _reasoning_text_from_content(input_item: Mapping[str, object]) -> str | None:@@ -1665,10 +1993,14 @@ class LiteLLMCompletionResponsesConfig:except Exception:return str(output)- tool_output_message: Final = ChatCompletionToolMessage(- role="tool",- content=_normalize_function_call_output_to_tool_content(tool_call_output.get("output")),- tool_call_id=str(call_id),+ tool_content: Final = _normalize_function_call_output_to_tool_content(tool_call_output.get("output"))+ output_cache_control: Final = _input_item_cache_control(tool_call_output)+ tool_output_message: Final = (+ ChatCompletionToolMessage(role="tool", content=tool_content, tool_call_id=str(call_id))+ if output_cache_control is None+ else _MarkedToolMessage(+ role="tool", content=tool_content, tool_call_id=str(call_id), cache_control=output_cache_control+ ))_tool_use_definition: Final = TOOL_CALLS_CACHE.get_cache(@@ -1750,24 +2082,26 @@ class LiteLLMCompletionResponsesConfig:raw_name: Final = function_call.get("name") or ""namespace: Final = function_call.get("namespace") or ""qualify: Final = bool(namespace) and function_call.get("type") != "custom_tool_call"- tool_call: Final = ChatCompletionToolCallChunk(- id=function_call.get("call_id") or function_call.get("id") or "",- type="function",- function=ChatCompletionToolCallFunctionChunk(- name=f"{namespace}__{raw_name}" if qualify else raw_name,- arguments=serialize_tool_call_arguments(raw_arguments),- ),- index=0,+ tool_call_id: Final = function_call.get("call_id") or function_call.get("id") or ""+ tool_call_function: Final = ChatCompletionToolCallFunctionChunk(+ name=f"{namespace}__{raw_name}" if qualify else raw_name,+ arguments=serialize_tool_call_arguments(raw_arguments),)-- # Create an assistant message with the tool call- chat_completion_response_message: Final = ChatCompletionResponseMessage(- tool_calls=[tool_call],- role="assistant",- content=None, # Function calls don't have content+ function_call_cache_control: Final = _input_item_cache_control(function_call)+ tool_call: Final = (+ ChatCompletionToolCallChunk(id=tool_call_id, type="function", function=tool_call_function, index=0)+ if function_call_cache_control is None+ else _MarkedToolCallChunk(+ id=tool_call_id,+ type="function",+ function=tool_call_function,+ index=0,+ cache_control=function_call_cache_control,+ ))- return [chat_completion_response_message]+ # Create an assistant message with the tool call+ return [ChatCompletionResponseMessage(tool_calls=[tool_call], role="assistant", content=None)]@staticmethoddef _resolve_file_id(item: Mapping[str, object]) -> object:diff --git a/litellm/responses/main.py b/litellm/responses/main.pyindex f6bd4bfba54..c90455e8e75 100644--- a/litellm/responses/main.py+++ b/litellm/responses/main.py@@ -10,7 +10,10 @@ from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn, Optional, TypeAimport httpxfrom pydantic import BaseModel, TypeAdapter, ValidationError-from typing_extensions import assert_never+from typing_extensions import (+ TypeIs, # noqa: TID251 # narrows a client input item before its mark is read+ assert_never,+)import litellmfrom litellm._logging import verbose_logger@@ -568,12 +571,54 @@ def _will_bridge_to_chat_completions()-def _stamp_injection_points_with_dialect(+def _is_a_client_input_item(+ item: object,+) -> TypeIs[Mapping[str, object]]: # guard-ok: bounds a client input item before its mark is read+ return isinstance(item, Mapping)+++_ITEM_TYPES_THE_BRIDGE_FORWARDS_MARKS_FROM: Final = frozenset(("function_call", "function_call_output"))+++def _item_carries_a_mark_outside_the_provisional_messages(item: object) -> bool:+ return (+ _is_a_client_input_item(item)+ and item.get("type") in _ITEM_TYPES_THE_BRIDGE_FORWARDS_MARKS_FROM+ and bool(item.get("cache_control"))+ )+++def _function_tool_carries_a_mark(tool: Mapping[str, object]) -> bool:+ return isinstance(tool, dict) and tool.get("type") == "function" and bool(tool.get("cache_control"))+++def _cache_control_marks_outside_the_provisional_messages(+ input: str | ResponseInputParam | None, tools: Iterable[Mapping[str, object]] | None+) -> int:+ """Client marks on the request parts the provisional message list leaves out.++ A ``function_call`` or ``function_call_output`` item has no role, so the hook's pass here+ never sees its mark, while the bridge forwards it onto the tool call or tool message it+ builds, where the provider counts it against the cap. A ``function`` tool's mark reaches+ the provider the same way, on the chat tool the bridge builds from it.+ """+ item_marks: Final = (+ 0+ if input is None or isinstance(input, str)+ else sum(1 for item in input if _item_carries_a_mark_outside_the_provisional_messages(item))+ )+ tool_marks: Final = sum(1 for tool in tools or () if _function_tool_carries_a_mark(tool))+ return item_marks + tool_marks+++def _stamp_injection_points_for_the_hook(kwargs: dict[str, object], # mutable-ok: the points are rewritten in the caller's own kwargs for the hook to readmodel: str,custom_llm_provider: str | None,+ input: str | ResponseInputParam | None,+ tools: Iterable[Mapping[str, object]] | None,) -> None:- """Carry the provider this layer resolved onto the points.+ """Carry onto the points the provider this layer resolved and the marks its pass cannot see.The hook reads ``custom_llm_provider`` from the request kwargs, which never hold the oneresolved here, and resolving the model name alone reads a Foundry deployment of an OpenAI@@ -582,8 +627,9 @@ def _stamp_injection_points_with_dialect(points: Final = configured_injection_points(kwargs.get("cache_control_injection_points"))if not points:return- kwargs["cache_control_injection_points"] = AnthropicCacheControlHook._stamped_with_dialect(+ kwargs["cache_control_injection_points"] = AnthropicCacheControlHook._stamped_for_prompt_hook(points,+ _cache_control_marks_outside_the_provisional_messages(input, tools),model,custom_llm_provider,kwargs.get("api_base") or kwargs.get("base_url"),@@ -704,7 +750,7 @@ async def aresponses(_api_base_kwarg(kwargs),),):- _stamp_injection_points_with_dialect(kwargs, model, custom_llm_provider)+ _stamp_injection_points_for_the_hook(kwargs, model, custom_llm_provider, input, tools)(model,merged_input,@@ -841,6 +887,7 @@ def _resolve_prompt_swapped_provider(def _apply_prompt_management_to_responses_call(input: str | ResponseInputParam,+ tools: Iterable[ToolParam] | None,model: str,custom_llm_provider: str | None,litellm_logging_obj: LiteLLMLoggingObj | None,@@ -875,7 +922,7 @@ def _apply_prompt_management_to_responses_call(_api_base_kwarg(kwargs),),):- _stamp_injection_points_with_dialect(kwargs, model, custom_llm_provider)+ _stamp_injection_points_for_the_hook(kwargs, model, custom_llm_provider, input, tools)(model,merged_input,@@ -1274,6 +1321,7 @@ def responses(input, model, custom_llm_provider, deployment_model_info = _apply_prompt_management_to_responses_call(input=input,+ tools=tools,model=model,custom_llm_provider=custom_llm_provider,litellm_logging_obj=litellm_logging_obj,diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.pyindex 26f65fee4fe..2fa567ffb46 100644--- a/litellm/types/llms/openai.py+++ b/litellm/types/llms/openai.py@@ -947,6 +947,7 @@ class ChatCompletionDeveloperMessage(OpenAIChatCompletionDeveloperMessage, totalclass GenericChatCompletionMessage(TypedDict, total=False):role: Required[str]content: Required[str | list]+ cache_control: ReadOnly[ChatCompletionCachedContent]ValidUserMessageContentTypes = [diff --git a/tests/integration/providers/_cache_control_marks_support.py b/tests/integration/providers/_cache_control_marks_support.pyindex 5194f7d7ca3..2f6071f9e45 100644--- a/tests/integration/providers/_cache_control_marks_support.py+++ b/tests/integration/providers/_cache_control_marks_support.py@@ -20,6 +20,7 @@ BEDROCK_CACHE_CHECKPOINT_CAP: Final = 4ANTHROPIC_MODEL: Final = "claude-opus-5-5"BEDROCK_MODEL: Final = "anthropic.claude-opus-5-5"+UNMAPPED_BEDROCK_ARN: Final = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/scripted"PROVIDER_KEY: Final = "synthetic-provider-key"SYSTEM: Final = "Use the provided tool results to answer the user."ASK: Final = "Look up the weather in London, Paris, and Tokyo."@@ -409,6 +410,23 @@ def bedrock_peer(request: Request) -> Reply:)+def _without_cache_points(value: JsonValue) -> JsonValue:+ if isinstance(value, dict):+ return {key: _without_cache_points(inner) for key, inner in value.items()}+ if isinstance(value, list):+ return [+ _without_cache_points(inner) for inner in value if not (isinstance(inner, dict) and "cachePoint" in inner)+ ]+ return value+++def sent_without_cache_points(requests: Sequence[Request], marker: str) -> list[JsonValue]:+ return [+ _without_cache_points(_JSON_OBJECT.validate_json(request.body.replace(marker.encode(), b"marker")))+ for request in requests+ ]++def gateway_injected(response_id: str) -> bool:rows: Final = eventually(lambda: read_rows(diff --git a/tests/integration/providers/test_cache_control_tool_call_marks_owned_proxy.py b/tests/integration/providers/test_cache_control_tool_call_marks_owned_proxy.pyindex bc0a6f31e74..27e1a819e06 100644--- a/tests/integration/providers/test_cache_control_tool_call_marks_owned_proxy.py+++ b/tests/integration/providers/test_cache_control_tool_call_marks_owned_proxy.py@@ -15,10 +15,9 @@ import psutilimport pytestfrom integration._support.client import Gateway, eventuallyfrom integration._support.database import read_rows-from integration._support.process import owned_proxy_process+from integration._support.process import graceful_stop_seconds, owned_proxy_processfrom integration._support.wire import Reply, Request, wire_serverfrom integration.providers._cache_control_marks_support import (- ASK_LABEL,CITIES,POINTS,SYSTEM_LABEL,@@ -40,6 +39,8 @@ from integration.providers._cache_control_marks_support import ()from pydantic import JsonValue+pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)+_STARTED_WORKER: Final = re.compile(r"Started server process \[(\d+)\]")_SURFACES: Final = ("chat", "chat-stream", "chat-unmarked", "messages", "responses")_MODEL: Final = "capped-claude"@@ -76,8 +77,6 @@ def _surface_request(surface: str, marker: str) -> tuple[str, dict[str, JsonValudef _expected_labels(item: _Sent) -> list[str]:- if item.surface == "responses":- return [SYSTEM_LABEL, ASK_LABEL]if item.surface == "chat-unmarked":return [SYSTEM_LABEL, final_label(item.marker)]return client_marked()@@ -148,7 +147,6 @@ def _single_spend_row(item: _Sent) -> None:assert len(rows) == 1, (item.surface, item.call_id)[email protected](240)async def test_capped_burst_rides_out_a_provider_outage_and_logs_every_request_once(gateway: Gateway, tmp_path: Path) -> None:@@ -183,7 +181,6 @@ async def test_capped_burst_rides_out_a_provider_outage_and_logs_every_request_o_single_spend_row(item)[email protected](240)async def test_worker_sigkill_mid_burst_leaves_the_sibling_serving_capped_requests(gateway: Gateway, tmp_path: Path) -> None:@@ -227,7 +224,6 @@ async def test_worker_sigkill_mid_burst_leaves_the_sibling_serving_capped_reques_single_spend_row(item)[email protected](240)def test_yaml_auto_caching_stands_down_for_tool_call_marks_and_outranks_a_key_opt_out(gateway: Gateway, tmp_path: Path) -> None:@@ -262,7 +258,7 @@ def test_yaml_auto_caching_stands_down_for_tool_call_marks_and_outranks_a_key_op][email protected](360)[email protected](4 * graceful_stop_seconds() + 120)async def test_proxy_restart_mid_burst_serves_capped_requests_after_the_reboot(gateway: Gateway, tmp_path: Path) -> None:diff --git a/tests/integration/providers/test_cache_control_tool_call_marks_wire.py b/tests/integration/providers/test_cache_control_tool_call_marks_wire.pyindex 21fee0554ea..8c698817ccf 100644--- a/tests/integration/providers/test_cache_control_tool_call_marks_wire.py+++ b/tests/integration/providers/test_cache_control_tool_call_marks_wire.py@@ -20,7 +20,7 @@ from integration._support.client import (string_value,)from integration._support.database import read_rows-from integration._support.process import owned_proxy+from integration._support.process import graceful_stop_seconds, owned_proxyfrom integration._support.wire import Reply, Request, Wire, wire_serverfrom integration.providers._cache_control_marks_support import (ANTHROPIC_MODEL,@@ -61,6 +61,7 @@ from pydantic import JsonValue, TypeAdapterfrom litellm.utils import get_prompt_cache_min_tokens+_OWNED_PROXY_TIMEOUT: Final = 2 * graceful_stop_seconds() + 120_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])_LANE_CONFIG: Final = Path(__file__).resolve().parents[1] / "proxy_config.yaml"_CLIENT_MARKED: Final = client_marked()@@ -505,17 +506,17 @@ def test_messages_endpoint_points_skip_injection_when_tool_use_marks_fill_the_caassert anthropic_labels(_only_request(wire)) == _CLIENT_MARKED-def test_responses_bridge_keeps_system_and_user_marks_within_the_cap(gateway: Gateway) -> None:+def test_responses_bridge_points_skip_injection_when_function_call_marks_fill_the_cap(gateway: Gateway) -> None:marker: Final = new_marker()with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:model: Final = _anthropic_deployment(scenario, wire, cache_control_injection_points=POINTS)response: Final = gateway.request("POST", "/v1/responses", responses_body(model, marker))assert response.status_code == 200, response.textassert _JSON_OBJECT.validate_json(response.content)["status"] == "completed", response.text- assert anthropic_labels(_only_request(wire)) == [SYSTEM_LABEL, ASK_LABEL]+ assert anthropic_labels(_only_request(wire)) == _CLIENT_MARKED[email protected](240)[email protected](_OWNED_PROXY_TIMEOUT)def test_response_cache_serves_the_capped_request_once(uncapped_gateway: Gateway) -> None:marker: Final = new_marker()with wire_server(anthropic_peer) as wire, uncapped_gateway.scenario() as scenario:@@ -567,14 +568,16 @@ def test_assistant_without_tool_calls_keeps_configured_points(gateway: Gateway,assert labels == [SYSTEM_LABEL, ASK_LABEL, final_label(marker)]-def test_responses_stream_bridge_keeps_system_and_user_marks_within_the_cap(gateway: Gateway) -> None:+def test_responses_stream_bridge_points_skip_injection_when_function_call_marks_fill_the_cap(+ gateway: Gateway,+) -> None:marker: Final = new_marker()with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:model: Final = _anthropic_deployment(scenario, wire, cache_control_injection_points=POINTS)status, text = _stream(gateway, "/v1/responses", {**responses_body(model, marker), "stream": True})assert status == 200, textassert '"type":"response.completed"' in text, text- assert anthropic_labels(_only_request(wire)) == [SYSTEM_LABEL, ASK_LABEL]+ assert anthropic_labels(_only_request(wire)) == _CLIENT_MARKEDdef _openai_client(gateway: Gateway) -> openai.OpenAI:@@ -698,7 +701,9 @@ async def test_anthropic_sdk_async_messages_stream_keeps_the_capped_request_withassert gateway_injected(f"msg_{marker}") is False-async def test_openai_sdk_async_responses_keeps_system_and_user_marks_within_the_cap(gateway: Gateway) -> None:+async def test_openai_sdk_async_responses_points_skip_injection_when_function_call_marks_fill_the_cap(+ gateway: Gateway,+) -> None:marker: Final = new_marker()with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:model: Final = _anthropic_deployment(scenario, wire, cache_control_injection_points=POINTS)@@ -712,7 +717,7 @@ async def test_openai_sdk_async_responses_keeps_system_and_user_marks_within_theinput=cast(ResponseInputParam, body["input"]),)assert response.status == "completed", response.model_dump()- assert anthropic_labels(_only_request(wire)) == [SYSTEM_LABEL, ASK_LABEL]+ assert anthropic_labels(_only_request(wire)) == _CLIENT_MARKEDdef test_request_level_points_skip_injection_when_client_marks_fill_the_cap(gateway: Gateway) -> None:@@ -859,7 +864,7 @@ def _cache_hit_rows(response_id: str) -> list[dict[str, JsonValue]]:)[email protected](240)[email protected](_OWNED_PROXY_TIMEOUT)def test_response_cache_hit_records_the_injection_on_the_first_row_only(uncapped_gateway: Gateway) -> None:marker: Final = new_marker()unmarked: Final = [tool_call(city) for city in CITIES]@@ -877,7 +882,7 @@ def test_response_cache_hit_records_the_injection_on_the_first_row_only(uncappedassert hit_rows[0]["injected"] is None, hit_rows[email protected](240)[email protected](_OWNED_PROXY_TIMEOUT)@pytest.mark.parametrize("path", ("/v1/messages", "/v1/responses"))def test_response_cache_twins_on_messages_and_responses_stay_within_the_cap(uncapped_gateway: Gateway, path: str@@ -891,8 +896,7 @@ def test_response_cache_twins_on_messages_and_responses_stay_within_the_cap(responses: Final = tuple(uncapped_gateway.request("POST", path, body) for _ in range(2))received: Final = wire.drain()assert [response.status_code for response in responses] == [200, 200], [response.text for response in responses]- expected: Final = _CLIENT_MARKED if path == "/v1/messages" else [SYSTEM_LABEL, ASK_LABEL]- assert [anthropic_labels(request) for request in received] == [expected] * len(received)+ assert [anthropic_labels(request) for request in received] == [_CLIENT_MARKED] * len(received)assert len(received) == 1, [request.target for request in received]diff --git a/tests/integration/providers/test_responses_bridge_item_marks_guardrail_wire.py b/tests/integration/providers/test_responses_bridge_item_marks_guardrail_wire.pynew file mode 100644index 00000000000..522ba8b1e81--- /dev/null+++ b/tests/integration/providers/test_responses_bridge_item_marks_guardrail_wire.py@@ -0,0 +1,229 @@+import json+from collections.abc import Iterator, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Final++import pytest+import yaml+from integration._support.client import Gateway, gateway_from_environment, object_value+from integration._support.process import graceful_stop_seconds, owned_proxy+from integration._support.wire import Reply, Request, Wire, wire_server+from integration.providers._cache_control_marks_support import (+ ASK,+ ASK_LABEL,+ EPHEMERAL,+ SYSTEM,+ SYSTEM_LABEL,+ Mark,+ anthropic_deployment,+ anthropic_labels,+ anthropic_marks,+ anthropic_peer,+ final_text,+ new_marker,+)+from pydantic import JsonValue, TypeAdapter++pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)++_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_GUARDED: Final = "bridge-mark-guarded"+_MODES: Final = ("none", "texts", "rows")+_CITY: Final = "Tokyo"+_REDACTED_ASK: Final = ASK.replace(_CITY, "[CITY]")+_REDACTED_ASK_LABEL: Final = f"user:text:{_REDACTED_ASK}"+++@dataclass(frozen=True, slots=True)+class _GuardedRig:+ gateway: Gateway+ provider: Wire+ guardrail: Wire+++@dataclass(frozen=True, slots=True)+class _Exchange:+ guardrail: tuple[dict[str, JsonValue], ...]+ provider: tuple[Request, ...]+++def _redacted(value: JsonValue) -> JsonValue:+ return value.replace(_CITY, "[CITY]") if isinstance(value, str) else value+++def _redacted_part(part: JsonValue) -> JsonValue:+ if not isinstance(part, dict) or "text" not in part:+ return part+ return {**part, "text": _redacted(part["text"])}+++def _redacted_row(row: JsonValue) -> JsonValue:+ message: Final = object_value(row)+ content: Final = message.get("content")+ if isinstance(content, list):+ return {**message, "content": [_redacted_part(part) for part in content]}+ return {**message, "content": _redacted(content)}+++def _listed(value: JsonValue) -> list[JsonValue]:+ assert isinstance(value, list), value+ return value+++def _verdict(mode: str, payload: dict[str, JsonValue]) -> dict[str, JsonValue]:+ match mode:+ case "texts":+ return {"action": "GUARDRAIL_INTERVENED", "texts": [_redacted(text) for text in _listed(payload["texts"])]}+ case "rows":+ rows: Final = _listed(payload["structured_messages"])+ return {"action": "GUARDRAIL_INTERVENED", "structured_messages": [_redacted_row(row) for row in rows]}+ case _:+ return {"action": "NONE"}+++def _guardrail_peer(request: Request) -> Reply:+ mode: Final = request.target.split("/")[1]+ return Reply(body=json.dumps(_verdict(mode, _JSON_OBJECT.validate_json(request.body))).encode())+++def _guardrail(mode: str, api_base: str) -> dict[str, JsonValue]:+ return {+ "guardrail_name": f"bridge-mark-{mode}",+ "litellm_params": {+ "guardrail": "generic_guardrail_api",+ "mode": "pre_call",+ "default_on": False,+ "api_base": f"{api_base}/{mode}",+ "api_key": "synthetic-guardrail-key",+ },+ }+++def _guarded_config(directory: Path, provider_url: str, guardrail_url: str) -> Path:+ stock: Final = _JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))+ config: Final[dict[str, JsonValue]] = {+ **stock,+ "model_list": [anthropic_deployment(_GUARDED, provider_url)],+ "router_settings": {**object_value(stock["router_settings"]), "num_retries": 0},+ "guardrails": [_guardrail(mode, guardrail_url) for mode in _MODES],+ }+ path: Final = directory / "bridge-mark-guarded.yaml"+ path.write_text(yaml.safe_dump(config))+ return path++[email protected](scope="module")+def guarded(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_GuardedRig]:+ directory: Final = tmp_path_factory.mktemp("bridge-mark-guarded")+ with (+ wire_server(anthropic_peer) as provider,+ wire_server(_guardrail_peer) as guardrail,+ gateway_from_environment() as gateway,+ ):+ config: Final = _guarded_config(directory, provider.url, guardrail.url)+ with owned_proxy(gateway, directory, {}, config=config, workers=2) as owned:+ yield _GuardedRig(owned, provider, guardrail)+++def _items(marker: str, mark: JsonValue = EPHEMERAL) -> list[JsonValue]:+ return [+ {"role": "system", "content": SYSTEM, "cache_control": EPHEMERAL},+ {"role": "user", "content": ASK, "cache_control": mark},+ {"role": "user", "content": final_text(marker)},+ ]+++def _send(rig: _GuardedRig, mode: str, items: Sequence[JsonValue], *, stream: bool = False) -> str:+ body: Final[dict[str, JsonValue]] = {+ "model": _GUARDED,+ "max_output_tokens": 64,+ "input": list(items),+ "stream": stream,+ "guardrails": [f"bridge-mark-{mode}"],+ }+ headers: Final = {"Authorization": f"Bearer {rig.gateway.key}"}+ with rig.gateway.client.stream("POST", "/v1/responses", json=body, headers=headers) as response:+ text: Final = response.read().decode()+ assert response.status_code == 200, text+ assert "sunny" in text, text+ if stream:+ assert '"type":"response.completed"' in text, text+ else:+ assert _JSON_OBJECT.validate_json(text)["status"] == "completed", text+ return text+++def _exchange(rig: _GuardedRig, marker: str) -> _Exchange:+ needle: Final = marker.encode()+ return _Exchange(+ guardrail=tuple(+ _JSON_OBJECT.validate_json(request.body) for request in rig.guardrail.drain() if needle in request.body+ ),+ provider=tuple(request for request in rig.provider.drain() if needle in request.body),+ )+++def _assert_read_without_marks(payload: dict[str, JsonValue], marker: str) -> None:+ assert "cache_control" not in json.dumps(payload), payload+ assert ASK in _listed(payload["texts"]), payload["texts"]+ assert final_text(marker) in _listed(payload["texts"]), payload["texts"]+ rows: Final = [object_value(row) for row in _listed(payload["structured_messages"])]+ assert [row.get("content") for row in rows] == [SYSTEM, ASK, final_text(marker)], rows++[email protected]("stream", (False, True), ids=("json", "stream"))+def test_guardrail_reads_the_input_without_item_marks_while_the_provider_keeps_them(+ guarded: _GuardedRig, stream: bool+) -> None:+ marker: Final = new_marker()+ _send(guarded, "none", _items(marker), stream=stream)+ seen: Final = _exchange(guarded, marker)+ assert len(seen.guardrail) == 1, seen.guardrail+ _assert_read_without_marks(seen.guardrail[0], marker)+ assert [anthropic_labels(request) for request in seen.provider] == [[SYSTEM_LABEL, ASK_LABEL]]+++def test_guardrail_on_a_response_cache_hit_reads_the_input_without_item_marks(guarded: _GuardedRig) -> None:+ marker: Final = new_marker()+ items: Final = _items(marker)+ for _ in range(2):+ _send(guarded, "none", items)+ seen: Final = _exchange(guarded, marker)+ assert len(seen.guardrail) == 2, seen.guardrail+ for payload in seen.guardrail:+ _assert_read_without_marks(payload, marker)+ assert [anthropic_labels(request) for request in seen.provider] == [[SYSTEM_LABEL, ASK_LABEL]]+++def test_guardrail_text_rewrite_keeps_the_item_mark(guarded: _GuardedRig) -> None:+ marker: Final = new_marker()+ _send(guarded, "texts", _items(marker))+ seen: Final = _exchange(guarded, marker)+ assert len(seen.guardrail) == 1, seen.guardrail+ _assert_read_without_marks(seen.guardrail[0], marker)+ assert [anthropic_labels(request) for request in seen.provider] == [[SYSTEM_LABEL, _REDACTED_ASK_LABEL]]+++ "mark",+ (+ pytest.param(EPHEMERAL, id="ephemeral"),+ pytest.param({"type": "ephemeral", "ttl": "1h"}, id="ttl-1h"),+ pytest.param({"type": "ephemeral", "ttl": "30m"}, id="ttl-30m"),+ pytest.param({"type": "persistent"}, id="unknown-type"),+ ),+)+def test_guardrail_row_rewrite_keeps_the_item_mark_as_sent(guarded: _GuardedRig, mark: dict[str, JsonValue]) -> None:+ marker: Final = new_marker()+ items: Final[list[JsonValue]] = [+ {"role": "user", "content": ASK, "cache_control": mark},+ {"role": "user", "content": final_text(marker)},+ ]+ _send(guarded, "rows", items)+ seen: Final = _exchange(guarded, marker)+ assert len(seen.guardrail) == 1, seen.guardrail+ assert "cache_control" not in json.dumps(seen.guardrail[0]), seen.guardrail[0]+ ttl: Final = mark.get("ttl")+ expected: Final = (Mark(_REDACTED_ASK_LABEL, ttl if isinstance(ttl, str) else None),)+ assert [anthropic_marks(request) for request in seen.provider] == [expected]diff --git a/tests/integration/providers/test_responses_bridge_message_cache_control_wire.py b/tests/integration/providers/test_responses_bridge_message_cache_control_wire.pynew file mode 100644index 00000000000..ea55552c331--- /dev/null+++ b/tests/integration/providers/test_responses_bridge_message_cache_control_wire.py@@ -0,0 +1,1219 @@+import json+from collections.abc import Iterator, Sequence+from dataclasses import dataclass+from itertools import chain+from typing import Final, cast++import httpx+import openai+import pytest+from integration._support import bedrock_runtime_peer+from integration._support import prompt_cache_breakpoint as pcb+from integration._support.client import Gateway, Scenario, object_value+from integration._support.openai_wire import answering_model_discovery, chat_reply+from integration._support.vertex import service_account_json+from integration._support.wire import Reply, Request, Wire, wire_server+from integration.providers._cache_control_marks_support import (+ ANTHROPIC_MODEL,+ ASK,+ ASK_LABEL,+ BEDROCK_MODEL,+ CITIES,+ EPHEMERAL,+ POINTS,+ PROVIDER_KEY,+ SYSTEM,+ SYSTEM_LABEL,+ UNMAPPED_BEDROCK_ARN,+ anthropic_labels,+ anthropic_marks,+ anthropic_peer,+ bedrock_labels,+ bedrock_peer,+ call_id,+ client_marked,+ final_label,+ final_text,+ marker_of,+ new_marker,+ responses_body,+ sent_without_cache_points,+ tool_use_label,+)+from openai.types.responses import ResponseInputParam+from pydantic import JsonValue, TypeAdapter++from litellm.utils import get_prompt_cache_min_tokens++_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_HOUR: Final[dict[str, JsonValue]] = {"type": "ephemeral", "ttl": "1h"}+_CHECK: Final = "I will check."+_ASSISTANT_LABEL: Final = f"assistant:text:{_CHECK}"+_RESULT_LABEL: Final = f"user:tool_result:{call_id(CITIES[0])}"+_BEDROCK_SYSTEM_LABEL: Final = f"system:text:{SYSTEM}"+_BEDROCK_RESULT_LABEL: Final = f"user:toolResult:{call_id(CITIES[0])}"+_TOOL: Final[dict[str, JsonValue]] = {"type": "function", "name": "lookup_weather", "parameters": {"type": "object"}}+_GEMINI: Final = "gemini/gemini-3.8-flash"+_GEMINI_GENERATE_ONLY: Final = [("POST", "/models/gemini-3.8-flash:generateContent")]+_GEMINI_REPLY: Final = json.dumps(+ {+ "candidates": [{"content": {"role": "model", "parts": [{"text": "sunny"}]}, "finishReason": "STOP"}],+ "usageMetadata": {"promptTokenCount": 1600, "candidatesTokenCount": 1, "totalTokenCount": 1601},+ }+).encode()+_OPENAI_COMPATIBLE: Final = "openai/gpt-5.4"+++@dataclass(frozen=True, slots=True)+class _Answer:+ status: int+ text: str+ call_id: str++[email protected](scope="module")+def spend() -> Iterator[pcb.SpendLogs]:+ with pcb.spend_logs() as logs:+ yield logs+++def _item(role: str, text: str, mark: JsonValue = EPHEMERAL) -> dict[str, JsonValue]:+ return {"role": role, "content": text, "cache_control": mark}+++def _responses(model: str, items: Sequence[JsonValue], **fields: JsonValue) -> dict[str, JsonValue]:+ return {"model": model, "max_output_tokens": 64, "input": list(items), **fields}+++def _marked_system(model: str, marker: str, mark: JsonValue = EPHEMERAL, **fields: JsonValue) -> dict[str, JsonValue]:+ return _responses(model, [_item("system", SYSTEM, mark), {"role": "user", "content": final_text(marker)}], **fields)+++def _role_items(role: str, marker: str) -> list[JsonValue]:+ match role:+ case "system" | "developer":+ return [_item(role, SYSTEM), {"role": "user", "content": final_text(marker)}]+ case "user":+ return [_item("user", ASK), {"role": "user", "content": final_text(marker)}]+ case _:+ return [+ {"role": "user", "content": ASK},+ _item("assistant", _CHECK),+ {"role": "user", "content": final_text(marker)},+ ]+++def _tool_items(marker: str, *, output_mark: JsonValue = None, call_mark: JsonValue = None) -> list[JsonValue]:+ call: Final[dict[str, JsonValue]] = {+ "type": "function_call",+ "call_id": call_id(CITIES[0]),+ "name": "lookup_weather",+ "arguments": json.dumps({"city": CITIES[0]}),+ }+ output: Final[dict[str, JsonValue]] = {+ "type": "function_call_output",+ "call_id": call_id(CITIES[0]),+ "output": "sunny.",+ }+ return [+ {"role": "user", "content": ASK},+ {**call, "cache_control": call_mark} if call_mark is not None else call,+ {**output, "cache_control": output_mark} if output_mark is not None else output,+ {"role": "user", "content": final_text(marker)},+ ]+++def _call_id_of(response: httpx.Response) -> str:+ return response.headers["x-litellm-call-id"] if "x-litellm-call-id" in response.headers else ""+++def _send(gateway: Gateway, body: dict[str, JsonValue], *, key: str | None = None) -> _Answer:+ headers: Final = {"Authorization": f"Bearer {gateway.key if key is None else key}"}+ with gateway.client.stream("POST", "/v1/responses", json=body, headers=headers) as response:+ return _Answer(response.status_code, response.read().decode(), _call_id_of(response))+++def _send_raw(gateway: Gateway, raw: bytes) -> _Answer:+ headers: Final = {"Authorization": f"Bearer {gateway.key}", "Content-Type": "application/json"}+ response: Final = gateway.client.post("/v1/responses", content=raw, headers=headers)+ return _Answer(response.status_code, response.text, _call_id_of(response))+++def _assert_completed(answer: _Answer, *, stream: bool = False) -> None:+ assert answer.status == 200, answer.text+ assert "sunny" in answer.text, answer.text+ if stream:+ assert '"type":"response.completed"' in answer.text, answer.text+ return+ assert _JSON_OBJECT.validate_json(answer.text)["status"] == "completed", answer.text+++def _only_request(wire: Wire) -> Request:+ received: Final = wire.drain()+ assert len(received) == 1, [request.target for request in received]+ return received[0]+++def _anthropic_deployment(scenario: Scenario, wire: Wire, *, inject: bool = False) -> str:+ if inject:+ return scenario.model(+ model=f"anthropic/{ANTHROPIC_MODEL}",+ api_base=wire.url,+ api_key=PROVIDER_KEY,+ cache_control_injection_points=POINTS,+ )+ return scenario.model(model=f"anthropic/{ANTHROPIC_MODEL}", api_base=wire.url, api_key=PROVIDER_KEY)+++def _bedrock_peer(request: Request) -> Reply:+ if request.target.endswith("/converse-stream"):+ return bedrock_runtime_peer.respond(request)+ return bedrock_peer(request)+++def _bedrock_deployment(scenario: Scenario, wire: Wire, route: str = "converse") -> str:+ return scenario.model(+ model=f"bedrock/{route}/{BEDROCK_MODEL}",+ api_key=PROVIDER_KEY,+ api_base=wire.url,+ aws_region_name="us-east-1",+ aws_bedrock_runtime_endpoint=wire.url,+ )+++def _unmapped_arn_deployment(scenario: Scenario, wire: Wire, **fields: JsonValue) -> str:+ return scenario.model(+ model=f"bedrock/converse/{UNMAPPED_BEDROCK_ARN}",+ api_key=PROVIDER_KEY,+ api_base=wire.url,+ aws_region_name="us-east-1",+ aws_bedrock_runtime_endpoint=wire.url,+ **fields,+ )+++def _blocks_of(body: dict[str, JsonValue]) -> Iterator[JsonValue]:+ system: Final = body.get("system")+ yield from system if isinstance(system, list) else []+ messages: Final = body.get("messages")+ for message in messages if isinstance(messages, list) else []:+ yield from _content_blocks(object_value(message).get("content"))+++def _content_blocks(content: JsonValue) -> Iterator[JsonValue]:+ yield from content if isinstance(content, list) else []+++def _bedrock_ttls(request: Request) -> list[JsonValue]:+ blocks: Final = list(_blocks_of(_JSON_OBJECT.validate_json(request.body)))+ return [+ object_value(block["cachePoint"]).get("ttl")+ for block in blocks+ if isinstance(block, dict) and "cachePoint" in block+ ]++[email protected]("stream", (False, True), ids=("json", "stream"))+ ("role", "expected"),+ (+ pytest.param("system", SYSTEM_LABEL, id="system"),+ pytest.param("developer", SYSTEM_LABEL, id="developer"),+ pytest.param("user", ASK_LABEL, id="user"),+ pytest.param("assistant", _ASSISTANT_LABEL, id="assistant"),+ ),+)+def test_marked_item_reaches_anthropic_as_a_cache_point(+ gateway: Gateway, spend: pcb.SpendLogs, role: str, expected: str, stream: bool+) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ answer: Final = _send(gateway, _responses(model, _role_items(role, marker), stream=stream))+ _assert_completed(answer, stream=stream)+ assert anthropic_labels(_only_request(wire)) == [expected]+ spend.landed(model, answer.call_id, None)+++def test_list_content_message_mark_lands_on_the_last_block(gateway: Gateway) -> None:+ marker: Final = new_marker()+ content: Final[list[JsonValue]] = [{"type": "input_text", "text": "first"}, {"type": "input_text", "text": ASK}]+ items: Final[list[JsonValue]] = [+ {"role": "user", "content": content, "cache_control": EPHEMERAL},+ {"role": "user", "content": final_text(marker)},+ ]+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _responses(model, items)))+ assert anthropic_labels(_only_request(wire)) == [ASK_LABEL]+++def test_block_mark_outranks_the_message_mark(gateway: Gateway) -> None:+ marker: Final = new_marker()+ items: Final[list[JsonValue]] = [+ {+ "role": "user",+ "content": [{"type": "input_text", "text": ASK, "cache_control": _HOUR}],+ "cache_control": EPHEMERAL,+ },+ {"role": "user", "content": final_text(marker)},+ ]+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _responses(model, items)))+ marks: Final = anthropic_marks(_only_request(wire))+ assert [(mark.label, mark.ttl) for mark in marks] == [(ASK_LABEL, "1h")]+++def test_function_call_output_mark_reaches_anthropic_as_a_tool_result_mark(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ body: Final = _responses(model, _tool_items(marker, output_mark=EPHEMERAL), tools=[_TOOL])+ _assert_completed(_send(gateway, body))+ assert anthropic_labels(_only_request(wire)) == [_RESULT_LABEL]+++def test_function_call_marks_reach_anthropic_as_tool_use_marks(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, responses_body(model, marker)))+ assert anthropic_labels(_only_request(wire)) == client_marked()++[email protected]("stream", (False, True), ids=("json", "stream"))+ ("role", "expected"),+ (+ pytest.param("system", _BEDROCK_SYSTEM_LABEL, id="system"),+ pytest.param("user", f"user:text:{ASK}", id="user"),+ pytest.param("assistant", f"assistant:text:{_CHECK}", id="assistant"),+ ),+)+def test_marked_item_reaches_bedrock_converse_as_a_cache_point(+ gateway: Gateway, role: str, expected: str, stream: bool+) -> None:+ marker: Final = new_marker()+ with wire_server(_bedrock_peer) as wire, gateway.scenario() as scenario:+ model: Final = _bedrock_deployment(scenario, wire)+ answer: Final = _send(gateway, _responses(model, _role_items(role, marker), stream=stream))+ assert answer.status == 200, answer.text+ assert f"marker-{marker}" in answer.text or "sunny" in answer.text, answer.text+ request: Final = _only_request(wire)+ assert request.target.endswith("/converse-stream" if stream else "/converse"), request.target+ assert bedrock_labels(request) == [expected]+++def test_function_call_output_mark_reaches_bedrock_as_a_tool_result_cache_point(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(_bedrock_peer) as wire, gateway.scenario() as scenario:+ model: Final = _bedrock_deployment(scenario, wire)+ body: Final = _responses(model, _tool_items(marker, output_mark=EPHEMERAL), tools=[_TOOL])+ answer: Final = _send(gateway, body)+ assert answer.status == 200, answer.text+ assert bedrock_labels(_only_request(wire)) == [_BEDROCK_RESULT_LABEL]++[email protected]("drop_params", (False, True), ids=("as-sent", "drop-params"))+def test_nova_tool_marks_follow_drop_params(gateway: Gateway, drop_params: bool) -> None:+ marker: Final = new_marker()+ with wire_server(_bedrock_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model="bedrock/converse/us.amazon.nova-2-lite-v1:0",+ api_key=PROVIDER_KEY,+ api_base=wire.url,+ aws_region_name="us-east-1",+ aws_bedrock_runtime_endpoint=wire.url,+ drop_params=drop_params,+ )+ items: Final = _tool_items(marker, output_mark=EPHEMERAL, call_mark=EPHEMERAL)+ answer: Final = _send(gateway, _responses(model, items, tools=[_TOOL]))+ assert answer.status == 200, answer.text+ labels: Final = bedrock_labels(_only_request(wire))+ assert (_BEDROCK_RESULT_LABEL in labels) is not drop_params, labels+ assert (len(labels) == 2) is not drop_params, labels+++def test_one_hour_mark_keeps_its_ttl_on_anthropic(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _marked_system(model, marker, _HOUR)))+ marks: Final = anthropic_marks(_only_request(wire))+ assert [(mark.label, mark.ttl) for mark in marks] == [(SYSTEM_LABEL, "1h")]+++def test_one_hour_mark_keeps_its_ttl_on_bedrock(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(_bedrock_peer) as wire, gateway.scenario() as scenario:+ model: Final = _bedrock_deployment(scenario, wire)+ answer: Final = _send(gateway, _marked_system(model, marker, _HOUR))+ assert answer.status == 200, answer.text+ request: Final = _only_request(wire)+ assert bedrock_labels(request) == [_BEDROCK_SYSTEM_LABEL]+ assert _bedrock_ttls(request) == ["1h"]+++def _openai_client(gateway: Gateway) -> openai.OpenAI:+ return openai.OpenAI(+ base_url=f"{gateway.client.base_url}/v1",+ api_key=gateway.key,+ max_retries=0,+ http_client=httpx.Client(trust_env=False, timeout=60),+ )+++def _async_openai_client(gateway: Gateway) -> openai.AsyncOpenAI:+ return openai.AsyncOpenAI(+ base_url=f"{gateway.client.base_url}/v1",+ api_key=gateway.key,+ max_retries=0,+ http_client=httpx.AsyncClient(trust_env=False, timeout=60),+ )+++def _sdk_input(marker: str) -> ResponseInputParam:+ return cast(ResponseInputParam, _role_items("system", marker))+++def test_openai_sdk_sync_responses_carries_the_system_mark(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ with _openai_client(gateway) as client:+ response: Final = client.responses.create(model=model, input=_sdk_input(marker), max_output_tokens=64)+ assert response.status == "completed", response.model_dump()+ assert response.output_text == "sunny", response.model_dump()+ assert anthropic_labels(_only_request(wire)) == [SYSTEM_LABEL]+++async def test_openai_sdk_async_stream_responses_carries_the_system_mark(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ async with _async_openai_client(gateway) as client:+ stream: Final = await client.responses.create(+ model=model, input=_sdk_input(marker), max_output_tokens=64, stream=True+ )+ events: Final = [event async for event in stream]+ assert [event.type for event in events][-1] == "response.completed", events+ assert anthropic_labels(_only_request(wire)) == [SYSTEM_LABEL]+++def _gemini_peer(request: Request) -> Reply:+ if "cachedContents" in request.target and request.method == "GET":+ return Reply(body=b'{"cachedContents":[]}')+ if "cachedContents" in request.target:+ return Reply(+ body=json.dumps(+ {+ "name": "cachedContents/bridge",+ "model": "models/gemini-3.8-flash",+ "expireTime": "2099-01-01T00:00:00Z",+ }+ ).encode()+ )+ return Reply(body=_GEMINI_REPLY)+++ "fields",+ (+ pytest.param({}, id="bare"),+ pytest.param({"instructions": SYSTEM, "tools": [_TOOL]}, id="instructions-and-tools"),+ ),+)+def test_gemini_marked_items_never_start_a_context_cache(gateway: Gateway, fields: dict[str, JsonValue]) -> None:+ marker: Final = new_marker()+ long_system: Final = "lorem " * (2 * get_prompt_cache_min_tokens(_GEMINI))+ items: Final[list[JsonValue]] = [+ _item("system", long_system),+ _item("developer", SYSTEM),+ {"role": "user", "content": final_text(marker)},+ ]+ with wire_server(_gemini_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=_GEMINI, api_base=wire.url, api_key=PROVIDER_KEY)+ _assert_completed(_send(gateway, _responses(model, items, **fields)))+ targets: Final = [(request.method, request.target.split("?")[0]) for request in wire.drain()]+ assert targets == _GEMINI_GENERATE_ONLY+++def test_azure_ai_claude_marked_system_item_reaches_the_anthropic_route(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"azure_ai/{ANTHROPIC_MODEL}", api_base=wire.url, api_key=PROVIDER_KEY)+ _assert_completed(_send(gateway, _marked_system(model, marker)))+ request: Final = _only_request(wire)+ assert request.target == "/anthropic/v1/messages", request.target+ assert anthropic_labels(request) == [SYSTEM_LABEL]+++def test_bedrock_invoke_marked_system_item_reaches_the_invoke_body(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _bedrock_deployment(scenario, wire, route="invoke")+ _assert_completed(_send(gateway, _marked_system(model, marker)))+ request: Final = _only_request(wire)+ assert request.target.endswith("/invoke"), request.target+ assert anthropic_labels(request) == [SYSTEM_LABEL]+++def _openai_message_marks(request: Request) -> list[str]:+ body: Final = _JSON_OBJECT.validate_json(request.body)+ messages: Final = body["messages"] if isinstance(body["messages"], list) else []+ return [+ f"cache_control@{object_value(message).get('role')}:message"+ for message in messages+ if "cache_control" in object_value(message)+ ]+++def _openai_block_marks(request: Request) -> list[JsonValue]:+ return [object_value(block).get("cache_control") for block in _blocks_of(_JSON_OBJECT.validate_json(request.body))]+++def test_databricks_claude_keeps_the_item_mark_like_its_chat_route(gateway: Gateway) -> None:+ marker: Final = new_marker()+ reply: Final = chat_reply(f"chatcmpl-{marker}", "databricks-claude-sonnet-4", "sunny", stream=False)+ with wire_server(answering_model_discovery(lambda request: reply)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model="databricks/databricks-claude-sonnet-4", api_base=wire.url, api_key=PROVIDER_KEY+ )+ _assert_completed(_send(gateway, _marked_system(model, marker)))+ posted: Final = [request for request in wire.drain() if request.method == "POST"]+ assert [request.target for request in posted] == ["/chat/completions"], [request.target for request in posted]+ assert _openai_block_marks(posted[0]) == [EPHEMERAL]+++def test_openai_compatible_chat_bridge_leaves_the_item_mark_off(gateway: Gateway) -> None:+ marker: Final = new_marker()+ reply: Final = chat_reply(f"chatcmpl-{marker}", "gpt-5.4", "sunny", stream=False)+ with wire_server(answering_model_discovery(lambda request: reply)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=_OPENAI_COMPATIBLE, api_base=f"{wire.url}/v1", api_key=PROVIDER_KEY, use_chat_completions_api=True+ )+ _assert_completed(_send(gateway, _marked_system(model, marker)))+ posted: Final = [request for request in wire.drain() if request.method == "POST"]+ assert [request.target for request in posted] == ["/v1/chat/completions"], [request.target for request in posted]+ assert _openai_message_marks(posted[0]) == []+++def test_injection_points_keep_the_caller_one_hour_system_mark(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire, inject=True)+ _assert_completed(_send(gateway, _marked_system(model, marker, _HOUR)))+ marks: Final = anthropic_marks(_only_request(wire))+ assert [(mark.label, mark.ttl) for mark in marks] == [(SYSTEM_LABEL, "1h"), (final_label(marker), None)]+++ "mark",+ (+ pytest.param({}, id="empty-object"),+ pytest.param(None, id="null"),+ pytest.param("", id="empty-string"),+ pytest.param(0, id="zero"),+ pytest.param(False, id="false"),+ ),+)+def test_falsy_marks_are_dropped(gateway: Gateway, mark: JsonValue) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _marked_system(model, marker, mark)))+ assert anthropic_labels(_only_request(wire)) == []+++def test_missing_mark_is_dropped(gateway: Gateway) -> None:+ marker: Final = new_marker()+ items: Final[list[JsonValue]] = [+ {"role": "system", "content": SYSTEM},+ {"role": "user", "content": final_text(marker)},+ ]+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _responses(model, items)))+ assert anthropic_labels(_only_request(wire)) == []+++def test_response_cache_serves_the_marked_request_once(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ body: Final = _marked_system(model, marker)+ answers: Final = tuple(_send(gateway, body) for _ in range(2))+ received: Final = wire.drain()+ for answer in answers:+ _assert_completed(answer)+ assert [anthropic_labels(request) for request in received] == [[SYSTEM_LABEL]]+++def _chat_with_message_mark(model: str, marker: str, mark: JsonValue = EPHEMERAL) -> dict[str, JsonValue]:+ return {+ "model": model,+ "max_tokens": 64,+ "messages": [+ {"role": "system", "content": SYSTEM, "cache_control": mark},+ {"role": "user", "content": final_text(marker)},+ ],+ }+++def _messages_with_system_mark(model: str, marker: str) -> dict[str, JsonValue]:+ return {+ "model": model,+ "max_tokens": 64,+ "system": [{"type": "text", "text": SYSTEM, "cache_control": EPHEMERAL}],+ "messages": [{"role": "user", "content": final_text(marker)}],+ }++[email protected]("path", ("/v1/chat/completions", "/v1/messages"))+def test_message_marks_on_the_other_endpoints_are_unchanged(gateway: Gateway, path: str) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ body: Final = (+ _chat_with_message_mark(model, marker)+ if path == "/v1/chat/completions"+ else _messages_with_system_mark(model, marker)+ )+ response: Final = gateway.request("POST", path, body)+ assert response.status_code == 200, response.text+ assert anthropic_labels(_only_request(wire)) == [SYSTEM_LABEL]+++def test_block_mark_on_responses_input_is_unchanged(gateway: Gateway) -> None:+ marker: Final = new_marker()+ items: Final[list[JsonValue]] = [+ {"role": "user", "content": [{"type": "input_text", "text": ASK, "cache_control": EPHEMERAL}]},+ {"role": "user", "content": final_text(marker)},+ ]+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _responses(model, items, instructions=SYSTEM)))+ assert anthropic_labels(_only_request(wire)) == [ASK_LABEL]+++def _non_object_marks(request: Request) -> list[JsonValue]:+ blocks: Final = list(_blocks_of(_JSON_OBJECT.validate_json(request.body)))+ return [+ block["cache_control"]+ for block in blocks+ if isinstance(block, dict) and "cache_control" in block and not isinstance(block["cache_control"], dict)+ ]+++def _strict_anthropic_peer(request: Request) -> Reply:+ odd: Final = _non_object_marks(request)+ if odd:+ return Reply(+ status=400,+ body=json.dumps(+ {+ "type": "error",+ "error": {+ "type": "invalid_request_error",+ "message": f"cache_control: Input should be a valid dictionary, got {json.dumps(odd[0])[:64]}",+ },+ }+ ).encode(),+ )+ return anthropic_peer(request)+++ "mark",+ (+ pytest.param("ephemeral", id="string"),+ pytest.param(1, id="int"),+ pytest.param(["ephemeral"], id="list"),+ pytest.param("x" * 5120, id="5kb-string"),+ ),+)+def test_non_object_marks_reach_anthropic_as_they_do_on_chat_completions(gateway: Gateway, mark: JsonValue) -> None:+ marker: Final = new_marker()+ with wire_server(_strict_anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ on_chat: Final = gateway.request("POST", "/v1/chat/completions", _chat_with_message_mark(model, marker, mark))+ on_responses: Final = _send(gateway, _marked_system(model, marker, mark))+ received: Final = wire.drain()+ assert (on_chat.status_code, on_responses.status) == (400, 400), (on_chat.text, on_responses.text)+ assert [_non_object_marks(request) for request in received] == [[mark], [mark]]+++def test_string_mark_reaches_bedrock_as_it_does_on_chat_completions(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(_bedrock_peer) as wire, gateway.scenario() as scenario:+ model: Final = _bedrock_deployment(scenario, wire)+ on_chat: Final = gateway.request(+ "POST", "/v1/chat/completions", _chat_with_message_mark(model, marker, "ephemeral")+ )+ assert on_chat.status_code == 200, on_chat.text+ on_responses: Final = _send(gateway, _marked_system(model, marker, "ephemeral"))+ assert on_responses.status == 200, on_responses.text+ received: Final = wire.drain()+ assert len(received) == 2, [request.target for request in received]+ assert bedrock_labels(received[1]) == bedrock_labels(received[0])+++def test_unknown_mark_type_is_forwarded_like_a_block_mark(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _marked_system(model, marker, {"type": "persistent"})))+ assert anthropic_labels(_only_request(wire)) == [SYSTEM_LABEL]+++def test_duplicate_mark_keys_keep_the_last_one(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ raw: Final = (+ f'{{"model":"{model}","max_output_tokens":64,"input":['+ f'{{"role":"system","content":{json.dumps(SYSTEM)},"cache_control":{{"type":"ephemeral"}},'+ f'"cache_control":{{"type":"ephemeral","ttl":"1h"}}}},'+ f'{{"role":"user","content":{json.dumps(final_text(marker))}}}]}}'+ ).encode()+ _assert_completed(_send_raw(gateway, raw))+ marks: Final = anthropic_marks(_only_request(wire))+ assert [(mark.label, mark.ttl) for mark in marks] == [(SYSTEM_LABEL, "1h")]+++def _many_marks(marker: str, *, assistant_marked: bool) -> list[JsonValue]:+ assistant: Final[dict[str, JsonValue]] = {"role": "assistant", "content": _CHECK}+ return [+ _item("system", SYSTEM),+ _item("user", ASK),+ {**assistant, "cache_control": EPHEMERAL} if assistant_marked else assistant,+ {+ "type": "function_call",+ "call_id": call_id(CITIES[0]),+ "name": "lookup_weather",+ "arguments": json.dumps({"city": CITIES[0]}),+ },+ {+ "type": "function_call_output",+ "call_id": call_id(CITIES[0]),+ "output": "sunny.",+ "cache_control": EPHEMERAL,+ },+ _item("user", final_text(marker)),+ ]+++def test_four_marks_reach_anthropic(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ body: Final = _responses(model, _many_marks(marker, assistant_marked=False), tools=[_TOOL])+ _assert_completed(_send(gateway, body))+ labels: Final = anthropic_labels(_only_request(wire))+ assert labels == [SYSTEM_LABEL, ASK_LABEL, _RESULT_LABEL, final_label(marker)]+++def test_five_marks_are_refused_by_the_vendor(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ body: Final = _responses(model, _many_marks(marker, assistant_marked=True), tools=[_TOOL])+ answer: Final = _send(gateway, body)+ labels: Final = anthropic_labels(_only_request(wire))+ assert answer.status == 400, answer.text+ assert "A maximum of 4 blocks with cache_control" in answer.text, answer.text+ assert len(labels) == 5, labels+++def test_five_marks_keep_the_newest_four_under_drop_params(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"anthropic/{ANTHROPIC_MODEL}", api_base=wire.url, api_key=PROVIDER_KEY, drop_params=True+ )+ body: Final = _responses(model, _many_marks(marker, assistant_marked=True), tools=[_TOOL])+ _assert_completed(_send(gateway, body))+ labels: Final = anthropic_labels(_only_request(wire))+ assert labels == [ASK_LABEL, _ASSISTANT_LABEL, _RESULT_LABEL, final_label(marker)]+++def test_a_top_level_mark_takes_a_slot_under_drop_params(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"anthropic/{ANTHROPIC_MODEL}", api_base=wire.url, api_key=PROVIDER_KEY, drop_params=True+ )+ body: Final = _responses(+ model, _many_marks(marker, assistant_marked=False), tools=[_TOOL], cache_control=EPHEMERAL+ )+ _assert_completed(_send(gateway, body))+ labels: Final = anthropic_labels(_only_request(wire))+ assert labels == [ASK_LABEL, _RESULT_LABEL, final_label(marker), "request"]+++ "mark",+ (+ pytest.param("ephemeral", id="string"),+ pytest.param({"type": "forever"}, id="unknown-type"),+ ),+)+def test_malformed_mark_is_dropped_under_drop_params(gateway: Gateway, mark: JsonValue) -> None:+ marker: Final = new_marker()+ with wire_server(_strict_anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"anthropic/{ANTHROPIC_MODEL}", api_base=wire.url, api_key=PROVIDER_KEY, drop_params=True+ )+ _assert_completed(_send(gateway, _marked_system(model, marker, mark)))+ assert anthropic_labels(_only_request(wire)) == []+++def test_ttl_order_violation_is_the_vendors_verdict(gateway: Gateway) -> None:+ marker: Final = new_marker()+ items: Final[list[JsonValue]] = [+ _item("system", SYSTEM),+ _item("user", ASK, _HOUR),+ {"role": "user", "content": final_text(marker)},+ ]+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ answer: Final = _send(gateway, _responses(model, items))+ marks: Final = anthropic_marks(_only_request(wire))+ assert answer.status == 400, answer.text+ assert "ttl='1h' cache_control block must not come after" in answer.text, answer.text+ assert [(mark.label, mark.ttl) for mark in marks] == [(SYSTEM_LABEL, None), (ASK_LABEL, "1h")]+++def test_unauthenticated_marked_request_never_reaches_the_provider(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ answer: Final = _send(gateway, _marked_system(model, marker), key=f"sk-not-a-key-{marker}")+ received: Final = wire.drain()+ assert answer.status == 401, answer.text+ assert "error" in _JSON_OBJECT.validate_json(answer.text), answer.text+ assert received == ()+++def _overloaded_peer(request: Request) -> Reply:+ return Reply(+ status=503,+ body=json.dumps({"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}).encode(),+ )+++def test_provider_error_on_a_marked_request_reaches_the_caller(gateway: Gateway, spend: pcb.SpendLogs) -> None:+ marker: Final = new_marker()+ with wire_server(_overloaded_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ answer: Final = _send(gateway, _marked_system(model, marker))+ labels: Final = anthropic_labels(_only_request(wire))+ assert answer.status == 500, answer.text+ assert "overloaded_error" in answer.text, answer.text+ assert labels == [SYSTEM_LABEL]+ spend.landed(model, answer.call_id, None, status="failure")+++_SAP_DISCOVERY: Final = ("/oauth/token", "/v2/lm/")+_SAP_COMPLETION: Final = "/sap-deployment/v2/completion"+++def _only_post(wire: Wire) -> Request:+ posted: Final = [+ request+ for request in wire.drain()+ if request.method == "POST" and not request.target.startswith(_SAP_DISCOVERY)+ ]+ assert len(posted) == 1, [request.target for request in posted]+ return posted[0]+++def _message_mark_labels(message: JsonValue) -> list[str]:+ fields: Final = object_value(message)+ content: Final = fields.get("content")+ blocks: Final = content if isinstance(content, list) else []+ block_labels: Final = [+ f"{fields.get('role')}:block" for block in blocks if object_value(block).get("cache_control") is not None+ ]+ return [f"{fields.get('role')}:message"] * int(fields.get("cache_control") is not None) + block_labels+++def _openai_mark_labels(request: Request) -> list[str]:+ messages: Final = _JSON_OBJECT.validate_json(request.body)["messages"]+ return list(chain.from_iterable(map(_message_mark_labels, messages if isinstance(messages, list) else [])))+++def _sap_mark_labels(request: Request) -> list[str]:+ config: Final = object_value(_JSON_OBJECT.validate_json(request.body)["config"])+ prompt: Final = object_value(object_value(object_value(config["modules"])["prompt_templating"])["prompt"])+ template: Final = prompt["template"]+ return list(chain.from_iterable(map(_message_mark_labels, template if isinstance(template, list) else [])))+++def _route_mark_labels(request: Request) -> list[str]:+ if "/converse" in request.target:+ return bedrock_labels(request)+ if request.target.endswith("/chat/completions"):+ return _openai_mark_labels(request)+ if request.target == _SAP_COMPLETION:+ return _sap_mark_labels(request)+ return anthropic_labels(request)+++def _sap_peer(request: Request) -> Reply:+ match request.target:+ case "/oauth/token":+ return Reply(body=json.dumps({"access_token": "scripted", "expires_in": 3600}).encode())+ case "/v2/lm/deployments":+ deployment: Final = {+ "scenarioId": "orchestration",+ "configurationId": "orchestration-config",+ "deploymentUrl": f"http://{request.headers['host']}/sap-deployment",+ "createdAt": "2026-01-01T00:00:00Z",+ }+ return Reply(body=json.dumps({"resources": [deployment]}).encode())+ case "/v2/lm/configurations/orchestration-config":+ return Reply(body=json.dumps({"executableId": "orchestration"}).encode())+ case _:+ completion: Final = chat_reply(f"chatcmpl-{marker_of(request)}", "scripted", "sunny", stream=False)+ return Reply(body=json.dumps({"final_result": json.loads(completion.body)}).encode())+++def _route_peer(request: Request) -> Reply:+ if "/converse" in request.target:+ return bedrock_peer(request)+ if request.target.endswith("/chat/completions"):+ return chat_reply(f"chatcmpl-{marker_of(request)}", "scripted", "sunny", stream=False)+ if request.target.startswith((*_SAP_DISCOVERY, "/sap-deployment/")):+ return _sap_peer(request)+ return anthropic_peer(request)+++def _route_deployment(gateway: Gateway, scenario: Scenario, wire: Wire, route: str) -> str:+ match route:+ case "vertex-claude":+ return scenario.model(+ model=f"vertex_ai/{ANTHROPIC_MODEL}",+ api_key=None,+ api_base=wire.url,+ vertex_project="scripted-project",+ vertex_location="us-east5",+ vertex_credentials=service_account_json("scripted-project", gateway.upstream_url.rstrip("/")),+ )+ case "bedrock-llama":+ return scenario.model(+ model="bedrock/converse/meta.llama3-3-70b-instruct-v1:0",+ api_key=PROVIDER_KEY,+ api_base=wire.url,+ aws_region_name="us-east-1",+ aws_bedrock_runtime_endpoint=wire.url,+ )+ case "sap-claude":+ service_key: Final = {+ "clientid": "scripted",+ "clientsecret": PROVIDER_KEY,+ "url": wire.url,+ "serviceurls": {"AI_API_URL": wire.url},+ }+ return scenario.model(+ model="sap/anthropic--claude-4.5-sonnet", api_base=wire.url, api_key=json.dumps(service_key)+ )+ case _ if route.startswith("openrouter/"):+ return scenario.model(model=route, api_base=wire.url, api_key=PROVIDER_KEY, use_chat_completions_api=True)+ case _:+ return scenario.model(model=route, api_base=wire.url, api_key=PROVIDER_KEY)+++def _chat_with_tool_mark(model: str, marker: str) -> dict[str, JsonValue]:+ tool_call: Final[dict[str, JsonValue]] = {+ "id": call_id(CITIES[0]),+ "type": "function",+ "function": {"name": "lookup_weather", "arguments": json.dumps({"city": CITIES[0]})},+ }+ return {+ "model": model,+ "max_tokens": 64,+ "tools": [{"type": "function", "function": {"name": "lookup_weather", "parameters": {"type": "object"}}}],+ "messages": [+ {"role": "user", "content": ASK},+ {"role": "assistant", "content": None, "tool_calls": [tool_call]},+ {"role": "tool", "tool_call_id": call_id(CITIES[0]), "content": "sunny.", "cache_control": EPHEMERAL},+ {"role": "user", "content": final_text(marker)},+ ],+ }+++def _shaped_requests(model: str, shape: str) -> tuple[dict[str, JsonValue], dict[str, JsonValue]]:+ match shape:+ case "tool":+ bridged: Final = _responses(model, _tool_items(new_marker(), output_mark=EPHEMERAL), tools=[_TOOL])+ return _chat_with_tool_mark(model, new_marker()), bridged+ case _:+ return _chat_with_message_mark(model, new_marker()), _marked_system(model, new_marker())+++ ("route", "shape", "keeps"),+ (+ pytest.param("dashscope/qwen-plus", "system", True, id="dashscope"),+ pytest.param("minimax/MiniMax-M2", "system", True, id="minimax"),+ pytest.param("zai/glm-4.6", "system", True, id="zai"),+ pytest.param(f"openrouter/anthropic/{ANTHROPIC_MODEL}", "system", True, id="openrouter-claude"),+ pytest.param("openrouter/google/gemini-3.8-flash", "system", True, id="openrouter-gemini"),+ pytest.param("snowflake/claude-4-sonnet", "tool", True, id="snowflake-claude-tool-output"),+ pytest.param("vertex-claude", "system", True, id="vertex-claude"),+ pytest.param("sap-claude", "system", True, id="sap-claude"),+ pytest.param("anthropic/my-gateway-model", "system", True, id="anthropic-non-claude-name"),+ pytest.param("snowflake/claude-4-sonnet", "system", False, id="snowflake-claude-string-system"),+ pytest.param("openrouter/openai/gpt-5.4", "system", False, id="openrouter-gpt"),+ pytest.param("snowflake/llama3.1-70b", "system", False, id="snowflake-llama"),+ pytest.param("snowflake/llama-claude-distill", "system", False, id="snowflake-claude-inside-the-name"),+ pytest.param("databricks/databricks-meta-llama-3-3-70b-instruct", "tool", False, id="databricks-llama"),+ pytest.param("bedrock-llama", "system", False, id="bedrock-llama"),+ ),+)+def test_item_mark_reaches_each_route_the_way_a_chat_message_mark_does(+ gateway: Gateway, route: str, shape: str, keeps: bool+) -> None:+ with wire_server(answering_model_discovery(_route_peer)) as wire, gateway.scenario() as scenario:+ model: Final = _route_deployment(gateway, scenario, wire, route)+ on_chat_body, bridged_body = _shaped_requests(model, shape)+ on_chat: Final = gateway.request("POST", "/v1/chat/completions", on_chat_body)+ assert on_chat.status_code == 200, on_chat.text+ chat_request: Final = _only_post(wire)+ _assert_completed(_send(gateway, bridged_body))+ bridged_request: Final = _only_post(wire)+ bridged_labels: Final = _route_mark_labels(bridged_request)+ assert bridged_request.target == chat_request.target+ assert bridged_labels == (_route_mark_labels(chat_request) if keeps else [])+ assert bool(bridged_labels) is keeps, bridged_labels+++ ("drop_params", "expected"),+ (+ pytest.param(False, [_BEDROCK_SYSTEM_LABEL], id="as-sent"),+ pytest.param(True, [], id="drop-params"),+ ),+)+def test_unmapped_bedrock_arn_keeps_the_item_mark_unless_drop_params(+ gateway: Gateway, drop_params: bool, expected: list[str]+) -> None:+ marker: Final = new_marker()+ with wire_server(_bedrock_peer) as wire, gateway.scenario() as scenario:+ model: Final = _unmapped_arn_deployment(scenario, wire, drop_params=drop_params)+ answer: Final = _send(gateway, _marked_system(model, marker))+ assert answer.status == 200, answer.text+ assert bedrock_labels(_only_request(wire)) == expected++[email protected]("request_drop_params", (True, "true"), ids=("bool", "string"))+def test_request_drop_params_trims_five_marks_to_the_newest_four(+ gateway: Gateway, request_drop_params: JsonValue+) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ items: Final = _many_marks(marker, assistant_marked=True)+ _assert_completed(_send(gateway, _responses(model, items, tools=[_TOOL], drop_params=request_drop_params)))+ labels: Final = anthropic_labels(_only_request(wire))+ assert labels == [ASK_LABEL, _ASSISTANT_LABEL, _RESULT_LABEL, final_label(marker)]+++ ("deployment_fields", "request_drop_params"),+ (+ pytest.param({}, None, id="request-null"),+ pytest.param({}, "", id="request-empty-string"),+ pytest.param({"drop_params": True}, False, id="request-false-over-deployment-true"),+ ),+)+def test_request_without_drop_params_forwards_five_marks_as_sent(+ gateway: Gateway, deployment_fields: dict[str, JsonValue], request_drop_params: JsonValue+) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"anthropic/{ANTHROPIC_MODEL}", api_base=wire.url, api_key=PROVIDER_KEY, **deployment_fields+ )+ items: Final = _many_marks(marker, assistant_marked=True)+ answer: Final = _send(gateway, _responses(model, items, tools=[_TOOL], drop_params=request_drop_params))+ labels: Final = anthropic_labels(_only_request(wire))+ assert answer.status == 400, answer.text+ assert "A maximum of 4 blocks with cache_control" in answer.text, answer.text+ assert len(labels) == 5, labels+++def _marked_function_call_items(marker: str) -> list[JsonValue]:+ calls: Final[list[JsonValue]] = [+ {+ "type": "function_call",+ "call_id": call_id(city),+ "name": "lookup_weather",+ "arguments": json.dumps({"city": city}),+ "cache_control": EPHEMERAL,+ }+ for city in CITIES+ ]+ outputs: Final[list[JsonValue]] = [+ {"type": "function_call_output", "call_id": call_id(city), "output": "sunny."} for city in CITIES+ ]+ return [{"role": "user", "content": ASK}, *calls, *outputs, {"role": "user", "content": final_text(marker)}]+++def test_injection_points_count_a_marked_function_tool_toward_the_cap(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire, inject=True)+ body: Final = _responses(+ model,+ _marked_function_call_items(marker),+ instructions=SYSTEM,+ tools=[{**_TOOL, "cache_control": EPHEMERAL}],+ )+ _assert_completed(_send(gateway, body))+ labels: Final = anthropic_labels(_only_request(wire))+ assert labels == ["tool:lookup_weather", *(tool_use_label(city) for city in CITIES)]+++def test_assistant_text_after_a_function_call_keeps_its_mark(gateway: Gateway) -> None:+ marker: Final = new_marker()+ items: Final[list[JsonValue]] = [+ {"role": "user", "content": ASK},+ {+ "type": "function_call",+ "call_id": call_id(CITIES[0]),+ "name": "lookup_weather",+ "arguments": json.dumps({"city": CITIES[0]}),+ },+ _item("assistant", _CHECK),+ {"type": "function_call_output", "call_id": call_id(CITIES[0]), "output": "sunny."},+ {"role": "user", "content": final_text(marker)},+ ]+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ _assert_completed(_send(gateway, _responses(model, items, tools=[_TOOL])))+ labels: Final = anthropic_labels(_only_request(wire))+ assert labels == [_ASSISTANT_LABEL]+++_COUNTED_TOKENS: Final = 42+++def _count_peer(request: Request) -> Reply:+ if request.target.endswith("/count_tokens"):+ return Reply(body=json.dumps({"input_tokens": _COUNTED_TOKENS}).encode())+ return anthropic_peer(request)+++def test_input_tokens_counts_marked_items_without_their_marks(gateway: Gateway) -> None:+ marker: Final = new_marker()+ with wire_server(_count_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ body: Final = {"model": model, "input": _many_marks(marker, assistant_marked=True), "tools": [_TOOL]}+ response: Final = gateway.request("POST", "/v1/responses/input_tokens", body)+ counted: Final = _only_request(wire)+ assert response.status_code == 200, response.text+ assert _JSON_OBJECT.validate_json(response.text) == {+ "object": "response.input_tokens",+ "input_tokens": _COUNTED_TOKENS,+ }+ assert counted.target.endswith("/count_tokens"), counted.target+ assert anthropic_labels(counted) == []+++_INPUT_SHAPES: Final = ("string", "list", "object")+++def _shaped_input(shape: str, marker: str) -> JsonValue:+ marked: Final = _item("user", final_text(marker))+ match shape:+ case "string":+ return final_text(marker)+ case "list":+ return [_item("system", SYSTEM), marked]+ case _:+ return {"type": "message", **marked}+++def _shaped_body(model: str, shape: str, marker: str, **fields: JsonValue) -> dict[str, JsonValue]:+ return {+ "model": model,+ "max_output_tokens": 64,+ "instructions": SYSTEM,+ "input": _shaped_input(shape, marker),+ **fields,+ }+++def _error_message(answer: _Answer) -> JsonValue:+ if answer.status == 200:+ return None+ return object_value(_JSON_OBJECT.validate_json(answer.text)["error"]).get("message")++[email protected]("shape", _INPUT_SHAPES)+def test_each_input_shape_reads_the_same_whether_or_not_the_route_keeps_item_marks(+ gateway: Gateway, shape: str+) -> None:+ kept_marker, stripped_marker = new_marker(), new_marker()+ with wire_server(_bedrock_peer) as wire, gateway.scenario() as scenario:+ model: Final = _unmapped_arn_deployment(scenario, wire)+ kept: Final = _send(gateway, _shaped_body(model, shape, kept_marker))+ kept_sent: Final = sent_without_cache_points(wire.drain(), kept_marker)+ stripped: Final = _send(gateway, _shaped_body(model, shape, stripped_marker, drop_params=True))+ stripped_sent: Final = sent_without_cache_points(wire.drain(), stripped_marker)+ assert (stripped.status, _error_message(stripped)) == (kept.status, _error_message(kept)), (+ kept.text,+ stripped.text,+ )+ assert stripped_sent == kept_sent++[email protected]("stream", (False, True), ids=("json", "stream"))+def test_object_input_on_a_mark_stripping_route_is_served(gateway: Gateway, stream: bool) -> None:+ marker: Final = new_marker()+ reply: Final = chat_reply(f"chatcmpl-{marker}", "gpt-5.4", "sunny", stream=stream)+ with wire_server(answering_model_discovery(lambda request: reply)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=_OPENAI_COMPATIBLE, api_base=f"{wire.url}/v1", api_key=PROVIDER_KEY, use_chat_completions_api=True+ )+ _assert_completed(_send(gateway, _shaped_body(model, "object", marker, stream=stream)), stream=stream)+ posted: Final = [request for request in wire.drain() if request.method == "POST"]+ assert [request.target for request in posted] == ["/v1/chat/completions"], [request.target for request in posted]+ assert _openai_message_marks(posted[0]) == []++[email protected]("shape", _INPUT_SHAPES)+def test_input_tokens_reads_each_input_shape_without_item_marks(gateway: Gateway, shape: str) -> None:+ marker: Final = new_marker()+ with wire_server(_count_peer) as wire, gateway.scenario() as scenario:+ model: Final = _anthropic_deployment(scenario, wire)+ body: Final = {+ key: value for key, value in _shaped_body(model, shape, marker).items() if key != "max_output_tokens"+ }+ response: Final = gateway.request("POST", "/v1/responses/input_tokens", body)+ counted: Final = wire.drain()+ assert response.status_code == 200, response.text+ assert _JSON_OBJECT.validate_json(response.text) == {+ "object": "response.input_tokens",+ "input_tokens": _COUNTED_TOKENS,+ }+ assert [anthropic_labels(request) for request in counted] == [[]]++[email protected]("shape", _INPUT_SHAPES)+def test_project_input_token_limit_reads_each_input_shape(gateway: Gateway, shape: str) -> None:+ marker: Final = new_marker()+ reply: Final = chat_reply(f"chatcmpl-{marker}", "gpt-5.4", "sunny", stream=False)+ with wire_server(answering_model_discovery(lambda request: reply)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=_OPENAI_COMPATIBLE, api_base=f"{wire.url}/v1", api_key=PROVIDER_KEY, use_chat_completions_api=True+ )+ team: Final = scenario.team()+ key: Final = scenario.key(team_id=team, project_id=scenario.project(team, model_itpm_limit={model: 1_000_000}))+ _assert_completed(_send(gateway, _shaped_body(model, shape, marker), key=key))+ posted: Final = [request for request in wire.drain() if request.method == "POST"]+ assert [request.target for request in posted] == ["/v1/chat/completions"], [request.target for request in posted]+ assert _openai_message_marks(posted[0]) == []diff --git a/tests/integration/providers/test_responses_bridge_message_cache_control_wire_chaos.py b/tests/integration/providers/test_responses_bridge_message_cache_control_wire_chaos.pynew file mode 100644index 00000000000..74ea3272503--- /dev/null+++ b/tests/integration/providers/test_responses_bridge_message_cache_control_wire_chaos.py@@ -0,0 +1,575 @@+import asyncio+import dataclasses+import threading+from collections import Counter+from collections.abc import Callable, Iterator, Mapping, Sequence+from dataclasses import dataclass+from pathlib import Path+from queue import SimpleQueue+from types import MappingProxyType+from typing import Final, TypeAlias+from urllib.parse import urlsplit++import httpx+import pytest+import yaml+from integration._support import prompt_cache_breakpoint as pcb+from integration._support.client import (+ Gateway,+ Scenario,+ eventually,+ gateway_from_environment,+ object_value,+ string_value,+)+from integration._support.process import OwnedProxy, graceful_stop_seconds, owned_proxy_process+from integration._support.openai_wire import answering_model_discovery, chat_reply+from integration._support.wire import Reply, Request, Wire, wire_server+from integration.providers._cache_control_marks_support import (+ ANTHROPIC_MODEL,+ ASK,+ ASK_LABEL,+ CITIES,+ EPHEMERAL,+ PROVIDER_KEY,+ SYSTEM,+ SYSTEM_LABEL,+ anthropic_deployment,+ anthropic_labels,+ anthropic_peer,+ bedrock_labels,+ bedrock_peer,+ call_id,+ final_label,+ final_text,+ marker_of,+ new_marker,+ owned_config,+ tool_use_label,+)+from pydantic import JsonValue, TypeAdapter++pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)++_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_OWNED: Final = "bridge-mark-owned"+_OWNED_DROP: Final = "bridge-mark-owned-drop"+_NOVA: Final = "bridge-mark-nova"+_CHAT: Final = "bridge-mark-chat"+_COMPARE: Final = "Compare the three cities."+_CHECK: Final = "I will check."+_TOOL: Final[dict[str, JsonValue]] = {"type": "function", "name": "lookup_weather", "parameters": {"type": "object"}}+_UNMARKED: Final = "unmarked"+_RecordProperty: TypeAlias = Callable[[str, object], None]+++@dataclass(frozen=True, slots=True)+class _Call:+ stream: bool+ marker: str+++@dataclass(frozen=True, slots=True)+class _Served:+ call: _Call+ status: int+ text: str+ call_id: str+++@dataclass(frozen=True, slots=True)+class _StoredRig:+ wire: Wire+ proxy: OwnedProxy++ @property+ def gateway(self) -> Gateway:+ return self.proxy.gateway+++def _owned_config(directory: Path, model_list: Sequence[JsonValue]) -> Path:+ stock: Final = _JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))+ config: Final[Mapping[str, JsonValue]] = {+ **stock,+ "model_list": list(model_list),+ "general_settings": {**object_value(stock["general_settings"]), "store_prompts_in_spend_logs": True},+ "router_settings": {**object_value(stock.get("router_settings") or {}), "num_retries": 0},+ }+ path: Final = directory / "bridge-mark-owned.yaml"+ path.write_text(yaml.safe_dump(config))+ return path+++def _stored_peer(request: Request) -> Reply:+ if "/converse" in request.target:+ return bedrock_peer(request)+ if request.target.endswith("/chat/completions"):+ return chat_reply(f"chatcmpl-{marker_of(request)}", "gpt-5.4", "sunny", stream=False)+ return anthropic_peer(request)+++def _stored_models(api_base: str) -> list[JsonValue]:+ return [+ anthropic_deployment(_OWNED, api_base),+ anthropic_deployment(_OWNED_DROP, api_base, drop_params=True),+ {+ "model_name": _NOVA,+ "litellm_params": {+ "model": "bedrock/converse/us.amazon.nova-2-lite-v1:0",+ "api_key": PROVIDER_KEY,+ "api_base": api_base,+ "aws_region_name": "us-east-1",+ "aws_bedrock_runtime_endpoint": api_base,+ },+ },+ {+ "model_name": _CHAT,+ "litellm_params": {+ "model": "openai/gpt-5.4",+ "api_key": PROVIDER_KEY,+ "api_base": f"{api_base}/v1",+ "use_chat_completions_api": True,+ },+ },+ ]++[email protected](scope="module")+def stored_rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_StoredRig]:+ directory: Final = tmp_path_factory.mktemp("bridge-mark-stored")+ with wire_server(answering_model_discovery(_stored_peer)) as wire, gateway_from_environment() as gateway:+ config: Final = _owned_config(directory, _stored_models(wire.url))+ with owned_proxy_process(gateway, directory, {}, config=config, workers=2) as owned:+ yield _StoredRig(wire, owned)++[email protected](scope="module")+def yaml_drop_rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_StoredRig]:+ directory: Final = tmp_path_factory.mktemp("bridge-mark-yaml-drop")+ with wire_server(anthropic_peer) as wire, gateway_from_environment() as gateway:+ config: Final = owned_config(+ directory, [anthropic_deployment(_OWNED, wire.url)], litellm_settings={"drop_params": True}+ )+ with owned_proxy_process(gateway, directory, {}, config=config, workers=2) as owned:+ yield _StoredRig(wire, owned)++[email protected](scope="module")+def spend() -> Iterator[pcb.SpendLogs]:+ with pcb.spend_logs() as logs:+ yield logs+++def _body(model: str, call: _Call) -> Mapping[str, JsonValue]:+ return {+ "model": model,+ "stream": call.stream,+ "max_output_tokens": 64,+ "cache": {"no-cache": True},+ "input": [+ {"role": "system", "content": SYSTEM, "cache_control": EPHEMERAL},+ {"role": "user", "content": final_text(call.marker)},+ ],+ }+++def _calls(count: int, *, stream: bool | None = None) -> tuple[_Call, ...]:+ return tuple(_Call(index % 2 == 1 if stream is None else stream, new_marker()) for index in range(count))+++async def _send(client: httpx.AsyncClient, key: str, model: str, call: _Call) -> _Served:+ async with client.stream(+ "POST", "/v1/responses", json=_body(model, call), headers={"Authorization": f"Bearer {key}"}+ ) as response:+ raw: Final = await response.aread()+ return _Served(call, response.status_code, raw.decode(), response.headers["x-litellm-call-id"])+++async def _burst(+ gateway: Gateway, model: str, calls: tuple[_Call, ...], *, tolerate_transport_errors: bool = False+) -> tuple[_Served, ...]:+ async with httpx.AsyncClient(base_url=str(gateway.client.base_url), timeout=60, trust_env=False) as client:+ results: Final = await asyncio.gather(+ *(_send(client, gateway.key, model, call) for call in calls), return_exceptions=tolerate_transport_errors+ )+ for result in results:+ assert not isinstance(result, BaseException) or isinstance(result, httpx.TransportError), repr(result)+ return tuple(result for result in results if isinstance(result, _Served))+++def _assert_answered(served: _Served) -> None:+ assert served.status == 200, served.text+ assert "sunny" in served.text, served.text+ assert served.text.startswith(("event:", "data:")) == served.call.stream, served.text+ assert ("response.completed" in served.text) == served.call.stream, served.text+ if not served.call.stream:+ assert _JSON_OBJECT.validate_json(served.text)["status"] == "completed", served.text+++def _marked_posts(wire: Wire) -> tuple[Request, ...]:+ return tuple(request for request in wire.drain() if marker_of(request) != _UNMARKED)+++def _marked_once(posts: Sequence[Request], calls: Sequence[_Call]) -> None:+ by_marker: Final = {marker_of(request): request for request in posts}+ assert len(by_marker) == len(posts), [request.body for request in posts]+ assert set(by_marker) == {call.marker for call in calls}, sorted(by_marker)+ assert [anthropic_labels(by_marker[call.marker]) for call in calls] == [[SYSTEM_LABEL]] * len(calls)+++def _assert_each_lands_once(+ spend: pcb.SpendLogs, model: str, failed: Sequence[_Served], served: Sequence[_Served]+) -> None:+ expected: Final = len(failed) + len(served)+ rows: Final = eventually(lambda: spend.rows_for(model), lambda found: len(found) >= expected, seconds=70)+ by_call: Final = {string_value(row["litellm_call_id"]): row for row in rows}+ assert len(by_call) == len(rows) == expected, rows+ for item in failed:+ assert by_call[item.call_id]["status"] == "failure", (item.call_id, rows)+ for item in served:+ assert by_call[item.call_id]["status"] == "success", (item.call_id, rows)+++def _health(gateway: Gateway, model: str) -> Mapping[str, JsonValue]:+ response: Final = gateway.request("GET", f"/health?model={model}", None)+ assert response.status_code in (200, 503), response.text+ return _JSON_OBJECT.validate_json(response.text)+++def _free_port() -> int:+ with wire_server(anthropic_peer) as probe:+ port: Final = urlsplit(probe.url).port+ assert port is not None, probe.url+ return port+++def _deployment(scenario: Scenario, api_base: str) -> str:+ return scenario.model(model=f"anthropic/{ANTHROPIC_MODEL}", api_base=api_base, api_key=PROVIDER_KEY)+++async def test_mixed_burst_carries_the_system_mark_once_per_call(gateway: Gateway, spend: pcb.SpendLogs) -> None:+ calls: Final = _calls(24)+ with wire_server(anthropic_peer) as wire, gateway.scenario() as scenario:+ model: Final = _deployment(scenario, wire.url)+ served: Final = await _burst(gateway, model, calls)+ assert len(served) == 24+ for item in served:+ _assert_answered(item)+ _marked_once(_marked_posts(wire), calls)+ _assert_each_lands_once(spend, model, (), served)+++async def test_peer_outage_fails_cleanly_and_the_restarted_peer_receives_the_marks(+ gateway: Gateway, spend: pcb.SpendLogs+) -> None:+ port: Final = _free_port()+ while_down: Final = _calls(12)+ after: Final = _calls(12)+ with gateway.scenario() as scenario:+ model: Final = _deployment(scenario, f"http://127.0.0.1:{port}")+ failed: Final = await _burst(gateway, model, while_down)+ assert len(failed) == 12+ for item in failed:+ assert item.status >= 500, (item.status, item.text)+ assert "sunny" not in item.text and "event:" not in item.text, item.text+ down: Final = _health(gateway, model)+ assert (down["healthy_count"], down["unhealthy_count"]) == (0, 1), down+ with wire_server(anthropic_peer, port=port) as wire:+ _health(gateway, model)+ assert _marked_posts(wire) == ()+ served: Final = await _burst(gateway, model, after)+ assert len(served) == 12+ for item in served:+ _assert_answered(item)+ _marked_once(_marked_posts(wire), after)+ _assert_each_lands_once(spend, model, failed, served)+++def _slow(request: Request) -> Reply:+ reply: Final = anthropic_peer(request)+ return dataclasses.replace(reply, pause_between_chunks=0.4) if reply.chunks else reply+++async def test_concurrent_slow_streams_each_carry_the_mark_once(gateway: Gateway, spend: pcb.SpendLogs) -> None:+ calls: Final = _calls(6, stream=True)+ with wire_server(_slow) as wire, gateway.scenario() as scenario:+ model: Final = _deployment(scenario, wire.url)+ served: Final = await _burst(gateway, model, calls)+ assert len(served) == 6+ for item in served:+ _assert_answered(item)+ _marked_once(_marked_posts(wire), calls)+ _assert_each_lands_once(spend, model, (), served)+++@dataclass(frozen=True, slots=True)+class _Held:+ release: threading.Event+ markers: SimpleQueue[str]++ def respond(self, request: Request) -> Reply:+ marker: Final = marker_of(request)+ if marker == _UNMARKED:+ return anthropic_peer(request)+ self.markers.put(marker)+ if not self.release.wait(timeout=60):+ return Reply(status=504, body=b'{"type":"error","error":{"type":"api_error","message":"never released"}}')+ return anthropic_peer(request)+++def _worker_pids(owned: OwnedProxy) -> tuple[int, ...]:+ return eventually(lambda: pcb.started_worker_pids(owned.log), lambda pids: len(pids) == 2, seconds=30)+++async def _hold_burst(+ held: _Held, candidate: Gateway, model: str, calls: tuple[_Call, ...]+) -> asyncio.Task[tuple[_Served, ...]]:+ burst: Final = asyncio.create_task(_burst(candidate, model, calls, tolerate_transport_errors=True))+ await asyncio.to_thread(eventually, held.markers.qsize, lambda size: size == len(calls), 60)+ return burst+++def _follow_up(gateway: Gateway, wire: Wire, spend: pcb.SpendLogs) -> None:+ call: Final = _Call(False, new_marker())+ response: Final = gateway.request("POST", "/v1/responses", dict(_body(_OWNED, call)))+ served: Final = _Served(call, response.status_code, response.text, response.headers["x-litellm-call-id"])+ _assert_answered(served)+ _marked_once(_marked_posts(wire), (call,))+ spend.landed(_OWNED, served.call_id, None)+++async def test_worker_sigkill_mid_burst_leaves_the_sibling_answering(+ gateway: Gateway, tmp_path: Path, spend: pcb.SpendLogs+) -> None:+ calls: Final = _calls(20, stream=False)+ held: Final = _Held(threading.Event(), SimpleQueue())+ with wire_server(held.respond) as wire:+ config: Final = _owned_config(tmp_path, [anthropic_deployment(_OWNED, wire.url)])+ with owned_proxy_process(gateway, tmp_path, {}, config=config, workers=2) as owned:+ candidate: Final = owned.gateway+ workers: Final = _worker_pids(owned)+ burst: Final = await _hold_burst(held, candidate, _OWNED, calls)+ held_by: Final = MappingProxyType({pid: pcb.open_upstream_connections(pid, wire.url) for pid in workers})+ assert sum(held_by.values()) == 20, held_by+ victim_pid, survivor_pid = sorted(workers, key=held_by.__getitem__)+ with owned.replacing_worker(victim_pid) as kill:+ kill()+ held.release.set()+ served: Final = await burst+ assert held_by[survivor_pid] >= 10, held_by+ assert len(served) == held_by[survivor_pid], (held_by, len(served))+ for item in served:+ _assert_answered(item)+ posts: Final = _marked_posts(wire)+ assert {marker_of(request) for request in posts} == {call.marker for call in calls}, posts+ assert [anthropic_labels(request) for request in posts] == [[SYSTEM_LABEL]] * len(posts)+ _follow_up(candidate, wire, spend)+++async def test_proxy_restart_mid_burst_never_lands_a_served_call_twice(+ gateway: Gateway, tmp_path: Path, record_property: _RecordProperty, spend: pcb.SpendLogs+) -> None:+ calls: Final = _calls(20, stream=False)+ held: Final = _Held(threading.Event(), SimpleQueue())+ with wire_server(held.respond) as wire:+ config: Final = _owned_config(tmp_path, [anthropic_deployment(_OWNED, wire.url)])+ with owned_proxy_process(gateway, tmp_path, {}, config=config, workers=2) as first:+ _worker_pids(first)+ burst: Final = await _hold_burst(held, first.gateway, _OWNED, calls)+ first.begin_shutdown()+ held.release.set()+ served: Final = await burst+ for item in served:+ _assert_answered(item)+ wire.drain()+ second_directory: Final = tmp_path / "second"+ second_directory.mkdir()+ with owned_proxy_process(gateway, second_directory, {}, config=config, workers=2) as second:+ _follow_up(second.gateway, wire, spend)+ counts: Final = Counter(string_value(row["litellm_call_id"]) for row in spend.rows_for(_OWNED))+ assert all(count == 1 for count in counts.values()), counts+ landed: Final = sum(1 for item in served if item.call_id in counts)+ record_property("served", len(served))+ record_property("landed", landed)+ record_property("lost_responses", len(calls) - len(served))+++def test_previous_response_replay_keeps_the_system_mark(stored_rig: _StoredRig, spend: pcb.SpendLogs) -> None:+ first_call: Final = _Call(False, new_marker())+ first: Final = stored_rig.gateway.request(+ "POST",+ "/v1/responses",+ {+ **_body(_OWNED, first_call),+ "input": [+ {"role": "system", "content": SYSTEM, "cache_control": EPHEMERAL},+ {"role": "user", "content": final_text(first_call.marker)},+ ],+ },+ )+ assert first.status_code == 200, first.text+ first_id: Final = string_value(_JSON_OBJECT.validate_json(first.text)["id"])+ spend.landed(_OWNED, first.headers["x-litellm-call-id"], None)+ assert [anthropic_labels(request) for request in _marked_posts(stored_rig.wire)] == [[SYSTEM_LABEL]]+ second: Final = stored_rig.gateway.request(+ "POST",+ "/v1/responses",+ {+ "model": _OWNED,+ "max_output_tokens": 64,+ "cache": {"no-cache": True},+ "previous_response_id": first_id,+ "input": [{"role": "user", "content": final_text(new_marker())}],+ },+ )+ assert second.status_code == 200, second.text+ assert _JSON_OBJECT.validate_json(second.text)["status"] == "completed", second.text+ replayed: Final = _marked_posts(stored_rig.wire)+ assert len(replayed) == 1, [request.target for request in replayed]+ body: Final = _JSON_OBJECT.validate_json(replayed[0].body)+ assert isinstance(body["messages"], list) and len(body["messages"]) == 3, body+ assert anthropic_labels(replayed[0]) == [SYSTEM_LABEL]+++def _respond(rig: _StoredRig, body: Mapping[str, JsonValue]) -> httpx.Response:+ response: Final = rig.gateway.request("POST", "/v1/responses", dict(body))+ assert response.status_code == 200, response.text+ assert _JSON_OBJECT.validate_json(response.text)["status"] == "completed", response.text+ return response+++def _stored_turn(rig: _StoredRig, spend: pcb.SpendLogs, model: str, items: Sequence[JsonValue]) -> tuple[str, Request]:+ rig.wire.drain()+ first: Final = _respond(+ rig, {"model": model, "max_output_tokens": 64, "cache": {"no-cache": True}, "tools": [_TOOL], "input": items}+ )+ spend.landed(model, first.headers["x-litellm-call-id"], None)+ (posted,) = _marked_posts(rig.wire)+ return string_value(_JSON_OBJECT.validate_json(first.text)["id"]), posted+++def _replayed(rig: _StoredRig, model: str, previous: str, items: Sequence[JsonValue]) -> Request:+ _respond(+ rig,+ {+ "model": model,+ "max_output_tokens": 64,+ "cache": {"no-cache": True},+ "tools": [_TOOL],+ "previous_response_id": previous,+ "input": list(items),+ },+ )+ (posted,) = _marked_posts(rig.wire)+ return posted+++def _marked(role: str, text: str, mark: JsonValue = EPHEMERAL) -> dict[str, JsonValue]:+ return {"role": role, "content": text, "cache_control": mark}+++def _weather_call(**fields: JsonValue) -> dict[str, JsonValue]:+ return {+ "type": "function_call",+ "call_id": call_id(CITIES[0]),+ "name": "lookup_weather",+ "arguments": '{"city": "London"}',+ **fields,+ }+++def _weather_output(**fields: JsonValue) -> dict[str, JsonValue]:+ return {"type": "function_call_output", "call_id": call_id(CITIES[0]), "output": "sunny.", **fields}+++def _marked_tool_round() -> list[JsonValue]:+ return [+ {"role": "user", "content": ASK},+ _weather_call(cache_control=EPHEMERAL),+ _weather_output(cache_control=EPHEMERAL),+ ]+++def test_replay_gives_the_current_marks_their_slots_first(stored_rig: _StoredRig, spend: pcb.SpendLogs) -> None:+ first_marker: Final = new_marker()+ second_marker: Final = new_marker()+ previous, first = _stored_turn(+ stored_rig,+ spend,+ _OWNED,+ [_marked("system", SYSTEM), _marked("user", ASK), _marked("user", final_text(first_marker))],+ )+ assert anthropic_labels(first) == [SYSTEM_LABEL, ASK_LABEL, final_label(first_marker)]+ replayed: Final = _replayed(+ stored_rig, _OWNED, previous, [_marked("user", _COMPARE), _marked("user", final_text(second_marker))]+ )+ assert anthropic_labels(replayed) == [+ ASK_LABEL,+ final_label(first_marker),+ f"user:text:{_COMPARE}",+ final_label(second_marker),+ ]+++def test_replay_never_forwards_a_mark_drop_params_dropped(stored_rig: _StoredRig, spend: pcb.SpendLogs) -> None:+ previous, first = _stored_turn(+ stored_rig,+ spend,+ _OWNED_DROP,+ [_marked("system", SYSTEM, "ephemeral"), {"role": "user", "content": final_text(new_marker())}],+ )+ assert b"cache_control" not in first.body, first.body+ replayed: Final = _replayed(stored_rig, _OWNED, previous, [{"role": "user", "content": final_text(new_marker())}])+ assert b"cache_control" not in replayed.body, replayed.body+++def test_replay_into_nova_drops_the_tool_block_marks(stored_rig: _StoredRig, spend: pcb.SpendLogs) -> None:+ previous, first = _stored_turn(+ stored_rig, spend, _OWNED, [*_marked_tool_round(), {"role": "user", "content": final_text(new_marker())}]+ )+ assert anthropic_labels(first) == [tool_use_label(CITIES[0]), f"user:tool_result:{call_id(CITIES[0])}"]+ replayed: Final = _replayed(stored_rig, _NOVA, previous, [{"role": "user", "content": final_text(new_marker())}])+ assert "/converse" in replayed.target, replayed.target+ assert bedrock_labels(replayed) == []+++def test_replay_into_a_chat_route_without_marks_sends_none(stored_rig: _StoredRig, spend: pcb.SpendLogs) -> None:+ previous, first = _stored_turn(+ stored_rig,+ spend,+ _OWNED,+ [_marked("system", SYSTEM), {"role": "user", "content": final_text(new_marker())}],+ )+ assert anthropic_labels(first) == [SYSTEM_LABEL]+ replayed: Final = _replayed(stored_rig, _CHAT, previous, [{"role": "user", "content": final_text(new_marker())}])+ assert replayed.target == "/v1/chat/completions", replayed.target+ assert b"cache_control" not in replayed.body, replayed.body+++def test_yaml_drop_params_keeps_the_newest_four_marks(yaml_drop_rig: _StoredRig) -> None:+ marker: Final = new_marker()+ yaml_drop_rig.wire.drain()+ _respond(+ yaml_drop_rig,+ {+ "model": _OWNED,+ "max_output_tokens": 64,+ "cache": {"no-cache": True},+ "tools": [_TOOL],+ "input": [+ _marked("system", SYSTEM),+ _marked("user", ASK),+ _marked("assistant", _CHECK),+ _weather_call(),+ _weather_output(cache_control=EPHEMERAL),+ _marked("user", final_text(marker)),+ ],+ },+ )+ (posted,) = _marked_posts(yaml_drop_rig.wire)+ assert anthropic_labels(posted) == [+ ASK_LABEL,+ f"assistant:text:{_CHECK}",+ f"user:tool_result:{call_id(CITIES[0])}",+ final_label(marker),+ ]diff --git a/tests/integration/sdk/test_cache_control_census_pydantic_messages_sdk.py b/tests/integration/sdk/test_cache_control_census_pydantic_messages_sdk.pyindex 327681010cb..44b2933639f 100644--- a/tests/integration/sdk/test_cache_control_census_pydantic_messages_sdk.py+++ b/tests/integration/sdk/test_cache_control_census_pydantic_messages_sdk.py@@ -1,7 +1,10 @@import json+from collections.abc import Callablefrom typing import Final-from integration._support.wire import Wire, wire_server+import pytest+from integration._support.openai_wire import responses_reply+from integration._support.wire import Reply, Request, Wire, wire_serverfrom integration.providers._cache_control_marks_support import (ANTHROPIC_MODEL,CITIES,@@ -10,14 +13,18 @@ from integration.providers._cache_control_marks_support import (PROVIDER_KEY,SYSTEM,TOOL,+ UNMAPPED_BEDROCK_ARN,anthropic_labels,anthropic_peer,ask,+ bedrock_peer,call_id,client_marked,final_text,new_marker,+ sent_without_cache_points,)+from openai.types.responses import FunctionToolfrom pydantic import JsonValueimport litellm@@ -78,3 +85,77 @@ async def test_pydantic_tool_call_marks_count_against_the_cap_in_process_async_sassert "".join(str(chunk.choices[0].delta.content or "") for chunk in chunks) == "sunny", chunksreceived: Final = wire.drain()assert [anthropic_labels(request) for request in received] == [_CLIENT_MARKED]+++_OPENAI_MODEL: Final = "gpt-5.6"+++def _openai_responses_peer(request: Request) -> Reply:+ return responses_reply("resp_sdk_typed_tool", _OPENAI_MODEL, "sunny", stream=False)+++def _outcome(call: Callable[[], object]) -> str:+ try:+ response: Final = call()+ except Exception as error:+ return f"{type(error).__name__}: {error}"+ return f"{type(response).__name__}: {getattr(response, 'output_text', response)}"+++def test_injection_points_leave_an_sdk_typed_function_tool_request_as_it_is_without_them() -> None:+ tool: Final = FunctionTool(type="function", name="lookup_weather", parameters={"type": "object"}, strict=False)+ with wire_server(_openai_responses_peer) as wire:+ request: Final[dict[str, object]] = {+ "model": f"openai/{_OPENAI_MODEL}",+ "input": final_text(new_marker()),+ "tools": [tool],+ "api_base": wire.url,+ "api_key": PROVIDER_KEY,+ "num_retries": 0,+ }+ without_points: Final = _outcome(lambda: litellm.responses(**request)) # pyright: ignore[reportArgumentType] # the SDK-typed tool stands in for the dict shape the signature names+ without_points_received: Final = len(wire.drain())+ with_points: Final = _outcome(+ lambda: litellm.responses(**request, cache_control_injection_points=POINTS) # pyright: ignore[reportArgumentType] # the SDK-typed tool stands in for the dict shape the signature names+ )+ with_points_received: Final = len(wire.drain())+ assert with_points == without_points+ assert with_points_received == without_points_received+++def _shaped_input(shape: str, marker: str) -> object:+ system: Final = {"role": "system", "content": SYSTEM, "cache_control": EPHEMERAL}+ marked: Final = {"type": "message", "role": "user", "content": final_text(marker), "cache_control": EPHEMERAL}+ match shape:+ case "string":+ return final_text(marker)+ case "list":+ return [system, marked]+ case "tuple":+ return (system, marked)+ case _:+ return marked++[email protected]("shape", ("string", "list", "tuple", "object"))+def test_each_input_shape_reads_the_same_whether_or_not_the_route_keeps_item_marks(shape: str) -> None:+ kept_marker, stripped_marker = new_marker(), new_marker()+ with wire_server(bedrock_peer) as wire:+ request: Final[dict[str, object]] = {+ "model": f"bedrock/converse/{UNMAPPED_BEDROCK_ARN}",+ "instructions": SYSTEM,+ "max_output_tokens": 64,+ "api_base": wire.url,+ "api_key": PROVIDER_KEY,+ "aws_region_name": "us-east-1",+ "aws_bedrock_runtime_endpoint": wire.url,+ "num_retries": 0,+ }+ kept: Final = _outcome(lambda: litellm.responses(input=_shaped_input(shape, kept_marker), **request)) # pyright: ignore[reportArgumentType] # the shapes a caller can pass, unvalidated+ kept_sent: Final = sent_without_cache_points(wire.drain(), kept_marker)+ stripped: Final = _outcome(+ lambda: litellm.responses(input=_shaped_input(shape, stripped_marker), drop_params=True, **request) # pyright: ignore[reportArgumentType] # the shapes a caller can pass, unvalidated+ )+ stripped_sent: Final = sent_without_cache_points(wire.drain(), stripped_marker)+ assert stripped == kept+ assert stripped_sent == kept_sentdiff --git a/tests/unit/integrations/test_anthropic_cache_control_hook.py b/tests/unit/integrations/test_anthropic_cache_control_hook.pyindex 5c2b9412d16..17d8e8ad9d1 100644--- a/tests/unit/integrations/test_anthropic_cache_control_hook.py+++ b/tests/unit/integrations/test_anthropic_cache_control_hook.py@@ -13,6 +13,8 @@ from pydantic import BaseModel, ConfigDictimport litellmfrom litellm.integrations.anthropic_cache_control_hook import (+ CARRY_UNMATCHED_MESSAGE_POINTS,+ EXTERNAL_BREAKPOINTS_STAMP,AnthropicCacheControlHook,configured_injection_points,supports_openai_prompt_cache_breakpoint,@@ -1180,7 +1182,9 @@ def test_tool_call_census_matches_the_breakpoints_providers_send(mark: object, tmessage: Final = cast(AllMessageValues, {"role": "assistant", "content": None, "tool_calls": [tool_call]})bedrock_cache_points: Final = sum(1- for block in _convert_to_bedrock_tool_call_invoke([tool_call], model="anthropic.claude-sonnet-4-5-20250929-v1:0")+ for block in _convert_to_bedrock_tool_call_invoke(+ [tool_call], model="anthropic.claude-sonnet-4-5-20250929-v1:0"+ )if "cachePoint" in block)anthropic_marks: Final = sum(@@ -1895,7 +1899,9 @@ class TestEnableAnthropicPromptCaching:)@pytest.mark.parametrize("infer_provider", [False, True])@pytest.mark.parametrize("supported", [False, True])- def test_claude_transport_defaults(self, monkeypatch, local_model_cost_map, family, provider, template, infer_provider, supported):+ def test_claude_transport_defaults(+ self, monkeypatch, local_model_cost_map, family, provider, template, infer_provider, supported+ ):from litellm.utils import supports_prompt_cachingmodel = template.format(f"claude-{family}")@@ -1908,14 +1914,21 @@ class TestEnableAnthropicPromptCaching:resolved_provider = None if infer_provider else providerassert supports_prompt_caching(model=target, custom_llm_provider=resolved_provider) is supportedpoints = AnthropicCacheControlHook.get_default_injection_points(- messages=copy.deepcopy(self.MESSAGES), system=None, model=target,- custom_llm_provider=resolved_provider, enable_prompt_caching=True,+ messages=copy.deepcopy(self.MESSAGES),+ system=None,+ model=target,+ custom_llm_provider=resolved_provider,+ enable_prompt_caching=True,)assert [point["index"] for point in points] == ([None, -1] if supported else [])affinity_messages = AnthropicCacheControlHook.messages_with_default_injections(- copy.deepcopy(self.MESSAGES), models=[qualified], enable_prompt_caching=True,+ copy.deepcopy(self.MESSAGES),+ models=[qualified],+ enable_prompt_caching=True,+ )+ assert sum(AnthropicCacheControlHook._count_cache_control_blocks(m) for m in affinity_messages) == (+ 2 if supported else 0)- assert sum(AnthropicCacheControlHook._count_cache_control_blocks(m) for m in affinity_messages) == (2 if supported else 0)@pytest.mark.parametrize("provider, model",@@ -1929,7 +1942,9 @@ class TestEnableAnthropicPromptCaching:("anthropic", "unknown-model"),],)- def test_non_claude_caching_capability_does_not_enable_defaults(self, monkeypatch, local_model_cost_map, provider, model):+ def test_non_claude_caching_capability_does_not_enable_defaults(+ self, monkeypatch, local_model_cost_map, provider, model+ ):from litellm.utils import supports_prompt_cachingqualified = f"{provider}/{model}"@@ -1946,21 +1961,56 @@ class TestEnableAnthropicPromptCaching:@pytest.mark.parametrize("client_control", ["none", "message", "system", "tool", "function", "top_level"])@pytest.mark.parametrize("envelope", ["request", "extra_body"])@pytest.mark.parametrize("configured", [False, True])- def test_new_transports_preserve_client_controls(self, monkeypatch, local_model_cost_map, provider, client_control, envelope, configured):+ def test_new_transports_preserve_client_controls(+ self, monkeypatch, local_model_cost_map, provider, client_control, envelope, configured+ ):from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.transformation import VertexAIAnthropicConfigmodel = "claude-sonnet-5"monkeypatch.setattr(litellm, "enable_anthropic_prompt_caching", True)- monkeypatch.setitem(litellm.model_cost, f"{provider}/{model}", {- **litellm.model_cost[f"{provider}/{model}"], "supports_prompt_caching": True,- })+ monkeypatch.setitem(+ litellm.model_cost,+ f"{provider}/{model}",+ {+ **litellm.model_cost[f"{provider}/{model}"],+ "supports_prompt_caching": True,+ },+ )control = {"type": "ephemeral"}- messages = [{"role": "user", "content": [{"type": "text", "text": "question", **({"cache_control": control} if client_control == "message" else {})}]}]- system = [{"type": "text", "text": "stable context", **({"cache_control": control} if client_control == "system" else {})}]- tools = [{"name": "lookup", "description": "Lookup", "input_schema": {"type": "object", "properties": {}}, **({"cache_control": control} if client_control == "tool" else {})}]+ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "question",+ **({"cache_control": control} if client_control == "message" else {}),+ }+ ],+ }+ ]+ system = [+ {+ "type": "text",+ "text": "stable context",+ **({"cache_control": control} if client_control == "system" else {}),+ }+ ]+ tools = [+ {+ "name": "lookup",+ "description": "Lookup",+ "input_schema": {"type": "object", "properties": {}},+ **({"cache_control": control} if client_control == "tool" else {}),+ }+ ]if client_control == "function":tools = [{"type": "function", "function": {"name": "lookup", "parameters": {}, "cache_control": control}}]- kwargs = {"metadata": {}, "model_info": {"id": "selected-deployment"}, **({"cache_control": control} if client_control == "top_level" else {})}+ kwargs = {+ "metadata": {},+ "model_info": {"id": "selected-deployment"},+ **({"cache_control": control} if client_control == "top_level" else {}),+ }if envelope == "extra_body":kwargs["extra_body"] = {"messages": messages, "system": system, "tools": tools}if "cache_control" in kwargs:@@ -1974,7 +2024,12 @@ class TestEnableAnthropicPromptCaching:seeded = copy.deepcopy(kwargs)original = copy.deepcopy((messages, system, tools))result_messages, result_system = AnthropicCacheControlHook.maybe_inject_cache_control(- messages, system, kwargs, model, provider, tools=tools,+ messages,+ system,+ kwargs,+ model,+ provider,+ tools=tools,)if client_control != "none" and not configured:assert (result_messages, result_system, tools) == original@@ -1989,32 +2044,46 @@ class TestEnableAnthropicPromptCaching:assert (result_system == original[1]) == (envelope == "request" and client_control == "system")if provider == "vertex_ai":wire = VertexAIAnthropicConfig().transform_request(- model=model, messages=[{"role": "system", "content": result_system}, *result_messages],- optional_params={"max_tokens": 8}, litellm_params={}, headers={},+ model=model,+ messages=[{"role": "system", "content": result_system}, *result_messages],+ optional_params={"max_tokens": 8},+ litellm_params={},+ headers={},)assert wire["system"][0]["cache_control"] == controlassert wire["messages"][-1]["content"][-1]["cache_control"] == controlaffinity = AnthropicCacheControlHook.messages_with_default_injections(- [{"role": "system", "content": original[1]}, *original[0]], [f"{provider}/{model}"],- tools=tools, request_kwargs=seeded,+ [{"role": "system", "content": original[1]}, *original[0]],+ [f"{provider}/{model}"],+ tools=tools,+ request_kwargs=seeded,)if client_control != "none":assert affinity == [{"role": "system", "content": original[1]}, *original[0]]AnthropicCacheControlHook.maybe_seed_default_injection_points(- seeded, [{"role": "system", "content": original[1]}, *original[0]], model, provider, tools=tools,+ seeded,+ [{"role": "system", "content": original[1]}, *original[0]],+ model,+ provider,+ tools=tools,)assert bool(seeded.get("cache_control_injection_points")) == (client_control == "none" or configured)@pytest.mark.asyncio@pytest.mark.parametrize("asynchronous", [False, True])- @pytest.mark.parametrize("model, target, client_control, expected", [- ("vertex_ai/claude-sonnet-5", "bedrock/amazon.nova-pro-v1:0", False, 0),- ("azure_ai/gpt-6-astra", "azure_ai/claude-sonnet-5", False, 2),- ("azure_ai/claude-sonnet-5", None, False, 2),- ("azure_ai/claude-sonnet-5", None, True, 1),- ("azure_ai/model_router/claude-replacement", None, False, 2),- ])- async def test_public_completion_cache_ownership(self, monkeypatch, local_model_cost_map, asynchronous, model, target, client_control, expected):+ @pytest.mark.parametrize(+ "model, target, client_control, expected",+ [+ ("vertex_ai/claude-sonnet-5", "bedrock/amazon.nova-pro-v1:0", False, 0),+ ("azure_ai/gpt-6-astra", "azure_ai/claude-sonnet-5", False, 2),+ ("azure_ai/claude-sonnet-5", None, False, 2),+ ("azure_ai/claude-sonnet-5", None, True, 1),+ ("azure_ai/model_router/claude-replacement", None, False, 2),+ ],+ )+ async def test_public_completion_cache_ownership(+ self, monkeypatch, local_model_cost_map, asynchronous, model, target, client_control, expected+ ):import httpxfrom litellm.llms.custom_httpx.http_handler import HTTPHandler@@ -2027,22 +2096,46 @@ class TestEnableAnthropicPromptCaching:monkeypatch.setitem(litellm.model_cost, qualified, entry)monkeypatch.setitem(litellm.model_cost, qualified.split("/", 1)[-1], entry)sent = []+def respond(request):sent.append(json.loads(request.content))- return httpx.Response(200, request=request, json={- "id": "msg-test", "type": "message", "role": "assistant", "model": "claude-sonnet-5",- "content": [{"type": "text", "text": "ok"}], "stop_reason": "end_turn", "stop_sequence": None,- "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}}, "stopReason": "end_turn",- "usage": {"input_tokens": 10, "output_tokens": 1, "inputTokens": 10, "outputTokens": 1, "totalTokens": 11},- })+ return httpx.Response(+ 200,+ request=request,+ json={+ "id": "msg-test",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-5",+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},+ "stopReason": "end_turn",+ "usage": {+ "input_tokens": 10,+ "output_tokens": 1,+ "inputTokens": 10,+ "outputTokens": 1,+ "totalTokens": 11,+ },+ },+ )+control = {"type": "ephemeral", "ttl": "1h"}messages = [{"role": "system", "content": "stable context"}, {"role": "user", "content": "question"}]metadata = {}kwargs = {- "model": model, "messages": copy.deepcopy(messages), "max_tokens": 32, "num_retries": 0,+ "model": model,+ "messages": copy.deepcopy(messages),+ "max_tokens": 32,+ "num_retries": 0,"litellm_metadata": metadata,- "api_base": "https://rig.services.ai.azure.com/anthropic", "api_key": "synthetic-test-key",- "aws_access_key_id": "synthetic", "aws_secret_access_key": "synthetic", "aws_region_name": "us-east-1",+ "api_base": "https://rig.services.ai.azure.com/anthropic",+ "api_key": "synthetic-test-key",+ "aws_access_key_id": "synthetic",+ "aws_secret_access_key": "synthetic",+ "aws_region_name": "us-east-1",**({"extra_body": {"cache_control": control}} if client_control else {}),}if asynchronous:@@ -2131,7 +2224,9 @@ class TestEnableAnthropicPromptCaching:"""OpenAI-shaped tools nest cache_control under ``function``; the Anthropicchat transform honors that location, so the stand-down must see it too."""monkeypatch.setattr(litellm, "enable_anthropic_prompt_caching", True)- tools = [{"type": "function", "function": {"name": "t", "parameters": {}, "cache_control": {"type": "ephemeral"}}}]+ tools = [+ {"type": "function", "function": {"name": "t", "parameters": {}, "cache_control": {"type": "ephemeral"}}}+ ]assert self._points(tools=tools) == []def test_seed_stands_down_when_only_tools_carry_cache_control(self, monkeypatch):@@ -2912,7 +3007,10 @@ class TestConfiguredInjectionPointsSurviveClientMarks:self._seed(params, copy.deepcopy(self.CLEAN_MESSAGES), tools=[self.MARKED_TOOL_TOP_LEVEL])affinity = AnthropicCacheControlHook.messages_with_default_injections(- copy.deepcopy(self.CLEAN_MESSAGES), ["claude-sonnet-4-5"], tools=[self.MARKED_TOOL_TOP_LEVEL], request_kwargs=params+ copy.deepcopy(self.CLEAN_MESSAGES),+ ["claude-sonnet-4-5"],+ tools=[self.MARKED_TOOL_TOP_LEVEL],+ request_kwargs=params,)assert [p["index"] for p in params["cache_control_injection_points"]] == [None, -1]@@ -2966,9 +3064,7 @@ class TestAnthropicPromptCachingEnvVars:print(json.dumps([litellm.enable_anthropic_prompt_caching, litellm.anthropic_prompt_caching_ttl]))""")- result = subprocess.run(- [sys.executable, "-c", script], capture_output=True, text=True, env=env, timeout=300- )+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, env=env, timeout=300)assert result.returncode == 0, result.stderrenabled, ttl = json.loads(result.stdout.strip().splitlines()[-1])return enabled, ttl@@ -3337,7 +3433,11 @@ class TestOpenAIPromptCacheBreakpointPlacementRules:def test_tool_message_text_is_marked_on_chat_path(self):messages = [{"role": "user", "content": "weather?"},- {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "w", "arguments": "{}"}}]},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "w", "arguments": "{}"}}],+ },{"role": "tool", "tool_call_id": "c1", "content": "sunny"},]out, params = self._chat(messages, [{"location": "message", "index": -1}])@@ -3561,9 +3661,9 @@ class TestChatPathProviderStamp:class TestClientBreakpointsCountedOnce:def test_client_message_breakpoints_are_not_double_counted(self):- messages = [{"role": "user", "content": [{"type": "text", "text": "m0", "cache_control": {"type": "ephemeral"}}]}] + [- {"role": "user", "content": [{"type": "text", "text": f"m{i}"}]} for i in range(1, 4)- ]+ messages = [+ {"role": "user", "content": [{"type": "text", "text": "m0", "cache_control": {"type": "ephemeral"}}]}+ ] + [{"role": "user", "content": [{"type": "text", "text": f"m{i}"}]} for i in range(1, 4)]out, system, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(messages=messages,system="sys",@@ -3721,7 +3821,6 @@ class TestPromptCacheBreakpointCapability:yieldlitellm.utils.cached_get_model_info_helper.cache_clear()-def test_listed_model_uses_the_model_map_flag(self, monkeypatch):flagged = {**litellm.model_cost["gpt-4.1"], "supports_prompt_cache_breakpoint": True}monkeypatch.setitem(litellm.model_cost, "gpt-4.1", flagged)@@ -3747,7 +3846,6 @@ class TestPromptCacheBreakpointCapability:)assert supports_openai_prompt_cache_breakpoint(model) is False-def test_published_map_without_the_flag_still_injects_on_gpt_5_6(self, monkeypatch):unflagged = {k: v for k, v in litellm.model_cost["gpt-5.6"].items() if k != "supports_prompt_cache_breakpoint"}monkeypatch.setitem(litellm.model_cost, "gpt-5.6", unflagged)@@ -3854,9 +3952,7 @@ class TestHostedOpenAIDialectFlag:def test_entry_provider_must_match_the_request_provider(self, monkeypatch):"""A flagged entry does not license a different provider serving the same model string."""self._register(monkeypatch, self.MANTLE_MODEL, "bedrock_mantle")- assert (- AnthropicCacheControlHook.targets_openai_prompt_cache_breakpoint(self.MANTLE_MODEL, "azure") is False- )+ assert AnthropicCacheControlHook.targets_openai_prompt_cache_breakpoint(self.MANTLE_MODEL, "azure") is Falsedef test_openai_entries_still_go_through_the_api_base_check(self, monkeypatch):"""gpt-5.6 is flagged and openai-provided, so it must not bypass the host gate."""@@ -3968,7 +4064,8 @@ class TestBedrockMantleGptShipsTheOpenAIDialect:def test_every_flagged_mantle_row_is_an_openai_gpt_5_6_or_newer_model(self):flagged = {- key for key, entry in litellm.model_cost.items()+ key+ for key, entry in litellm.model_cost.items()if key.startswith("bedrock_mantle/") and entry.get("supports_prompt_cache_breakpoint") is True}assert self.MANTLE_MODEL in flagged@@ -3995,7 +4092,9 @@ class TestBedrockMantleGptShipsTheOpenAIDialect:prompt_variables=None,dynamic_callback_params={},)- assert messages[0]["content"] == [{"type": "text", "text": "sys", "prompt_cache_breakpoint": {"mode": "explicit"}}]+ assert messages[0]["content"] == [+ {"type": "text", "text": "sys", "prompt_cache_breakpoint": {"mode": "explicit"}}+ ]assert params["prompt_cache_options"] == {"mode": "implicit"}assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == 1@@ -4009,7 +4108,9 @@ class TestBedrockMantleGptShipsTheOpenAIDialect:prompt_variables=None,dynamic_callback_params={},)- assert messages[0]["content"] == [{"type": "text", "text": "sys", "prompt_cache_breakpoint": {"mode": "explicit"}}]+ assert messages[0]["content"] == [+ {"type": "text", "text": "sys", "prompt_cache_breakpoint": {"mode": "explicit"}}+ ]assert params["prompt_cache_options"] == {"mode": "implicit"}BARE_MODEL = "openai.gpt-5.6-sol"@@ -4052,10 +4153,10 @@ class TestBedrockMantleGptShipsTheOpenAIDialect:assert out["prompt_cache_options"] == {"mode": "implicit"}def test_the_responses_stamp_carries_the_resolved_provider_for_a_bare_deployment_name(self):- from litellm.responses.main import _stamp_injection_points_with_dialect+ from litellm.responses.main import _stamp_injection_points_for_the_hookkwargs: dict = {"cache_control_injection_points": copy.deepcopy(self.POINTS)}- _stamp_injection_points_with_dialect(kwargs, self.BARE_MODEL, "bedrock_mantle")+ _stamp_injection_points_for_the_hook(kwargs, self.BARE_MODEL, "bedrock_mantle", None, None)_, messages, out = AnthropicCacheControlHook().get_chat_completion_prompt(model=self.BARE_MODEL,messages=copy.deepcopy(self.MESSAGES),@@ -4068,6 +4169,156 @@ class TestBedrockMantleGptShipsTheOpenAIDialect:assert out["prompt_cache_options"] == {"mode": "implicit"}+class TestResponsesLayerReservesMarksOutsideTheProvisionalMessages:+ """The Responses layer's hook pass sees only the role-bearing input items, while the bridge+ forwards a function_call or function_call_output mark onto the tool call or tool message it+ builds, so the pass reserves those marks before placing an ordinal point and the bridge's+ pass, which sees them in its own messages, replaces the reservation with its own count."""++ MODEL = "claude-sonnet-4-6"+ MARK = {"type": "ephemeral"}++ @classmethod+ def _items(cls, marked_calls: int) -> list[dict]:+ calls = [+ {+ "type": "function_call",+ "call_id": f"call_{index}",+ "name": "weather",+ "arguments": "{}",+ "cache_control": cls.MARK,+ }+ for index in range(marked_calls)+ ]+ outputs = [+ {"type": "function_call_output", "call_id": f"call_{index}", "output": "sunny"}+ for index in range(marked_calls)+ ]+ return [+ {"role": "user", "content": "ask", "cache_control": cls.MARK},+ *calls,+ *outputs,+ {"role": "user", "content": "next"},+ ]++ @classmethod+ def _tools(cls, marked_tools: int) -> list[dict[str, object]]:+ return [+ {"type": "function", "name": f"tool_{index}", "parameters": {}, "cache_control": cls.MARK}+ for index in range(marked_tools)+ ]++ def _marks_on_the_last_message_after_the_responses_pass(+ self, marked_calls: int, marked_tools: int = 0, other_items: tuple[dict[str, object], ...] = ()+ ) -> int:+ from litellm.responses.main import _stamp_injection_points_for_the_hook+ from litellm.responses.utils import ResponsesAPIRequestUtils++ *earlier, last = self._items(marked_calls)+ items = [*earlier, *other_items, last]+ kwargs: dict = {+ "cache_control_injection_points": [{"location": "message", "index": -1}],+ CARRY_UNMATCHED_MESSAGE_POINTS: True,+ }+ _stamp_injection_points_for_the_hook(kwargs, self.MODEL, "anthropic", items, self._tools(marked_tools))+ _, messages, _ = AnthropicCacheControlHook().get_chat_completion_prompt(+ model=self.MODEL,+ messages=ResponsesAPIRequestUtils.responses_input_to_chat_messages(items),+ non_default_params=kwargs,+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ )+ return AnthropicCacheControlHook._count_cache_control_blocks(messages[-1])++ def test_function_call_marks_filling_the_cap_leave_the_ordinal_point_unplaced(self):+ assert self._marks_on_the_last_message_after_the_responses_pass(marked_calls=3) == 0++ def test_function_call_marks_under_the_cap_leave_the_ordinal_point_its_slot(self):+ assert self._marks_on_the_last_message_after_the_responses_pass(marked_calls=2) == 1++ def test_function_tool_marks_filling_the_cap_leave_the_ordinal_point_unplaced(self):+ assert self._marks_on_the_last_message_after_the_responses_pass(marked_calls=1, marked_tools=2) == 0++ def test_function_tool_marks_under_the_cap_leave_the_ordinal_point_its_slot(self):+ assert self._marks_on_the_last_message_after_the_responses_pass(marked_calls=1, marked_tools=1) == 1++ def test_marked_reasoning_items_leave_the_ordinal_point_its_slot(self):+ reasoning = tuple(+ {+ "type": "reasoning",+ "id": f"rs_{index}",+ "summary": [{"type": "summary_text", "text": "checked the weather"}],+ "cache_control": self.MARK,+ }+ for index in range(3)+ )+ assert self._marks_on_the_last_message_after_the_responses_pass(marked_calls=0, other_items=reasoning) == 1++ def test_a_marked_tool_of_another_type_is_not_reserved(self):+ from litellm.responses.main import _cache_control_marks_outside_the_provisional_messages++ tools = [{"type": "web_search", "cache_control": self.MARK}, *self._tools(1)]+ assert _cache_control_marks_outside_the_provisional_messages(self._items(1), tools) == 2++ def test_sdk_typed_output_items_are_skipped_by_the_reserve(self):+ from openai.types.responses import ResponseFunctionToolCall++ from litellm.responses.main import _cache_control_marks_outside_the_provisional_messages++ items = [+ *self._items(1),+ ResponseFunctionToolCall(type="function_call", call_id="call_typed", name="weather", arguments="{}"),+ ]+ assert _cache_control_marks_outside_the_provisional_messages(items, None) == 1++ def test_sdk_typed_tools_are_skipped_by_the_reserve(self):+ from openai.types.responses import FunctionTool++ from litellm.responses.main import _cache_control_marks_outside_the_provisional_messages++ tools = [*self._tools(1), FunctionTool(type="function", name="typed", parameters={}, strict=False)]+ assert _cache_control_marks_outside_the_provisional_messages(self._items(1), tools) == 2++ def test_the_chat_pass_replaces_the_count_the_responses_layer_stamped(self):+ messages = [+ {"role": "system", "content": "sys"},+ {"role": "user", "content": "ask", "cache_control": self.MARK},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_0",+ "type": "function",+ "function": {"name": "weather", "arguments": "{}"},+ "cache_control": self.MARK,+ }+ ],+ },+ {"role": "tool", "tool_call_id": "call_0", "content": "sunny"},+ {"role": "user", "content": "next"},+ ]+ params: dict = {+ "cache_control_injection_points": [{"location": "message", "role": "system", EXTERNAL_BREAKPOINTS_STAMP: 3}]+ }+ AnthropicCacheControlHook.maybe_seed_default_injection_points(+ non_default_params=params,+ messages=copy.deepcopy(messages),+ model=self.MODEL,+ custom_llm_provider="anthropic",+ )+ _, out, _ = AnthropicCacheControlHook().get_chat_completion_prompt(+ model=self.MODEL,+ messages=copy.deepcopy(messages),+ non_default_params=params,+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ )+ assert AnthropicCacheControlHook._count_cache_control_blocks(out[0]) == 1++class TestRecordGatewayInjection:"""The injection marker spend accounting gates prompt-caching savings on."""@@ -4274,8 +4525,8 @@ class TestMalformedInjectionPointsAreIgnored:@pytest.mark.parametrize("value", SHAPES)def test_responses_dialect_stamp_leaves_the_request_untouched(self, value):- from litellm.responses.main import _stamp_injection_points_with_dialect+ from litellm.responses.main import _stamp_injection_points_for_the_hookkwargs: dict = {"cache_control_injection_points": copy.deepcopy(value)}- _stamp_injection_points_with_dialect(kwargs, "gpt-5.6", "openai")+ _stamp_injection_points_for_the_hook(kwargs, "gpt-5.6", "openai", None, None)assert kwargs == {"cache_control_injection_points": value}diff --git a/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py b/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.pyindex 8bd242308f7..57e66032e5a 100644--- a/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py+++ b/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py@@ -898,10 +898,7 @@ class TestOpenAIResponsesHandlerToolCallExtraction:assert tool_call["id"] == "call_4SjsMeA6DUHwGKaE87ZojgOF"assert tool_call["type"] == "function"assert tool_call["function"]["name"] == "get_current_weather"- assert (- tool_call["function"]["arguments"]- == '{"location":"Boston, MA","unit":"celsius"}'- )+ assert tool_call["function"]["arguments"] == '{"location":"Boston, MA","unit":"celsius"}'assert tool_call["index"] == 0def test_extract_tool_call_from_dict_format(self):@@ -942,10 +939,7 @@ class TestOpenAIResponsesHandlerToolCallExtraction:assert tool_call["id"] == "call_4SjsMeA6DUHwGKaE87ZojgOF"assert tool_call["type"] == "function"assert tool_call["function"]["name"] == "get_current_weather"- assert (- tool_call["function"]["arguments"]- == '{"location":"Boston, MA","unit":"celsius"}'- )+ assert tool_call["function"]["arguments"] == '{"location":"Boston, MA","unit":"celsius"}'@pytest.mark.parametrize("output_item",@@ -1481,9 +1475,7 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:logging_obj: Optional[Any] = None,) -> GenericGuardrailAPIInputs:texts = inputs.get("texts", [])- inputs["texts"] = [- t.replace("<TOKEN_1>", "[email protected]") for t in texts- ]+ inputs["texts"] = [t.replace("<TOKEN_1>", "[email protected]") for t in texts]return inputshandler = OpenAIResponsesHandler()@@ -1519,15 +1511,11 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:litellm_logging_obj=None,)- completed_chunk = next(- c- for c in result- if isinstance(c, dict) and c.get("type") == "response.completed"- )+ completed_chunk = next(c for c in result if isinstance(c, dict) and c.get("type") == "response.completed")output_text = completed_chunk["response"]["output"][0]["content"][0]["text"]- assert (- output_text == "send to [email protected]"- ), f"Expected PII token to be unmasked in response.completed output, got: {output_text!r}"+ assert output_text == "send to [email protected]", (+ f"Expected PII token to be unmasked in response.completed output, got: {output_text!r}"+ )@pytest.mark.asyncioasync def test_process_output_streaming_response_pass_through_unchanged(self):@@ -1585,7 +1573,11 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:"content_index": 0,"part": {"type": "output_text", "text": "hello world"},},- {"type": "response.output_item.done", "output_index": 0, "item": {**item, "content": [dict(c) for c in content]}},+ {+ "type": "response.output_item.done",+ "output_index": 0,+ "item": {**item, "content": [dict(c) for c in content]},+ },{"type": "response.completed","response": {@@ -1646,15 +1638,29 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:return [{"type": "response.output_item.added", "output_index": 0, "item": item("", "in_progress")},- {"type": "response.function_call_arguments.delta", "item_id": "fc_123", "output_index": 0, "delta": '{"fruit":'},- {"type": "response.function_call_arguments.delta", "item_id": "fc_123", "output_index": 0, "delta": ' "persimmon"}'},+ {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_123",+ "output_index": 0,+ "delta": '{"fruit":',+ },+ {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_123",+ "output_index": 0,+ "delta": ' "persimmon"}',+ },{"type": "response.function_call_arguments.done","item_id": "fc_123","output_index": 0,"arguments": '{"fruit": "persimmon"}',},- {"type": "response.output_item.done", "output_index": 0, "item": item('{"fruit": "persimmon"}', "completed")},+ {+ "type": "response.output_item.done",+ "output_index": 0,+ "item": item('{"fruit": "persimmon"}', "completed"),+ },{"type": "response.completed","response": {@@ -1759,8 +1765,18 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:return [{"type": "response.output_item.added", "output_index": 0, "item": item("", "in_progress")},{"type": "response.custom_tool_call_input.delta", "item_id": "ctc_1", "output_index": 0, "delta": "echo "},- {"type": "response.custom_tool_call_input.delta", "item_id": "ctc_1", "output_index": 0, "delta": "persimmon"},- {"type": "response.custom_tool_call_input.done", "item_id": "ctc_1", "output_index": 0, "input": "echo persimmon"},+ {+ "type": "response.custom_tool_call_input.delta",+ "item_id": "ctc_1",+ "output_index": 0,+ "delta": "persimmon",+ },+ {+ "type": "response.custom_tool_call_input.done",+ "item_id": "ctc_1",+ "output_index": 0,+ "input": "echo persimmon",+ },{"type": "response.output_item.done", "output_index": 0, "item": item("echo persimmon", "completed")},{"type": "response.completed",@@ -1893,19 +1909,43 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:return [{"type": "response.output_item.added", "output_index": 0, "item": dict(reasoning)},{"type": "response.output_item.done", "output_index": 0, "item": dict(reasoning)},- {"type": "response.output_item.added", "output_index": 0, "item": {**message, "status": "in_progress", "content": []}},- {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "Looking that up"},+ {+ "type": "response.output_item.added",+ "output_index": 0,+ "item": {**message, "status": "in_progress", "content": []},+ },+ {+ "type": "response.output_text.delta",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "delta": "Looking that up",+ },{"type": "response.output_item.done", "output_index": 0, "item": {**message, "content": [dict(text)]}},{"type": "response.output_item.added", "output_index": 1, "item": function_call("", "in_progress")},- {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "output_index": 1, "delta": '{"fruit":'},- {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "output_index": 1, "delta": ' "persimmon"}'},+ {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_1",+ "output_index": 1,+ "delta": '{"fruit":',+ },+ {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_1",+ "output_index": 1,+ "delta": ' "persimmon"}',+ },{"type": "response.function_call_arguments.done","item_id": "fc_1","output_index": 1,"arguments": '{"fruit": "persimmon"}',},- {"type": "response.output_item.done", "output_index": 1, "item": function_call('{"fruit": "persimmon"}', "completed")},+ {+ "type": "response.output_item.done",+ "output_index": 1,+ "item": function_call('{"fruit": "persimmon"}', "completed"),+ },{"type": "response.completed","response": {@@ -2303,9 +2343,7 @@ class TestGetStructuredMessages:}result = handler.get_structured_messages(data)assert result is not None- has_system = any(- isinstance(msg, dict) and msg.get("role") == "system" for msg in result- )+ has_system = any(isinstance(msg, dict) and msg.get("role") == "system" for msg in result)assert has_system, f"Expected system message from instructions, got: {result}"def test_should_return_none_when_no_input(self):@@ -2405,9 +2443,7 @@ class StructuredRewriteGuardrail(CustomGuardrail):) -> GenericGuardrailAPIInputs:messages = list(inputs.get("structured_messages") or [])first_user = next(i for i, m in enumerate(messages) if m.get("role") == "user")- rewritten = [- {**m, "content": COMPRESSED_MARKER} if i == first_user else m for i, m in enumerate(messages)- ]+ rewritten = [{**m, "content": COMPRESSED_MARKER} if i == first_user else m for i, m in enumerate(messages)]return {**inputs, "structured_messages": rewritten}@@ -2453,9 +2489,7 @@ class ToolOutputRewriteGuardrail(CustomGuardrail):) -> GenericGuardrailAPIInputs:messages = list(inputs.get("structured_messages") or [])first_tool = next(i for i, m in enumerate(messages) if isinstance(m, dict) and m.get("role") == "tool")- rewritten = [- {**m, "content": COMPRESSED_MARKER} if i == first_tool else m for i, m in enumerate(messages)- ]+ rewritten = [{**m, "content": COMPRESSED_MARKER} if i == first_tool else m for i, m in enumerate(messages)]return {**inputs, "structured_messages": rewritten}@@ -2472,9 +2506,7 @@ class DroppingRewriteGuardrail(CustomGuardrail):) -> GenericGuardrailAPIInputs:messages = list(inputs.get("structured_messages") or [])first_user = next(i for i, m in enumerate(messages) if isinstance(m, dict) and m.get("role") == "user")- rewritten = [- {**m, "content": COMPRESSED_MARKER} if i == first_user else m for i, m in enumerate(messages)- ]+ rewritten = [{**m, "content": COMPRESSED_MARKER} if i == first_user else m for i, m in enumerate(messages)]return {**inputs, "structured_messages": rewritten[:-1]}@@ -2520,6 +2552,21 @@ class TestStructuredMessagesWriteBack:assert [_texts(item) for item in result["input"]] == [[COMPRESSED_MARKER]]assert "instructions" not in result+ @pytest.mark.asyncio+ async def test_rows_the_guardrail_left_alone_keep_their_cache_control_past_the_provider_cap(self):+ handler = OpenAIResponsesHandler()+ ephemeral = {"type": "ephemeral"}+ marked_turns = [{"role": "user", "content": f"turn {index}", "cache_control": ephemeral} for index in range(4)]+ data = {+ "model": "bedrock/us.anthropic.claude-sonnet-4-6",+ "input": [{"role": "user", "content": "memo " * 400, "cache_control": ephemeral}, *marked_turns],+ }++ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())++ assert _texts(result["input"][0]) == [COMPRESSED_MARKER]+ assert result["input"][1:] == marked_turns+@pytest.mark.asyncioasync def test_developer_item_preserved_verbatim_by_row_patch(self):handler = OpenAIResponsesHandler()@@ -2816,6 +2863,20 @@ class TestPerMessageRewriteWriteBack:only where every row has a scanned text (instructions plus a string input) andis otherwise rejected by name instead of sent unrewritten."""+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "cache_control", [{"type": "ephemeral", "ttl": "30m"}, {"type": "persistent"}], ids=["ttl-30m", "unknown-type"]+ )+ async def test_an_item_mark_no_chat_row_can_hold_still_lets_the_guardrail_run(self, cache_control: dict):+ guardrail = _per_message_redactor()+ marked_item = {"role": "user", "content": "Look up " + SSN + " for me.", "cache_control": cache_control}+ data = {"model": "gemini/gemini-2.5-flash", "input": [marked_item]}++ with patch.object(guardrail.async_handler, "post", side_effect=_per_message_guardrail_server(True)):+ result = await OpenAIResponsesHandler().process_input_messages(data, guardrail)++ assert result["input"] == [{**marked_item, "content": "Look up " + REDACTED_SSN + " for me."}]+@pytest.mark.asyncioasync def test_structured_rows_land_on_instructions_and_tool_output(self):guardrail = _per_message_redactor()@@ -3034,9 +3095,7 @@ class SystemRewriteGuardrail(CustomGuardrail):) -> GenericGuardrailAPIInputs:messages = list(inputs.get("structured_messages") or [])first = next(i for i, m in enumerate(messages) if isinstance(m, dict) and m.get("role") == "system")- rewritten = [- {**m, "content": self.rewritten_content} if i == first else m for i, m in enumerate(messages)- ]+ rewritten = [{**m, "content": self.rewritten_content} if i == first else m for i, m in enumerate(messages)]return {**inputs, "structured_messages": rewritten}@@ -3411,9 +3470,7 @@ class TestBuildBlockSseChunks:{"type": "message", "id": "msg_live", "status": "in_progress", "role": "assistant", "content": []})yielded = [- OutputItemAddedEvent(- type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED, output_index=0, item=open_item- ),+ OutputItemAddedEvent(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED, output_index=0, item=open_item),ContentPartAddedEvent(type=ResponsesAPIStreamEvents.CONTENT_PART_ADDED,item_id="msg_live",@@ -3627,7 +3684,11 @@ class TestOpenAIResponsesHandlerStreamingScanKey:"delta": '{"city":',}function_call = {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": '{"city":'}- terminal = {"type": terminal_type, "sequence_number": 2, "response": {"id": "resp_1", "output": [function_call]}}+ terminal = {+ "type": terminal_type,+ "sequence_number": 2,+ "response": {"id": "resp_1", "output": [function_call]},+ }mid_stream_key = handler.get_streaming_scan_key([arguments_delta])ended_key = handler.get_streaming_scan_key([arguments_delta, terminal])assert ended_key.stream_ended is True@@ -3661,7 +3722,13 @@ class TestOpenAIResponsesHandlerStreamingScanKey:added = {"type": "response.output_item.added","sequence_number": 1,- "item": {"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "get_weather", "arguments": ""},+ "item": {+ "type": "function_call",+ "id": "fc_1",+ "call_id": "call_1",+ "name": "get_weather",+ "arguments": "",+ },}arguments_delta = {"type": "response.function_call_arguments.delta",@@ -3686,7 +3753,11 @@ class TestOpenAIResponsesHandlerStreamingScanKey:arguments = json.dumps({"city": city})pending = {"type": "function_call", "id": item_id, "call_id": "call_" + item_id, "name": "get_weather"}return (- {"type": "response.output_item.added", "sequence_number": sequence_number, "item": {**pending, "arguments": ""}},+ {+ "type": "response.output_item.added",+ "sequence_number": sequence_number,+ "item": {**pending, "arguments": ""},+ },{"type": "response.function_call_arguments.delta","sequence_number": sequence_number + 1,@@ -3710,7 +3781,9 @@ class TestOpenAIResponsesHandlerStreamingScanKey:ended_key = handler.get_streaming_scan_key(handler.released_stream_as_ended(released))assert ended_key.stream_ended is Trueassert ended_key.texts == ("hi",)- cities = tuple(city for fingerprint in ended_key.tool_calls for city in ("Paris", "Rome") if city in fingerprint)+ cities = tuple(+ city for fingerprint in ended_key.tool_calls for city in ("Paris", "Rome") if city in fingerprint+ )assert cities == ("Paris", "Rome"), ended_keydef test_released_stream_as_ended_keys_a_message_whose_item_already_finished(self):@@ -3720,7 +3793,9 @@ class TestOpenAIResponsesHandlerStreamingScanKey:"sequence_number": 1,"item": {"type": "message", "id": "msg_1", "content": [{"type": "output_text", "text": "hi"}]},}- ended_key = handler.get_streaming_scan_key(handler.released_stream_as_ended((self._delta(0, "hi"), message_done)))+ ended_key = handler.get_streaming_scan_key(+ handler.released_stream_as_ended((self._delta(0, "hi"), message_done))+ )assert ended_key.stream_ended is Trueassert ended_key.texts == ("hi",)diff --git a/tests/unit/llms/snowflake/test_snowflake_native_endpoints.py b/tests/unit/llms/snowflake/test_snowflake_native_endpoints.pyindex 344b8e5573d..8ddbb7c1a6b 100644--- a/tests/unit/llms/snowflake/test_snowflake_native_endpoints.py+++ b/tests/unit/llms/snowflake/test_snowflake_native_endpoints.py@@ -18,7 +18,7 @@ import pytestfrom litellm.llms.snowflake.chat.transformation import (SnowflakeConfig,- _is_claude_model,+ is_snowflake_claude_model,)from litellm.types.utils import ModelResponse@@ -69,6 +69,7 @@ def _make_anthropic_response(content: str = "Hello!") -> httpx.Response:# ─── SnowflakeConfig (OpenAI-compatible) ───────────────────────────────────+class TestSnowflakeConfigURL:def setup_method(self):self.cfg = SnowflakeConfig()@@ -266,6 +267,7 @@ class TestSnowflakeConfigResponse:# ─── SnowflakeConfig ────────────────────────────────────────+class TestAnthropicConfigURL:def setup_method(self):self.cfg = SnowflakeConfig()@@ -533,21 +535,23 @@ class TestAnthropicConfigResponse:# ─── Model detection helper ────────────────────────────────────────────────+class TestIsClaudeModel:def test_claude_model_detected(self):- assert _is_claude_model("snowflake/claude-sonnet-4-5") is True- assert _is_claude_model("claude-3-haiku") is True- assert _is_claude_model("snowflake/claude-opus-4") is True+ assert is_snowflake_claude_model("snowflake/claude-sonnet-4-5") is True+ assert is_snowflake_claude_model("claude-3-haiku") is True+ assert is_snowflake_claude_model("snowflake/claude-opus-4") is Truedef test_non_claude_not_detected(self):- assert _is_claude_model("snowflake/llama3.1-70b") is False- assert _is_claude_model("snowflake/mistral-large") is False- assert _is_claude_model("snowflake/deepseek-r1") is False- assert _is_claude_model("snowflake/snowflake-arctic") is False+ assert is_snowflake_claude_model("snowflake/llama3.1-70b") is False+ assert is_snowflake_claude_model("snowflake/mistral-large") is False+ assert is_snowflake_claude_model("snowflake/deepseek-r1") is False+ assert is_snowflake_claude_model("snowflake/snowflake-arctic") is False# ─── Anthropic Tool Transformation Tests ──────────────────────────────────+class TestAnthropicToolTransformation:def setup_method(self):self.cfg = SnowflakeConfig()diff --git a/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py b/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.pyindex 7d70b96eeff..19eb3c71a5b 100644--- a/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py+++ b/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py@@ -115,14 +115,9 @@ class TestGenericGuardrailAPIConfiguration:headers={"Authorization": "Bearer test-key"},additional_provider_specific_params={"custom_param": "value"},)- assert (- guardrail.api_base- == "https://api.test.guardrail.com/beta/litellm_basic_guardrail_api"- )+ assert guardrail.api_base == "https://api.test.guardrail.com/beta/litellm_basic_guardrail_api"assert guardrail.headers == {"Authorization": "Bearer test-key"}- assert guardrail.additional_provider_specific_params == {- "custom_param": "value"- }+ assert guardrail.additional_provider_specific_params == {"custom_param": "value"}def test_init_with_env_vars(self):"""Test initialization with environment variables"""@@ -133,10 +128,7 @@ class TestGenericGuardrailAPIConfiguration:},):guardrail = GenericGuardrailAPI()- assert (- guardrail.api_base- == "https://env.api.guardrail.com/beta/litellm_basic_guardrail_api"- )+ assert guardrail.api_base == "https://env.api.guardrail.com/beta/litellm_basic_guardrail_api"def test_init_without_api_base_raises_error(self):"""Test that initialization without API base raises ValueError"""@@ -149,20 +141,14 @@ class TestGenericGuardrailAPIConfiguration:guardrail = GenericGuardrailAPI(api_base="https://api.test.guardrail.com/v1",)- assert (- guardrail.api_base- == "https://api.test.guardrail.com/v1/beta/litellm_basic_guardrail_api"- )+ assert guardrail.api_base == "https://api.test.guardrail.com/v1/beta/litellm_basic_guardrail_api"def test_api_base_not_duplicated(self):"""Test that endpoint path is not duplicated if already present"""guardrail = GenericGuardrailAPI(api_base="https://api.test.guardrail.com/beta/litellm_basic_guardrail_api",)- assert (- guardrail.api_base- == "https://api.test.guardrail.com/beta/litellm_basic_guardrail_api"- )+ assert guardrail.api_base == "https://api.test.guardrail.com/beta/litellm_basic_guardrail_api"def test_api_key_sets_x_api_key_header(self):"""Test that api_key is set as x-api-key header"""@@ -224,9 +210,7 @@ class TestExtraHeadersForwarding:}mock_response.raise_for_status = MagicMock()- with patch.object(- guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(guardrail.async_handler, "post", return_value=mock_response) as mock_post:await guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=request_data,@@ -264,9 +248,7 @@ class TestExtraHeadersForwarding:}mock_response.raise_for_status = MagicMock()- with patch.object(- guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(guardrail.async_handler, "post", return_value=mock_response) as mock_post:await guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=request_data,@@ -285,9 +267,7 @@ class TestMetadataExtraction:"""Test metadata extraction from request data"""@pytest.mark.asyncio- async def test_extract_metadata_from_input_request(- self, generic_guardrail, mock_request_data_input- ):+ async def test_extract_metadata_from_input_request(self, generic_guardrail, mock_request_data_input):"""Test extracting metadata from input request (metadata field)"""# Mock API responsemock_response = MagicMock()@@ -297,9 +277,7 @@ class TestMetadataExtraction:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["Who is Ishaan?"]},request_data=mock_request_data_input,@@ -355,9 +333,7 @@ class TestMetadataExtraction:}mock_api_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_api_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_api_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["hey i'm ishaan!"]},request_data=request_data,@@ -380,9 +356,7 @@ class TestMetadataExtraction:assert request_metadata["user_api_key_user_id"] == "default_user_id"@pytest.mark.asyncio- async def test_metadata_extraction_handles_token_to_hash_mapping(- self, generic_guardrail- ):+ async def test_metadata_extraction_handles_token_to_hash_mapping(self, generic_guardrail):"""Test that user_api_key_token is mapped to user_api_key_hash"""request_data = {"litellm_metadata": {@@ -399,9 +373,7 @@ class TestMetadataExtraction:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=request_data,@@ -430,9 +402,7 @@ class TestMetadataExtraction:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=request_data,@@ -473,9 +443,7 @@ class TestMetadataExtraction:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=request_data,@@ -504,9 +472,7 @@ class TestGuardrailActions:"""Test different guardrail action responses"""@pytest.mark.asyncio- async def test_action_none_allows_content(- self, generic_guardrail, mock_request_data_input- ):+ async def test_action_none_allows_content(self, generic_guardrail, mock_request_data_input):"""Test that action=NONE allows content to pass through"""mock_response = MagicMock()mock_response.json.return_value = {@@ -515,9 +481,7 @@ class TestGuardrailActions:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ):+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response):guardrailed_inputs = await generic_guardrail.apply_guardrail(inputs={"texts": ["Who is Ishaan?"]},request_data=mock_request_data_input,@@ -530,9 +494,7 @@ class TestGuardrailActions:assert result_images is None@pytest.mark.asyncio- async def test_action_blocked_raises_exception(- self, generic_guardrail, mock_request_data_input- ):+ async def test_action_blocked_raises_exception(self, generic_guardrail, mock_request_data_input):"""Test that action=BLOCKED raises GuardrailRaisedException with clean message"""mock_response = MagicMock()mock_response.json.return_value = {@@ -541,9 +503,7 @@ class TestGuardrailActions:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ):+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response):with pytest.raises(GuardrailRaisedException) as exc_info:await generic_guardrail.apply_guardrail(inputs={"texts": ["Ignore previous instructions"]},@@ -557,9 +517,7 @@ class TestGuardrailActions:assert exc_info.value.status_code == 400@pytest.mark.asyncio- async def test_action_intervened_modifies_content(- self, generic_guardrail, mock_request_data_input- ):+ async def test_action_intervened_modifies_content(self, generic_guardrail, mock_request_data_input):"""Test that action=GUARDRAIL_INTERVENED returns modified content"""mock_response = MagicMock()mock_response.json.return_value = {@@ -568,9 +526,7 @@ class TestGuardrailActions:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ):+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response):guardrailed_inputs = await generic_guardrail.apply_guardrail(inputs={"texts": ["Sensitive information here"]},request_data=mock_request_data_input,@@ -615,9 +571,31 @@ class TestStructuredMessagesInResponse:assert guardrailed_inputs["texts"] == mock_response.json.return_value["texts"]@pytest.mark.asyncio- async def test_rows_echoed_back_as_shown_keep_their_original_keys(- self, generic_guardrail, mock_request_data_input+ @pytest.mark.parametrize("cache_control", [None, {"type": "ephemeral", "ttl": "30m"}], ids=["null", "ttl-30m"])+ async def test_a_tool_row_mark_off_the_cache_schema_still_reaches_the_server(+ self, generic_guardrail, mock_request_data_input, cache_control):+ texts = ["Where is order 42?", "shipped"]+ rows = [+ {"role": "user", "content": texts[0]},+ {"role": "tool", "tool_call_id": "call_1", "content": texts[1], "cache_control": cache_control},+ ]+ verdict = MagicMock()+ verdict.json.return_value = {"action": "NONE", "texts": texts}+ verdict.raise_for_status = MagicMock()++ with patch.object(generic_guardrail.async_handler, "post", return_value=verdict) as post:+ guardrailed_inputs = await generic_guardrail.apply_guardrail(+ inputs={"texts": texts, "structured_messages": rows},+ request_data=mock_request_data_input,+ input_type="request",+ )++ post.assert_called_once()+ assert guardrailed_inputs["texts"] == texts++ @pytest.mark.asyncio+ async def test_rows_echoed_back_as_shown_keep_their_original_keys(self, generic_guardrail, mock_request_data_input):tool_call_row = {"role": "assistant","content": None,@@ -726,9 +704,7 @@ class TestImageSupport:"""Test image handling in guardrail requests"""@pytest.mark.asyncio- async def test_images_passed_in_request(- self, generic_guardrail, mock_request_data_input- ):+ async def test_images_passed_in_request(self, generic_guardrail, mock_request_data_input):"""Test that images are passed to the API"""mock_response = MagicMock()mock_response.json.return_value = {@@ -738,9 +714,7 @@ class TestImageSupport:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:guardrailed_inputs = await generic_guardrail.apply_guardrail(inputs={"texts": ["What's in this image?"],@@ -778,9 +752,7 @@ class TestApiKeyHeader:}mock_response.raise_for_status = MagicMock()- with patch.object(- guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(guardrail.async_handler, "post", return_value=mock_response) as mock_post:await guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=mock_request_data_input,@@ -814,9 +786,7 @@ class TestAdditionalParams:}mock_response.raise_for_status = MagicMock()- with patch.object(- guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(guardrail.async_handler, "post", return_value=mock_response) as mock_post:await guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=mock_request_data_input,@@ -826,23 +796,15 @@ class TestAdditionalParams:# Verify API was called with additional paramscall_args = mock_post.call_argsjson_payload = call_args.kwargs["json"]- assert (- json_payload["additional_provider_specific_params"]["custom_threshold"]- == 0.8- )- assert (- json_payload["additional_provider_specific_params"]["enable_feature"]- is True- )+ assert json_payload["additional_provider_specific_params"]["custom_threshold"] == 0.8+ assert json_payload["additional_provider_specific_params"]["enable_feature"] is Trueclass TestModelParameter:"""Test model parameter handling in guardrail requests"""@pytest.mark.asyncio- async def test_model_passed_from_inputs(- self, generic_guardrail, mock_request_data_input- ):+ async def test_model_passed_from_inputs(self, generic_guardrail, mock_request_data_input):"""Test that model is passed to the API when provided in inputs"""mock_response = MagicMock()mock_response.json.return_value = {@@ -851,9 +813,7 @@ class TestModelParameter:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["test"], "model": "gpt-4"},request_data=mock_request_data_input,@@ -866,9 +826,7 @@ class TestModelParameter:assert json_payload["model"] == "gpt-4"@pytest.mark.asyncio- async def test_model_none_when_not_provided(- self, generic_guardrail, mock_request_data_input- ):+ async def test_model_none_when_not_provided(self, generic_guardrail, mock_request_data_input):"""Test that model is None when not provided in inputs"""mock_response = MagicMock()mock_response.json.return_value = {@@ -877,9 +835,7 @@ class TestModelParameter:}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["test"]}, # No model in inputsrequest_data=mock_request_data_input,@@ -896,18 +852,14 @@ class TestErrorHandling:"""Test error handling scenarios"""@pytest.mark.asyncio- async def test_api_failure_handling(- self, generic_guardrail, mock_request_data_input- ):+ async def test_api_failure_handling(self, generic_guardrail, mock_request_data_input):"""Test API failure handling"""with patch.object(generic_guardrail.async_handler,"post",- side_effect=httpx.HTTPStatusError(- "API Error", request=MagicMock(), response=MagicMock(status_code=500)- ),+ side_effect=httpx.HTTPStatusError("API Error", request=MagicMock(), response=MagicMock(status_code=500)),):- with pytest.raises(Exception, match='Generic Guardrail API failed: API Error') as exc_info:+ with pytest.raises(Exception, match="Generic Guardrail API failed: API Error") as exc_info:await generic_guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=mock_request_data_input,@@ -917,16 +869,14 @@ class TestErrorHandling:assert "Generic Guardrail API failed" in str(exc_info.value)@pytest.mark.asyncio- async def test_network_error_handling(- self, generic_guardrail, mock_request_data_input- ):+ async def test_network_error_handling(self, generic_guardrail, mock_request_data_input):"""Test network error handling"""with patch.object(generic_guardrail.async_handler,"post",side_effect=httpx.RequestError("Connection failed", request=MagicMock()),):- with pytest.raises(Exception, match='Generic Guardrail API failed: Connection failed') as exc_info:+ with pytest.raises(Exception, match="Generic Guardrail API failed: Connection failed") as exc_info:await generic_guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=mock_request_data_input,@@ -950,7 +900,7 @@ class TestErrorHandling:"post",side_effect=httpx.RequestError("Connection failed", request=MagicMock()),):- with pytest.raises(Exception, match='Generic Guardrail API failed: Connection failed') as exc_info:+ with pytest.raises(Exception, match="Generic Guardrail API failed: Connection failed") as exc_info:await guardrail.apply_guardrail(inputs={"texts": ["test"]},request_data=mock_request_data_input,@@ -1078,9 +1028,7 @@ class TestMultimodalSupport:}mock_response.raise_for_status = MagicMock()- with patch.object(- guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(guardrail.async_handler, "post", return_value=mock_response) as mock_post:# This should not raise SerializationIterator errorawait guardrail.apply_guardrail(inputs={@@ -1142,9 +1090,7 @@ class TestMultimodalSupport:}mock_response.raise_for_status = MagicMock()- with patch.object(- guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(guardrail.async_handler, "post", return_value=mock_response) as mock_post:await guardrail.apply_guardrail(inputs={"texts": ["Hello", "World"],@@ -1325,9 +1271,7 @@ class TestGenericGuardrailAPIStreamingConfig:guardrail_config = {"guardrail_name": "test-generic-streaming"}- with patch(- "litellm.logging_callback_manager.add_litellm_callback"- ):+ with patch("litellm.logging_callback_manager.add_litellm_callback"):guardrail = initialize_guardrail(litellm_params, guardrail_config)assert guardrail.streaming_end_of_stream_only is False@@ -1398,9 +1342,7 @@ class TestGenericGuardrailAPIStreamingConfig:guardrail_config = {"guardrail_name": "test-generic-streaming-mixed"}- with patch(- "litellm.logging_callback_manager.add_litellm_callback"- ):+ with patch("litellm.logging_callback_manager.add_litellm_callback"):guardrail = initialize_guardrail(litellm_params, guardrail_config)assert guardrail.streaming_end_of_stream_only is True@@ -1430,9 +1372,7 @@ class TestGenericGuardrailAPIStreamingConfig:guardrail_config = {"guardrail_name": "test-generic-streaming-nested-wins"}- with patch(- "litellm.logging_callback_manager.add_litellm_callback"- ):+ with patch("litellm.logging_callback_manager.add_litellm_callback"):guardrail = initialize_guardrail(litellm_params, guardrail_config)assert guardrail.streaming_end_of_stream_only is True@@ -1461,9 +1401,7 @@ class TestGenericGuardrailAPIStreamingConfig:guardrail_config = {"guardrail_name": "test-generic-streaming-dict-optional"}- with patch(- "litellm.logging_callback_manager.add_litellm_callback"- ):+ with patch("litellm.logging_callback_manager.add_litellm_callback"):guardrail = initialize_guardrail(litellm_params, guardrail_config)assert guardrail.streaming_end_of_stream_only is True@@ -1492,9 +1430,7 @@ class TestGenericGuardrailAPIStreamingConfig:guardrail_config = {"guardrail_name": "test-generic-streaming-dict-sibling"}- with patch(- "litellm.logging_callback_manager.add_litellm_callback"- ):+ with patch("litellm.logging_callback_manager.add_litellm_callback"):guardrail = initialize_guardrail(litellm_params, guardrail_config)assert guardrail.streaming_end_of_stream_only is True@@ -1605,11 +1541,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:finish_reason="stop" if i == len(chunks_data) - 1 else None,)- mock_post = AsyncMock(- return_value=_mock_guardrail_post_response(- action="NONE", texts=["Hello world! Goodbye"]- )- )+ mock_post = AsyncMock(return_value=_mock_guardrail_post_response(action="NONE", texts=["Hello world! Goodbye"]))with (patch.object(guardrail.async_handler, "post", mock_post),@@ -1618,9 +1550,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:return_value=_make_assembled_model_response("Hello world! Goodbye"),),):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/chat/completions"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/chat/completions")request_data = {"messages": [{"role": "user", "content": "hi"}],"guardrail_to_apply": guardrail,@@ -1662,9 +1592,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:)mock_post = AsyncMock(- return_value=_mock_guardrail_post_response(- action="BLOCKED", blocked_reason="Ishaan is not allowed"- )+ return_value=_mock_guardrail_post_response(action="BLOCKED", blocked_reason="Ishaan is not allowed"))with (@@ -1674,9 +1602,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:return_value=_make_assembled_model_response("Hello ishaan here"),),):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/chat/completions"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/chat/completions")request_data = {"messages": [{"role": "user", "content": "hi"}],"guardrail_to_apply": guardrail,@@ -1717,11 +1643,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:finish_reason="stop" if i == len(chunks_data) - 1 else None,)- mock_post = AsyncMock(- return_value=_mock_guardrail_post_response(- action="NONE", texts=["ABCDEFGHIJ"]- )- )+ mock_post = AsyncMock(return_value=_mock_guardrail_post_response(action="NONE", texts=["ABCDEFGHIJ"]))with (patch.object(guardrail.async_handler, "post", mock_post),@@ -1730,9 +1652,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:return_value=_make_assembled_model_response("ABCDEFGHIJ"),),):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/chat/completions"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/chat/completions")request_data = {"messages": [{"role": "user", "content": "hi"}],"guardrail_to_apply": guardrail,@@ -1776,11 +1696,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:finish_reason="stop" if i == len(chunks_data) - 1 else None,)- mock_post = AsyncMock(- return_value=_mock_guardrail_post_response(- action="NONE", texts=["ABCDEFGHIJ"]- )- )+ mock_post = AsyncMock(return_value=_mock_guardrail_post_response(action="NONE", texts=["ABCDEFGHIJ"]))with (patch.object(guardrail.async_handler, "post", mock_post),@@ -1789,9 +1705,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:return_value=_make_assembled_model_response("ABCDEFGHIJ"),),):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/chat/completions"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/chat/completions")request_data = {"messages": [{"role": "user", "content": "hi"}],"guardrail_to_apply": guardrail,@@ -1806,8 +1720,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:passassert mock_post.await_count == 1, (- f"Expected exactly one guardrail call at end of stream, "- f"got {mock_post.await_count}"+ f"Expected exactly one guardrail call at end of stream, got {mock_post.await_count}")@pytest.mark.asyncio@@ -1836,9 +1749,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:finish_reason="stop" if i == len(chunks_data) - 1 else None,)- mock_post = AsyncMock(- return_value=_mock_guardrail_post_response(action="NONE", texts=["ABCDEF"])- )+ mock_post = AsyncMock(return_value=_mock_guardrail_post_response(action="NONE", texts=["ABCDEF"]))with (patch.object(guardrail.async_handler, "post", mock_post),@@ -1847,9 +1758,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:return_value=_make_assembled_model_response("ABCDEF"),),):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/chat/completions"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/chat/completions")request_data = {"messages": [{"role": "user", "content": "hi"}],"guardrail_to_apply": guardrail,@@ -1886,9 +1795,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:async def mock_stream():for i, content in enumerate(["A", "B", "C"]):- yield _make_stream_chunk(- content, finish_reason="stop" if i == 2 else None- )+ yield _make_stream_chunk(content, finish_reason="stop" if i == 2 else None)mock_post = AsyncMock(side_effect=httpx.ConnectError("connection refused"))@@ -1899,9 +1806,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:return_value=_make_assembled_model_response("ABC"),),):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/chat/completions"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/chat/completions")request_data = {"messages": [{"role": "user", "content": "hi"}],"guardrail_to_apply": guardrail,@@ -1937,16 +1842,10 @@ class TestGenericGuardrailAPIStreamingViaUnified:for event in _make_responses_stream_events("Hello world"):yield event- mock_post = AsyncMock(- return_value=_mock_guardrail_post_response(- action="NONE", texts=["Hello world"]- )- )+ mock_post = AsyncMock(return_value=_mock_guardrail_post_response(action="NONE", texts=["Hello world"]))with patch.object(guardrail.async_handler, "post", mock_post):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/v1/responses"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/v1/responses")request_data = {"input": "hi","guardrail_to_apply": guardrail,@@ -1963,8 +1862,7 @@ class TestGenericGuardrailAPIStreamingViaUnified:assert events_received == 6assert mock_post.await_count == 1, (- f"Expected exactly one guardrail call at end of /v1/responses stream, "- f"got {mock_post.await_count}"+ f"Expected exactly one guardrail call at end of /v1/responses stream, got {mock_post.await_count}")assert mock_post.await_args.kwargs["json"]["input_type"] == "response"@@ -1989,15 +1887,11 @@ class TestGenericGuardrailAPIStreamingViaUnified:yield eventmock_post = AsyncMock(- return_value=_mock_guardrail_post_response(- action="BLOCKED", blocked_reason="Responses content not allowed"- )+ return_value=_mock_guardrail_post_response(action="BLOCKED", blocked_reason="Responses content not allowed"))with patch.object(guardrail.async_handler, "post", mock_post):- user_api_key_dict = UserAPIKeyAuth(- api_key="test", request_route="/v1/responses"- )+ user_api_key_dict = UserAPIKeyAuth(api_key="test", request_route="/v1/responses")request_data = {"input": "hi","guardrail_to_apply": guardrail,@@ -2014,13 +1908,12 @@ class TestGenericGuardrailAPIStreamingViaUnified:assert "Responses content not allowed" in str(exc_info.value)+class TestToolSupport:"""Test tool handling in guardrail requests"""@pytest.mark.asyncio- async def test_builtin_tools_without_function_block_do_not_crash(- self, generic_guardrail- ):+ async def test_builtin_tools_without_function_block_do_not_crash(self, generic_guardrail):"""Built-in tools (code_interpreter, file_search) have no `function` block.Regression for a 500 where serializing them raised a Pydantic@@ -2041,9 +1934,7 @@ class TestToolSupport:mock_response.json.return_value = {"action": "NONE", "texts": ["hi"]}mock_response.raise_for_status = MagicMock()- with patch.object(- generic_guardrail.async_handler, "post", return_value=mock_response- ) as mock_post:+ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response) as mock_post:await generic_guardrail.apply_guardrail(inputs={"texts": ["hi"], "tools": tools},request_data={},@@ -2069,16 +1960,10 @@ class TestFailOnError:)@pytest.mark.asyncio- async def test_endpoint_error_continues_when_fail_on_error_false(- self, fail_open_guardrail- ):+ async def test_endpoint_error_continues_when_fail_on_error_false(self, fail_open_guardrail):"""A non-unreachable endpoint error (HTTP 400) is swallowed and the request proceeds unchanged."""- error = httpx.HTTPStatusError(- "bad request", request=MagicMock(), response=MagicMock(status_code=400)- )- with patch.object(- fail_open_guardrail.async_handler, "post", side_effect=error- ):+ error = httpx.HTTPStatusError("bad request", request=MagicMock(), response=MagicMock(status_code=400))+ with patch.object(fail_open_guardrail.async_handler, "post", side_effect=error):result = await fail_open_guardrail.apply_guardrail(inputs={"texts": ["hi"]},request_data={},@@ -2088,9 +1973,7 @@ class TestFailOnError:assert result == {"texts": ["hi"]}@pytest.mark.asyncio- async def test_internal_error_continues_without_calling_endpoint(- self, fail_open_guardrail- ):+ async def test_internal_error_continues_without_calling_endpoint(self, fail_open_guardrail):"""An error while building the request (here: invalid input_type) fails open too.Proves the request construction runs inside the protected block: the@@ -2107,9 +1990,7 @@ class TestFailOnError:assert result == {"texts": ["hi"]}@pytest.mark.asyncio- async def test_valid_block_still_blocks_when_fail_on_error_false(- self, fail_open_guardrail- ):+ async def test_valid_block_still_blocks_when_fail_on_error_false(self, fail_open_guardrail):"""Only a valid response acts: a BLOCKED decision still raises even with fail_on_error=False."""mock_response = MagicMock()mock_response.json.return_value = {@@ -2118,9 +1999,7 @@ class TestFailOnError:}mock_response.raise_for_status = MagicMock()- with patch.object(- fail_open_guardrail.async_handler, "post", return_value=mock_response- ):+ with patch.object(fail_open_guardrail.async_handler, "post", return_value=mock_response):with pytest.raises(GuardrailRaisedException):await fail_open_guardrail.apply_guardrail(inputs={"texts": ["hi"]},@@ -2131,9 +2010,7 @@ class TestFailOnError:@pytest.mark.asyncioasync def test_endpoint_error_raises_by_default(self, generic_guardrail):"""Default fail_on_error=True keeps blocking on a non-unreachable endpoint error."""- error = httpx.HTTPStatusError(- "bad request", request=MagicMock(), response=MagicMock(status_code=400)- )+ error = httpx.HTTPStatusError("bad request", request=MagicMock(), response=MagicMock(status_code=400))with patch.object(generic_guardrail.async_handler, "post", side_effect=error):with pytest.raises(Exception, match="Generic Guardrail API failed"):await generic_guardrail.apply_guardrail(@@ -2143,16 +2020,10 @@ class TestFailOnError:)@pytest.mark.asyncio- async def test_response_path_continues_when_fail_on_error_false(- self, fail_open_guardrail- ):+ async def test_response_path_continues_when_fail_on_error_false(self, fail_open_guardrail):"""fail_on_error governs the response path identically to the request path."""- error = httpx.HTTPStatusError(- "bad request", request=MagicMock(), response=MagicMock(status_code=400)- )- with patch.object(- fail_open_guardrail.async_handler, "post", side_effect=error- ):+ error = httpx.HTTPStatusError("bad request", request=MagicMock(), response=MagicMock(status_code=400))+ with patch.object(fail_open_guardrail.async_handler, "post", side_effect=error):result = await fail_open_guardrail.apply_guardrail(inputs={"texts": ["model output"]},request_data={},@@ -2171,9 +2042,7 @@ class TestFailOnError:}mock_response.raise_for_status = MagicMock()- with patch.object(- fail_open_guardrail.async_handler, "post", return_value=mock_response- ):+ with patch.object(fail_open_guardrail.async_handler, "post", return_value=mock_response):with pytest.raises(GuardrailRaisedException):await fail_open_guardrail.apply_guardrail(inputs={"texts": ["model output"]},diff --git a/tests/unit/proxy/response_api_endpoints/test_endpoints.py b/tests/unit/proxy/response_api_endpoints/test_endpoints.pyindex 5dac1d25572..c1ff8205a04 100644--- a/tests/unit/proxy/response_api_endpoints/test_endpoints.py+++ b/tests/unit/proxy/response_api_endpoints/test_endpoints.py@@ -43,27 +43,57 @@ async def test_streaming_upstream_errors_keep_the_client_protocol(model: Final = "gpt-6-astra"message: Final = "Upstream cannot complete this response"code: Final = {- "rate_limit": "rate_limit_exceeded", "numeric_rate_limit": "429",- "server_error": "server_error", "response_failed": "server_error", "cyber_policy": "cyber_policy",+ "rate_limit": "rate_limit_exceeded",+ "numeric_rate_limit": "429",+ "server_error": "server_error",+ "response_failed": "server_error",+ "cyber_policy": "cyber_policy",}[error_kind]error: Final = {"message": message, "code": code, "type": None, "param": "input"}- response: Final = {"id": "resp_upstream", "object": "response", "created_at": 1,- "status": "in_progress", "model": model, "output": [],- "parallel_tool_calls": True, "tool_choice": "auto", "tools": []}+ response: Final = {+ "id": "resp_upstream",+ "object": "response",+ "created_at": 1,+ "status": "in_progress",+ "model": model,+ "output": [],+ "parallel_tool_calls": True,+ "tool_choice": "auto",+ "tools": [],+ }created: Final = {"type": "response.created", "sequence_number": 0, "response": response}- tool_added: Final = {"type": "response.output_item.added", "sequence_number": 1, "output_index": 0,- "item": {"type": "function_call", "id": "fc_partial", "call_id": "call_partial",- "name": "read_file", "arguments": "", "status": "in_progress"}}- tool_delta: Final = {"type": "response.function_call_arguments.delta", "sequence_number": 2,- "item_id": "fc_partial", "output_index": 0, "delta": '{"path":"partial'}+ tool_added: Final = {+ "type": "response.output_item.added",+ "sequence_number": 1,+ "output_index": 0,+ "item": {+ "type": "function_call",+ "id": "fc_partial",+ "call_id": "call_partial",+ "name": "read_file",+ "arguments": "",+ "status": "in_progress",+ },+ }+ tool_delta: Final = {+ "type": "response.function_call_arguments.delta",+ "sequence_number": 2,+ "item_id": "fc_partial",+ "output_index": 0,+ "delta": '{"path":"partial',+ }failed: Final = (- {"type": "response.failed", "sequence_number": 9,- "response": {**response, "status": "failed", "error": error}}- if error_kind in ("response_failed", "cyber_policy") else {"type": "error", "error": error}+ {"type": "response.failed", "sequence_number": 9, "response": {**response, "status": "failed", "error": error}}+ if error_kind in ("response_failed", "cyber_policy")+ else {"type": "error", "error": error})- chat: Final = {"id": "chatcmpl_partial", "object": "chat.completion.chunk", "created": 1,- "model": model, "choices": [{"index": 0, "delta": {"content": "partial"},- "finish_reason": None}]}+ chat: Final = {+ "id": "chatcmpl_partial",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": model,+ "choices": [{"index": 0, "delta": {"content": "partial"}, "finish_reason": None}],+ }is_chat: Final = path == "/v1/chat/completions"partial: Final = path != "/v1/responses" or error_kind in ("numeric_rate_limit", "response_failed", "cyber_policy")response_events: Final = (created, tool_added, tool_delta, failed) if partial else (failed,)@@ -71,8 +101,12 @@ async def test_streaming_upstream_errors_keep_the_client_protocol(wire: Final = "".join("data: " + json.dumps(event) + "\n\n" for event in upstream_events)upstream_url: Final = "https://streaming.example/v1"router: Final = litellm.Router(- model_list=[{"model_name": model, "litellm_params": {- "model": "openai/" + model, "api_base": upstream_url, "api_key": "fixture-key"}}],+ model_list=[+ {+ "model_name": model,+ "litellm_params": {"model": "openai/" + model, "api_base": upstream_url, "api_key": "fixture-key"},+ }+ ],num_retries=0,)monkeypatch.setattr(ps, "llm_router", router)@@ -84,15 +118,18 @@ async def test_streaming_upstream_errors_keep_the_client_protocol()async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://testserver") as client:result: Final = await client.post(- path, json={- "model": model, "stream": True,+ path,+ json={+ "model": model,+ "stream": True,**({"messages": [{"role": "user", "content": "hello"}]} if is_chat else {"input": "hello"}),},)frames: Final = tuple(frame for frame in result.text.split("\n\n") if "data: " in frame)events: Final = tuple(json.loads(next(line[6:] for line in frame.splitlines() if line.startswith("data: ")))- for frame in frames if "data: [DONE]" not in frame+ for frame in frames+ if "data: [DONE]" not in frame)assert result.status_code == 200, result.text@@ -102,8 +139,10 @@ async def test_streaming_upstream_errors_keep_the_client_protocol(assert frames[-2].startswith("event: response.failed\n"), result.textif partial:assert [event["type"] for event in events] == [- "response.created", "response.output_item.added",- "response.function_call_arguments.delta", "response.failed",+ "response.created",+ "response.output_item.added",+ "response.function_call_arguments.delta",+ "response.failed",]assert events[2]["delta"] == tool_delta["delta"]assert events[-1]["sequence_number"] == events[-2]["sequence_number"] + 1@@ -113,10 +152,16 @@ async def test_streaming_upstream_errors_keep_the_client_protocol(assert events[0]["sequence_number"] == 0assert events[0]["response"]["id"].startswith("resp_")assert events[-1]["response"]["status"] == "failed"- assert events[-1]["response"]["error"]["code"] == {- "rate_limit": "rate_limit_exceeded", "numeric_rate_limit": "rate_limit_exceeded",- "server_error": "server_error", "response_failed": "server_error", "cyber_policy": "cyber_policy",- }[error_kind]+ assert (+ events[-1]["response"]["error"]["code"]+ == {+ "rate_limit": "rate_limit_exceeded",+ "numeric_rate_limit": "rate_limit_exceeded",+ "server_error": "server_error",+ "response_failed": "server_error",+ "cyber_policy": "cyber_policy",+ }[error_kind]+ )assert events[-1]["response"]["error"]["message"] == messageelse:assert events[0]["object"] == "chat.completion.chunk", result.text@@ -769,7 +814,9 @@ class TestResponsesWSFirstFrameModelAuth:replayed_input = [{"type": "reasoning", "id": "encitem_abc", "encrypted_content": "litellm_enc:abc;blob"}]payload = {"model": "gpt-4o-mini", "input": replayed_input, "previous_response_id": "resp_prev"}- first_frame = {"type": "response.create", "response": payload} if nested else {"type": "response.create", **payload}+ first_frame = (+ {"type": "response.create", "response": payload} if nested else {"type": "response.create", **payload}+ )raw_first_frame = json.dumps(first_frame)ws = MagicMock()@@ -1115,7 +1162,6 @@ class TestReadWSModelFromFirstFrameErrors:ws.close.assert_not_awaited()-@pytest.mark.parametrize("configured,expected",[@@ -2421,6 +2467,27 @@ class TestResponsesInputTokens:]assert token_request.tools == tools+ def test_item_cache_control_is_left_out_of_the_counted_messages(self):+ response, counter = self._post_input_tokens(+ {+ "model": "anthropic/claude-sonnet-4-6",+ "input": [+ {"role": "system", "content": "Long handbook", "cache_control": {"type": "ephemeral"}},+ {+ "role": "user",+ "content": "What does a reviewer do first?",+ "cache_control": {"type": "ephemeral"},+ },+ ],+ }+ )++ assert response.status_code == 200, response.text+ assert counter.call_args.kwargs["request"].messages == [+ {"role": "system", "content": "Long handbook"},+ {"role": "user", "content": "What does a reviewer do first?"},+ ]+def test_missing_model_returns_openai_400(self):response, counter = self._post_input_tokens({"input": "Hello"})diff --git a/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py b/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.pyindex 5563c2826bb..0280a6fcc0c 100644--- a/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py+++ b/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py@@ -45,7 +45,10 @@ async def test_async_response_api_handler_merges_trace_id_without_error():handler = LiteLLMCompletionTransformationHandler()async def fake_session_handler(- previous_response_id: str, litellm_completion_request: dict[str, object], instructions: str | None = None+ previous_response_id: str,+ litellm_completion_request: dict[str, object],+ instructions: str | None = None,+ request_kwargs: Mapping[str, object] | None = None,) -> dict[str, object]:litellm_completion_request["litellm_trace_id"] = "session-trace"return litellm_completion_request@@ -305,9 +308,7 @@ async def test_previous_response_id_without_instructions_carries_the_latest_onesdef _anthropic_sse(*events: Mapping[str, object]) -> bytes:- return b"".join(- f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode() for event in events- )+ return b"".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode() for event in events)def test_streamed_responses_over_anthropic_emit_the_responses_event_sequence(respx_mock: respx.MockRouter) -> None:diff --git a/tests/unit/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/unit/responses/litellm_completion_transformation/test_litellm_completion_responses.pyindex 7006feb22b2..6cdccf3958b 100644--- a/tests/unit/responses/litellm_completion_transformation/test_litellm_completion_responses.py+++ b/tests/unit/responses/litellm_completion_transformation/test_litellm_completion_responses.py@@ -1,9 +1,12 @@+import asyncioimport json+from collections.abc import Mapping, Sequencefrom copy import deepcopy-from typing import Final, Literal+from typing import Final, Literal, castimport pytestfrom openai.types.responses import ResponseFunctionToolCall+from openai.types.responses.response_create_params import ResponseInputParamfrom openai.types.responses.response_function_web_search import (ActionFind,ActionOpenPage,@@ -11,15 +14,22 @@ from openai.types.responses.response_function_web_search import (ActionSearchSource,ResponseFunctionWebSearch,)+from pydantic import TypeAdapterimport litellm+from litellm.integrations.anthropic_cache_control_hook import MAX_CACHE_CONTROL_BLOCKS, AnthropicCacheControlHookfrom litellm.litellm_core_utils.hidden_params import HIDDEN_PARAMS_ATTR-from litellm.litellm_core_utils.prompt_templates.factory import anthropic_messages_pt+from litellm.litellm_core_utils.prompt_templates.factory import (+ _bedrock_converse_messages_pt,+ anthropic_messages_pt,+)from litellm.responses.litellm_completion_transformation.transformation import (TOOL_CALLS_CACHE,+ ChatCompletionSession,LiteLLMCompletionResponsesConfig,)from litellm.types.llms.base import HiddenParams+from litellm.types.llms.openai import ResponsesAPIOptionalRequestParamsfrom litellm.types.responses.main import build_web_search_callfrom litellm.types.utils import (ChatCompletionMessageToolCall,@@ -5162,6 +5172,766 @@ async def test_bridge_rejects_untranslatable_tool_choice_with_a_400(stream: boolassert "tool_choice={'type': 'file_search'}" in str(exc_info.value)+def test_cache_control_on_user_message():+ """cache_control on a user message should be passed through to GenericChatCompletionMessage"""+ input_item = {+ "role": "user",+ "content": "Hello, world!",+ "cache_control": {"type": "ephemeral"},+ }++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item=input_item+ )++ assert len(result) == 1+ msg = result[0]+ assert msg["role"] == "user"+ assert msg.get("cache_control") == {"type": "ephemeral"}+++def test_cache_control_on_assistant_message():+ """cache_control on an assistant message should be passed through"""+ input_item = {+ "role": "assistant",+ "content": "I can help with that.",+ "cache_control": {"type": "ephemeral"},+ }++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item=input_item+ )++ assert len(result) == 1+ msg = result[0]+ assert msg["role"] == "assistant"+ assert msg.get("cache_control") == {"type": "ephemeral"}+++def test_no_cache_control_when_absent():+ """Messages without cache_control should not have the field set"""+ input_item = {+ "role": "user",+ "content": "Hello",+ }++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item=input_item+ )++ assert len(result) == 1+ msg = result[0]+ assert "cache_control" not in msg+++def test_cache_control_on_function_call_output():+ """cache_control on a function_call_output should be passed through to tool message"""+ TOOL_CALLS_CACHE.set_cache(+ key="call_123",+ value={+ "id": "call_123",+ "type": "function",+ "function": {"name": "get_weather", "arguments": '{"city": "NYC"}'},+ },+ )++ input_item = {+ "type": "function_call_output",+ "call_id": "call_123",+ "output": '{"temp": 72}',+ "cache_control": {"type": "ephemeral"},+ }++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item=input_item+ )++ # Should have assistant message + tool message+ assert len(result) == 2+ tool_msg = result[1]+ assert tool_msg["role"] == "tool"+ assert tool_msg.get("cache_control") == {"type": "ephemeral"}+++def test_cache_control_on_function_call():+ """cache_control on a function_call input should land on the tool call it builds"""+ input_item = {+ "type": "function_call",+ "call_id": "call_456",+ "name": "get_weather",+ "arguments": '{"city": "NYC"}',+ "cache_control": {"type": "ephemeral"},+ }++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item=input_item+ )++ assert len(result) == 1+ msg = result[0]+ assert msg["role"] == "assistant"+ assert "cache_control" not in msg+ assert msg["tool_calls"][0]["cache_control"] == {"type": "ephemeral"}+++def test_cache_control_preserved_in_full_input_transform():+ """cache_control should survive the full transform_responses_api_input_to_messages path"""+ input_items = [+ {+ "role": "user",+ "content": "What is the weather?",+ },+ {+ "role": "assistant",+ "content": "Let me check.",+ "cache_control": {"type": "ephemeral"},+ },+ {+ "role": "user",+ "content": "Thanks!",+ "cache_control": {"type": "ephemeral"},+ },+ ]++ result = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=input_items,+ responses_api_request={},+ item_cache_control=True,+ )++ # 3 messages, no system+ assert len(result) == 3+ assert "cache_control" not in result[0]+ assert result[1].get("cache_control") == {"type": "ephemeral"}+ assert result[2].get("cache_control") == {"type": "ephemeral"}+++def test_cache_control_propagated_to_last_content_block_for_list_content():+ """+ For Anthropic/Bedrock, an item-level cache_control over list content activates+ prompt caching only as a mark on the last content block, so the bridge moves+ it there instead of keeping a message-level copy the hook's census would also count.+ """+ input_item = {+ "role": "user",+ "content": [+ {"type": "input_text", "text": "first block"},+ {"type": "input_text", "text": "last block"},+ ],+ "cache_control": {"type": "ephemeral"},+ }++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item=input_item+ )++ assert len(result) == 1+ msg = result[0]+ assert "cache_control" not in msg+ assert isinstance(msg["content"], list)+ assert "cache_control" not in msg["content"][0]+ assert msg["content"][-1]["cache_control"] == {"type": "ephemeral"}+ assert AnthropicCacheControlHook.count_request_cache_breakpoints(result) == 1+++def test_cache_control_does_not_overwrite_existing_block_level_cache_control():+ """+ If the last content block already carries its own cache_control+ (preserved by _transform_responses_api_content_to_chat_completion_content),+ the message-level cache_control must not silently overwrite it.+ """+ input_item = {+ "role": "user",+ "content": [+ {+ "type": "input_text",+ "text": "last block",+ "cache_control": {"type": "ephemeral", "ttl": "1h"},+ },+ ],+ "cache_control": {"type": "ephemeral"},+ }++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item=input_item+ )++ assert len(result) == 1+ msg = result[0]+ assert "cache_control" not in msg+ assert msg["content"][-1]["cache_control"] == {"type": "ephemeral", "ttl": "1h"}+ assert AnthropicCacheControlHook.count_request_cache_breakpoints(result) == 1+++def test_function_call_cache_control_reaches_the_provider_tool_use_block():+ cache_control: Final = {"type": "ephemeral"}+ messages: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=[+ {"role": "user", "content": "Summarize the gateway latency report."},+ {+ "type": "function_call",+ "call_id": "call_cached_tool_use",+ "name": "get_latency_report",+ "arguments": '{"service": "gateway"}',+ "cache_control": cache_control,+ },+ {"type": "function_call_output", "call_id": "call_cached_tool_use", "output": "p50 120ms"},+ ],+ responses_api_request={},+ item_cache_control=True,+ )++ anthropic_turns: Final = anthropic_messages_pt(+ messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic"+ )+ tool_use_block: Final = anthropic_turns[1]["content"][0]+ assert tool_use_block["type"] == "tool_use"+ assert tool_use_block["cache_control"] == cache_control++ bedrock_blocks: Final = _bedrock_converse_messages_pt(+ messages=messages, model="us.anthropic.claude-sonnet-4-6", llm_provider="bedrock"+ )[1]["content"]+ tool_use_index: Final = next(index for index, block in enumerate(bedrock_blocks) if "toolUse" in block)+ assert "cachePoint" in bedrock_blocks[tool_use_index + 1]+++def test_assistant_text_merged_into_a_function_call_turn_keeps_its_cache_control():+ cache_control: Final = {"type": "ephemeral"}+ messages: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=[+ {"role": "user", "content": "Summarize the gateway latency report."},+ {+ "type": "function_call",+ "call_id": "call_merged_text",+ "name": "get_latency_report",+ "arguments": '{"service": "gateway"}',+ },+ {"role": "assistant", "content": "Looking that up now.", "cache_control": cache_control},+ {"type": "function_call_output", "call_id": "call_merged_text", "output": "p50 120ms"},+ ],+ responses_api_request={},+ item_cache_control=True,+ )++ assert len(messages) == 3+ assert messages[1]["cache_control"] == cache_control++ anthropic_turns: Final = anthropic_messages_pt(+ messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic"+ )+ text_block: Final = anthropic_turns[1]["content"][0]+ assert text_block["type"] == "text"+ assert text_block["cache_control"] == cache_control++ bedrock_blocks: Final = _bedrock_converse_messages_pt(+ messages=messages, model="us.anthropic.claude-sonnet-4-6", llm_provider="bedrock"+ )[1]["content"]+ assert any("cachePoint" in block for block in bedrock_blocks)+++def test_assistant_text_merged_behind_earlier_text_puts_cache_control_on_the_last_block():+ cache_control: Final = {"type": "ephemeral"}+ messages: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=[+ {"role": "user", "content": "Summarize the gateway latency report."},+ {+ "type": "function_call",+ "call_id": "call_two_texts",+ "name": "get_latency_report",+ "arguments": '{"service": "gateway"}',+ },+ {"role": "assistant", "content": "Looking that up now."},+ {"role": "assistant", "content": "One moment.", "cache_control": cache_control},+ {"type": "function_call_output", "call_id": "call_two_texts", "output": "p50 120ms"},+ ],+ responses_api_request={},+ item_cache_control=True,+ )++ merged_turn: Final = messages[1]+ assert "cache_control" not in merged_turn+ assert "cache_control" not in merged_turn["content"][0]+ assert merged_turn["content"][-1]["cache_control"] == cache_control+ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == 1+++def test_marked_assistant_text_merged_ahead_of_later_text_keeps_its_cache_control_on_its_block():+ cache_control: Final = {"type": "ephemeral"}+ messages: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=[+ {"role": "user", "content": "Summarize the gateway latency report."},+ {+ "type": "function_call",+ "call_id": "call_marked_first_text",+ "name": "get_latency_report",+ "arguments": '{"service": "gateway"}',+ },+ {"role": "assistant", "content": "Looking that up now.", "cache_control": cache_control},+ {"role": "assistant", "content": "One moment."},+ {"type": "function_call_output", "call_id": "call_marked_first_text", "output": "p50 120ms"},+ ],+ responses_api_request={},+ item_cache_control=True,+ )++ merged_turn: Final = messages[1]+ assert "cache_control" not in merged_turn+ assert merged_turn["content"][0]["cache_control"] == cache_control+ assert "cache_control" not in merged_turn["content"][-1]+ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == 1++ anthropic_turns: Final = anthropic_messages_pt(+ messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic"+ )+ blocks: Final = TypeAdapter(list[dict[str, object]]).validate_python(anthropic_turns[1]["content"])+ marked_blocks: Final = [block for block in blocks if block.get("cache_control")]+ assert len(marked_blocks) == 1+ assert marked_blocks[0]["text"] == "Looking that up now."+++_CLAUDE_ON_BEDROCK: Final = "us.anthropic.claude-sonnet-4-6"+_EPHEMERAL: Final = {"type": "ephemeral"}+++def _replayed_messages_from(+ turns: Sequence[Mapping[str, object]],+ current: Mapping[str, object],+ *,+ model: str = _CLAUDE_ON_BEDROCK,+ tools: Sequence[Mapping[str, object]] = (),+ **request_kwargs: object,+) -> Sequence[Mapping[str, object]]:+ async def session_lookup(previous_response_id: str) -> ChatCompletionSession:+ assert previous_response_id == "resp_marked_history"+ return ChatCompletionSession(messages=list(turns), litellm_session_id=None)++ request: Final = asyncio.run(+ LiteLLMCompletionResponsesConfig.async_responses_api_session_handler(+ previous_response_id="resp_marked_history",+ litellm_completion_request={+ "model": model,+ "custom_llm_provider": "bedrock",+ "messages": [current],+ **({"tools": list(tools)} if tools else {}),+ },+ instructions=None,+ session_lookup=session_lookup,+ request_kwargs=request_kwargs,+ )+ )+ return TypeAdapter(list[dict[str, object]]).validate_python(request["messages"])+++def test_a_replayed_turn_over_the_remaining_budget_yields_its_marks_while_older_turns_keep_theirs():+ three_marked_blocks: Final = [+ {"type": "text", "text": f"block {index}", "cache_control": _EPHEMERAL} for index in range(3)+ ]+ replayed_turns: Final = [+ {"role": "user", "content": "turn 0", "cache_control": _EPHEMERAL},+ {"role": "user", "content": "turn 1", "cache_control": _EPHEMERAL},+ {"role": "user", "content": three_marked_blocks},+ {"role": "user", "content": "turn 3", "cache_control": _EPHEMERAL},+ ]++ messages: Final = _replayed_messages_from(+ replayed_turns, {"role": "user", "content": "newest", "cache_control": _EPHEMERAL}+ )++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == MAX_CACHE_CONTROL_BLOCKS+ assert [AnthropicCacheControlHook._count_cache_control_blocks(message) for message in messages] == [1, 1, 0, 1, 1]+ assert messages[2] == {+ "role": "user",+ "content": [{"type": "text", "text": f"block {index}"} for index in range(3)],+ }+++def test_replayed_session_turns_yield_their_cache_control_to_the_newest_markers():+ replayed_turns: Final = [+ {"role": "user", "content": f"turn {index}", "cache_control": _EPHEMERAL} for index in range(5)+ ]++ messages: Final = _replayed_messages_from(+ replayed_turns, {"role": "user", "content": "newest", "cache_control": _EPHEMERAL}+ )+ assert ["cache_control" in message for message in messages] == [False, False, True, True, True, True]+ assert messages[0] == {"role": "user", "content": "turn 0"}+ assert messages[-1] == {"role": "user", "content": "newest", "cache_control": _EPHEMERAL}+++def test_a_marked_tool_takes_a_slot_from_the_replayed_turns():+ replayed_turns: Final = [+ {"role": "user", "content": f"turn {index}", "cache_control": _EPHEMERAL} for index in range(3)+ ]+ marked_tool: Final = {+ "type": "function",+ "function": {"name": "lookup", "parameters": {"type": "object"}},+ "cache_control": _EPHEMERAL,+ }++ messages: Final = _replayed_messages_from(+ replayed_turns, {"role": "user", "content": "newest", "cache_control": _EPHEMERAL}, tools=[marked_tool]+ )++ assert ["cache_control" in message for message in messages] == [False, True, True, True]+++ "request_kwargs",+ [{"cache_control": _EPHEMERAL}, {"extra_body": {"cache_control": _EPHEMERAL}}],+ ids=["top_level", "extra_body"],+)+def test_a_top_level_cache_control_takes_a_slot_from_the_replayed_turns(request_kwargs: Mapping[str, object]):+ replayed_turns: Final = [+ {"role": "user", "content": f"turn {index}", "cache_control": _EPHEMERAL} for index in range(3)+ ]++ messages: Final = _replayed_messages_from(+ replayed_turns, {"role": "user", "content": "newest", "cache_control": _EPHEMERAL}, **request_kwargs+ )++ assert ["cache_control" in message for message in messages] == [False, True, True, True]+++def test_a_null_cache_control_on_the_current_turn_takes_no_slot_from_the_replayed_turns():+ current: Final = {"role": "user", "content": [{"type": "text", "text": "newest", "cache_control": None}]}++ messages: Final = _replayed_messages_from(list(_marked_turns(4)), current)++ assert ["cache_control" in message for message in messages[:4]] == [True, True, True, True]++[email protected]("drop_params", [False, True])+def test_replayed_marks_a_provider_would_refuse_drop_with_or_without_drop_params(drop_params: bool):+ replayed_turns: Final = [{"role": "user", "content": "turn 0", "cache_control": {"type": "forever"}}]+ current: Final = {"role": "user", "content": "newest"}++ assert _replayed_messages_from(replayed_turns, current, drop_params=drop_params)[0] == {+ "role": "user",+ "content": "turn 0",+ }+++def test_replayed_tool_marks_drop_for_nova_without_drop_params():+ replayed_turns: Final = [+ {"role": "user", "content": "Summarize the gateway latency report."},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "get_latency_report", "arguments": "{}"},+ "cache_control": _EPHEMERAL,+ }+ ],+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "p50 12 ms", "cache_control": _EPHEMERAL},+ ]++ messages: Final = _replayed_messages_from(+ replayed_turns, {"role": "user", "content": "newest"}, model="us.amazon.nova-2-lite-v1:0"+ )++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == 0+ assert messages[2] == {"role": "tool", "tool_call_id": "call_1", "content": "p50 12 ms"}+++def test_replayed_marks_stay_untouched_for_a_target_without_cache_points():+ replayed_turns: Final = [+ {"role": "user", "content": f"turn {index}", "cache_control": _EPHEMERAL} for index in range(5)+ ]++ messages: Final = _replayed_messages_from(+ replayed_turns, {"role": "user", "content": "newest"}, model="meta.llama3-70b-instruct-v1:0"+ )++ assert messages[:5] == replayed_turns+++def _bridged_request(+ *items: Mapping[str, object],+ model: str = f"bedrock/{_CLAUDE_ON_BEDROCK}",+ custom_llm_provider: str = "bedrock",+ tools: Sequence[Mapping[str, object]] = (),+ **kwargs: object,+) -> Sequence[Mapping[str, object]]:+ request: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_request_to_chat_completion_request(+ model=model,+ input=cast(ResponseInputParam, list(items)), # cast-ok: cache_control is not a key of the input TypedDicts+ responses_api_request=cast( # cast-ok: cache_control is not a key of the tool TypedDicts+ ResponsesAPIOptionalRequestParams, {"instructions": "Be brief.", "tools": list(tools)}+ ),+ custom_llm_provider=custom_llm_provider,+ **kwargs,+ )+ return TypeAdapter(list[dict[str, object]]).validate_python(request["messages"])+++def _marked_turns(count: int) -> tuple[Mapping[str, object], ...]:+ return tuple({"role": "user", "content": f"turn {index}", "cache_control": _EPHEMERAL} for index in range(count))+++def test_marks_past_the_provider_cap_reach_it_as_sent_without_drop_params():+ messages: Final = _bridged_request(*_marked_turns(5))++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == MAX_CACHE_CONTROL_BLOCKS + 1++[email protected]("drop_params", [{"drop_params": True}, {"drop_params": "true"}], ids=["bool", "string"])+def test_marks_past_the_provider_cap_keep_the_newest_under_drop_params(drop_params: Mapping[str, object]):+ messages: Final = _bridged_request(*_marked_turns(5), **drop_params)++ assert ["cache_control" in message for message in messages] == [False, False, True, True, True, True]+ assert messages[1] == {"role": "user", "content": "turn 0"}+++def test_global_drop_params_keeps_the_newest_marks(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(litellm, "drop_params", True)++ messages: Final = _bridged_request(*_marked_turns(5))++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == MAX_CACHE_CONTROL_BLOCKS+++def test_a_marked_tool_takes_a_slot_from_the_request_marks_under_drop_params():+ marked_tool: Final = {+ "type": "function",+ "name": "lookup",+ "parameters": {"type": "object"},+ "cache_control": _EPHEMERAL,+ }++ messages: Final = _bridged_request(*_marked_turns(4), tools=[marked_tool], drop_params=True)++ assert ["cache_control" in message for message in messages] == [False, False, True, True, True]+++ "request_kwargs",+ [{"cache_control": _EPHEMERAL}, {"extra_body": {"cache_control": _EPHEMERAL}}],+ ids=["top_level", "extra_body"],+)+def test_a_top_level_cache_control_takes_a_slot_from_the_request_marks_under_drop_params(+ request_kwargs: Mapping[str, object],+):+ messages: Final = _bridged_request(*_marked_turns(4), drop_params=True, **request_kwargs)++ assert ["cache_control" in message for message in messages] == [False, False, True, True, True]+++def test_an_item_mark_replaces_a_null_mark_on_its_last_block():+ item: Final = {+ "role": "user",+ "content": [{"type": "input_text", "text": "x", "cache_control": None}],+ "cache_control": _EPHEMERAL,+ }++ assert _bridged_request(item)[1]["content"] == [{"type": "text", "text": "x", "cache_control": _EPHEMERAL}]+++_MARKED_TOOL_ROUND_TRIP: Final = (+ {"type": "function_call", "call_id": "call_1", "name": "lookup", "arguments": "{}", "cache_control": _EPHEMERAL},+ {"type": "function_call_output", "call_id": "call_1", "output": "42", "cache_control": _EPHEMERAL},+ {"role": "user", "content": "thanks", "cache_control": _EPHEMERAL},+)+++def _marked_tool_round_trip_marks(messages: Sequence[Mapping[str, object]]) -> tuple[bool, bool, bool]:+ tool_calls: Final = TypeAdapter(list[dict[str, object]]).validate_python(messages[1]["tool_calls"])+ return ("cache_control" in tool_calls[0], "cache_control" in messages[2], "cache_control" in messages[3])+++def test_nova_gets_no_marks_on_tool_calls_and_results_under_drop_params():+ nova: Final = "bedrock/us.amazon.nova-2-lite-v1:0"++ assert _marked_tool_round_trip_marks(_bridged_request(*_MARKED_TOOL_ROUND_TRIP, model=nova)) == (True, True, True)+ assert _marked_tool_round_trip_marks(_bridged_request(*_MARKED_TOOL_ROUND_TRIP, model=nova, drop_params=True)) == (+ False,+ False,+ True,+ )+++def test_claude_keeps_marks_on_tool_calls_and_results_under_drop_params():+ assert _marked_tool_round_trip_marks(_bridged_request(*_MARKED_TOOL_ROUND_TRIP, drop_params=True)) == (+ True,+ True,+ True,+ )++[email protected]("value", [1, "ephemeral", ["ephemeral"], {"type": "forever"}])+def test_a_cache_control_value_the_provider_would_refuse_reaches_it_as_sent_without_drop_params(value: object):+ assert _bridged_request({"role": "user", "content": "hi", "cache_control": value})[1] == {+ "role": "user",+ "content": "hi",+ "cache_control": value,+ }++[email protected]("value", [1, "ephemeral", ["ephemeral"], {"type": "forever"}])+def test_a_cache_control_value_the_provider_would_refuse_is_dropped_under_drop_params(value: object):+ assert _bridged_request({"role": "user", "content": "hi", "cache_control": value}, drop_params=True)[1] == {+ "role": "user",+ "content": "hi",+ }+++def test_drop_params_keeps_a_valid_mark_with_its_ttl_and_without_unknown_keys():+ marked: Final = {"role": "user", "content": "hi", "cache_control": {"type": "ephemeral", "ttl": "1h", "extra": 1}}++ assert _bridged_request(marked, drop_params=True)[1] == {+ "role": "user",+ "content": "hi",+ "cache_control": {"type": "ephemeral", "ttl": "1h"},+ }+++def test_a_marked_developer_item_reaches_a_claude_target_as_a_marked_system_message():+ developer: Final = {+ "role": "developer",+ "content": "Answer in French.",+ "name": "policy",+ "cache_control": _EPHEMERAL,+ }++ assert _bridged_request(developer)[1] == {+ "role": "system",+ "content": "Answer in French.",+ "cache_control": _EPHEMERAL,+ }+++ ("model", "custom_llm_provider"),+ [+ ("gemini/gemini-2.5-flash", "gemini"),+ ("mistral/mistral-small-latest", "mistral"),+ ("bedrock/meta.llama3-70b-instruct-v1:0", "bedrock"),+ ("openrouter/openai/gpt-5", "openrouter"),+ ("databricks/databricks-meta-llama-3-3-70b-instruct", "databricks"),+ ("snowflake/llama-claude-distill", "snowflake"),+ ],+)+def test_item_marks_stay_off_a_target_without_cache_points(model: str, custom_llm_provider: str):+ messages: Final = _bridged_request(+ {"role": "system", "content": "House rules", "cache_control": _EPHEMERAL},+ {"role": "developer", "content": "Answer in French.", "cache_control": _EPHEMERAL},+ {"role": "user", "content": "hi"},+ model=model,+ custom_llm_provider=custom_llm_provider,+ )++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == 0+ assert messages[2] == {"role": "developer", "content": "Answer in French."}+++ ("model", "custom_llm_provider"),+ [+ ("databricks/databricks-claude-sonnet-4", "databricks"),+ ("dashscope/qwen-plus", "dashscope"),+ ("minimax/MiniMax-M2", "minimax"),+ ("zai/glm-4.6", "zai"),+ ("sap/anthropic--claude-4-sonnet", "sap"),+ ("openrouter/anthropic/claude-sonnet-4.5", "openrouter"),+ ("openrouter/google/gemini-2.5-flash", "openrouter"),+ ("snowflake/claude-sonnet-4-5", "snowflake"),+ ("anthropic/my-gateway-model", "anthropic"),+ ],+)+def test_item_marks_reach_a_target_whose_chat_route_keeps_them(model: str, custom_llm_provider: str):+ messages: Final = _bridged_request(+ {"role": "system", "content": "House rules", "cache_control": _EPHEMERAL},+ model=model,+ custom_llm_provider=custom_llm_provider,+ )++ assert messages[1] == {"role": "system", "content": "House rules", "cache_control": _EPHEMERAL}+++def test_a_block_mark_reaches_a_target_without_cache_points_as_before():+ block: Final = {"type": "input_text", "text": "House rules", "cache_control": _EPHEMERAL}++ messages: Final = _bridged_request(+ {"role": "system", "content": [block]}, model="gemini/gemini-2.5-flash", custom_llm_provider="gemini"+ )++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == 1+++_APPLICATION_INFERENCE_PROFILE: Final = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123"+++def test_an_application_inference_profile_keeps_its_item_marks_without_drop_params():+ messages: Final = _bridged_request(+ {"role": "system", "content": "House rules", "cache_control": _EPHEMERAL},+ model=f"bedrock/{_APPLICATION_INFERENCE_PROFILE}",+ )++ assert messages[1] == {"role": "system", "content": "House rules", "cache_control": _EPHEMERAL}+++def test_an_application_inference_profile_gets_no_item_marks_under_drop_params():+ messages: Final = _bridged_request(+ {"role": "system", "content": "House rules", "cache_control": _EPHEMERAL},+ {"role": "user", "content": "Summarize the gateway latency report."},+ {+ "type": "function_call",+ "call_id": "call_1",+ "name": "get_latency_report",+ "arguments": "{}",+ "cache_control": _EPHEMERAL,+ },+ {"type": "function_call_output", "call_id": "call_1", "output": "p50 12 ms", "cache_control": _EPHEMERAL},+ model=f"bedrock/{_APPLICATION_INFERENCE_PROFILE}",+ drop_params=True,+ )++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == 0+++def test_the_shared_input_transform_keeps_every_item_mark_for_a_request_it_sends():+ messages: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast(ResponseInputParam, list(_marked_turns(5))), # cast-ok: cache_control is not an input TypedDict key+ responses_api_request={},+ item_cache_control=True,+ )++ assert AnthropicCacheControlHook.count_request_cache_breakpoints(messages) == MAX_CACHE_CONTROL_BLOCKS + 1+++def test_guardrails_and_token_counting_read_the_input_as_if_it_carried_no_item_marks():+ marked_turns: Final = list(_marked_turns(5))++ inspected: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast(ResponseInputParam, marked_turns), # cast-ok: cache_control is not an input TypedDict key+ responses_api_request={},+ )+ unmarked: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast(ResponseInputParam, [{"role": "user", "content": turn["content"]} for turn in marked_turns]),+ responses_api_request={},+ )++ assert inspected == unmarked+++def test_a_single_item_input_reads_the_same_whether_or_not_item_marks_are_kept():+ single_item: Final = cast( # cast-ok: a bare item where the input list belongs, as some clients send it+ ResponseInputParam, {"type": "message", "role": "user", "content": "hi"}+ )++ inspected: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=single_item, responses_api_request={}+ )+ sent: Final = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=single_item, responses_api_request={}, item_cache_control=True+ )++ assert inspected == sent++@pytest.mark.parametrize("index", [0, 1, 2])def test_convert_response_function_tool_call_keeps_the_index_it_is_given(index: int) -> None:item: Final = ResponseFunctionToolCall(diff --git a/tests/unit/responses/test_responses_prompt_management.py b/tests/unit/responses/test_responses_prompt_management.pyindex 60376408326..1e8880424ea 100644--- a/tests/unit/responses/test_responses_prompt_management.py+++ b/tests/unit/responses/test_responses_prompt_management.py@@ -620,6 +620,7 @@ def test_sync_prompt_swap_cross_provider_with_credentials_raises():with pytest.raises(litellm.BadRequestError, match="Refusing to send"):_apply_prompt_management_to_responses_call(input="hi",+ tools=None,model="anthropic/claude-haiku-4-5",custom_llm_provider="anthropic",litellm_logging_obj=logging_obj,