diff --git a/backend/routes/allowlist.py b/backend/routes/allowlist.py
index 00c4e0070e6..c7f389c36a4 100644
--- a/backend/routes/allowlist.py
+++ b/backend/routes/allowlist.py
@@ -51,6 +51,7 @@ BACKEND_PATH_PREFIXES: tuple[str, ...] = (
"/cache_settings",
"/coordination_redis/",
"/cost_tracking",
+ "/cost_optimization/",
"/cost/",
"/credentials",
"/credential",
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260920041500_add_policy_attachment_is_default/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260920041500_add_policy_attachment_is_default/migration.sql
new file mode 100644
index 00000000000..a6c45448d03
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260920041500_add_policy_attachment_is_default/migration.sql
@@ -0,0 +1 @@
+ALTER TABLE "LiteLLM_PolicyAttachmentTable" ADD COLUMN IF NOT EXISTS "is_default" BOOLEAN NOT NULL DEFAULT false;
diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
index d2032cec0d0..2d7e557a9d1 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
@@ -1419,6 +1419,7 @@ model LiteLLM_PolicyAttachmentTable {
models String[] @default([]) // Model names or patterns
tags String[] @default([]) // Tag patterns (e.g., ["healthcare", "prod-*"])
priority Int? // Explicit execution order
+ is_default Boolean @default(false) // Applied only when no non-default attachment matches
created_at DateTime @default(now())
created_by String?
updated_at DateTime @default(now()) @updatedAt
diff --git a/litellm/__init__.py b/litellm/__init__.py
index be8f59d210b..d202bd41cfe 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -1684,6 +1684,9 @@ if TYPE_CHECKING:
from .llms.bedrock.messages.mantle_transformation import (
AmazonMantleMessagesConfig as AmazonMantleMessagesConfig,
)
+ from .llms.bedrock_mantle.messages.transformation import (
+ BedrockMantleAnthropicMessagesConfig as BedrockMantleAnthropicMessagesConfig,
+ )
from .llms.together_ai.chat import TogetherAIConfig as TogetherAIConfig
from .llms.together_ai.chat.transformation import (
TogetherAIChatConfig as TogetherAIChatConfig,
diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py
index 9cfcb9e41f7..bca04a17250 100644
--- a/litellm/_lazy_imports_registry.py
+++ b/litellm/_lazy_imports_registry.py
@@ -176,6 +176,7 @@ LLM_CONFIG_NAMES: Final = (
"BedrockClaudePlatformMessagesConfig",
"AmazonAnthropicClaudeMessagesConfig",
"AmazonMantleMessagesConfig",
+ "BedrockMantleAnthropicMessagesConfig",
"TogetherAIConfig",
"TogetherAIChatConfig",
"NLPCloudConfig",
@@ -746,6 +747,10 @@ _LLM_CONFIGS_IMPORT_MAP: Final = {
".llms.bedrock.messages.mantle_transformation",
"AmazonMantleMessagesConfig",
),
+ "BedrockMantleAnthropicMessagesConfig": (
+ ".llms.bedrock_mantle.messages.transformation",
+ "BedrockMantleAnthropicMessagesConfig",
+ ),
"TogetherAIConfig": (".llms.together_ai.chat", "TogetherAIConfig"),
"TogetherAIChatConfig": (
".llms.together_ai.chat.transformation",
diff --git a/litellm/anthropic_beta_headers_config.json b/litellm/anthropic_beta_headers_config.json
index eb31cc17a15..1331de4c266 100644
--- a/litellm/anthropic_beta_headers_config.json
+++ b/litellm/anthropic_beta_headers_config.json
@@ -131,6 +131,41 @@
"web-fetch-2025-09-10": null,
"web-search-2025-03-05": null
},
+ "bedrock_mantle": {
+ "advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
+ "advisor-tool-2026-03-01": null,
+ "bash_20241022": null,
+ "bash_20250124": null,
+ "claude-code-20250219": "claude-code-20250219",
+ "code-execution-2025-08-25": null,
+ "compact-2026-01-12": "compact-2026-01-12",
+ "computer-use-2025-01-24": "computer-use-2025-01-24",
+ "computer-use-2025-11-24": "computer-use-2025-11-24",
+ "context-1m-2025-08-07": "context-1m-2025-08-07",
+ "context-management-2025-06-27": "context-management-2025-06-27",
+ "effort-2025-11-24": "effort-2025-11-24",
+ "fast-mode-2026-02-01": null,
+ "files-api-2025-04-14": null,
+ "fine-grained-tool-streaming-2025-05-14": "fine-grained-tool-streaming-2025-05-14",
+ "interleaved-thinking-2025-05-14": "interleaved-thinking-2025-05-14",
+ "mcp-client-2025-04-04": null,
+ "mcp-client-2025-11-20": null,
+ "mcp-servers-2025-12-04": null,
+ "output-128k-2025-02-19": "output-128k-2025-02-19",
+ "per-turn-control-2026-07-01": "per-turn-control-2026-07-01",
+ "prompt-caching-scope-2026-01-05": null,
+ "skills-2025-10-02": null,
+ "structured-output-2024-03-01": null,
+ "structured-outputs-2025-11-13": "structured-outputs-2025-11-13",
+ "text_editor_20241022": null,
+ "text_editor_20250124": null,
+ "thinking-binding-controls-2026-08-01": "thinking-binding-controls-2026-08-01",
+ "token-efficient-tools-2025-02-19": "token-efficient-tools-2025-02-19",
+ "tool-examples-2025-10-29": "tool-examples-2025-10-29",
+ "tool-search-tool-2025-10-19": "tool-search-tool-2025-10-19",
+ "web-fetch-2025-09-10": null,
+ "web-search-2025-03-05": "web-search-2025-03-05"
+ },
"vertex_ai": {
"advisor-tool-2026-03-01": null,
"advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
diff --git a/litellm/anthropic_beta_headers_manager.py b/litellm/anthropic_beta_headers_manager.py
index abce47c191e..7e7099a53b0 100644
--- a/litellm/anthropic_beta_headers_manager.py
+++ b/litellm/anthropic_beta_headers_manager.py
@@ -334,7 +334,7 @@ def update_headers_with_filtered_beta(
Updated headers dict
"""
existing_beta: Final = headers.get("anthropic-beta")
- if not existing_beta:
+ if existing_beta is None:
return headers
# Parse existing beta headers
diff --git a/litellm/constants.py b/litellm/constants.py
index 95ccad93284..72495b389d7 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -402,6 +402,7 @@ MINIMUM_PROMPT_CACHE_TOKEN_COUNT: Final = (
if MINIMUM_PROMPT_CACHE_TOKEN_COUNT_OVERRIDE is not None
else DEFAULT_MINIMUM_PROMPT_CACHE_TOKEN_COUNT
)
+PROMPT_CACHE_LOOKBACK_POSITIONS: Final = 20
DEFAULT_TRIM_RATIO: Final = float(
os.getenv("DEFAULT_TRIM_RATIO", 0.75)
) # default ratio of tokens to trim from the end of a prompt
diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py
index 4b456710057..49434befd4e 100644
--- a/litellm/experimental_mcp_client/client.py
+++ b/litellm/experimental_mcp_client/client.py
@@ -7,12 +7,13 @@ import base64
import hashlib
import json
import os
-from collections.abc import Awaitable, Callable, Generator
+from collections.abc import Awaitable, Callable, Generator, Sequence
from contextlib import AbstractAsyncContextManager
from functools import partial
from types import MappingProxyType
from typing import Any, Final, TypeAlias, TypeVar
+import anyio
import httpx2
from httpx2._client import UseClientDefault
from httpx2._types import AuthTypes
@@ -38,6 +39,8 @@ from mcp.types import (
ListPromptsResult,
ListResourcesResult,
ListResourceTemplatesResult,
+ PaginatedRequestParams,
+ PaginatedResult,
Prompt,
ResourceTemplate,
ServerNotification,
@@ -49,7 +52,12 @@ from mcp.types import Tool as MCPTool
from pydantic import AnyUrl
from litellm._logging import verbose_logger
-from litellm.constants import MCP_CLIENT_TIMEOUT, MCP_NPM_CACHE_DIR, MCP_TOOL_LISTING_TIMEOUT
+from litellm.constants import (
+ MCP_CLIENT_TIMEOUT,
+ MCP_NPM_CACHE_DIR,
+ MCP_TOOL_LISTING_MAX_PAGES,
+ MCP_TOOL_LISTING_TIMEOUT,
+)
from litellm.experimental_mcp_client.tools import list_tools_with_pagination
from litellm.llms.custom_httpx.http_handler import get_ssl_configuration
from litellm.proxy._experimental.mcp_server.mcp_debug import capture_upstream_error_response
@@ -147,6 +155,8 @@ def as_mcp_read_timeout(exc: BaseException) -> TimeoutError | None:
TSessionResult = TypeVar("TSessionResult")
+_ListPage = TypeVar("_ListPage", bound=PaginatedResult)
+_ListItem = TypeVar("_ListItem")
class _MCPHTTPClient(httpx2.AsyncClient):
@@ -793,6 +803,33 @@ class MCPClient:
# Return a default error result instead of raising
return self.error_tool_result(e)
+ async def _list_optional_pages(
+ self,
+ fetch_page: Callable[[PaginatedRequestParams | None], Awaitable[_ListPage]],
+ items_of: Callable[[_ListPage], Sequence[_ListItem]],
+ ) -> list[_ListItem]: # mutable-ok: existing list discovery API
+ items: Final[list[_ListItem]] = [] # mutable-ok: bounded iterative page accumulation
+ cursors: Final[set[str]] = set() # mutable-ok: constant-time detection of cursor cycles
+ cursor: str | None = None # rebind-ok: iterative traversal avoids recursion at the existing page cap
+ with anyio.fail_after(max(self.timeout, MCP_TOOL_LISTING_TIMEOUT)):
+ for page_index in range(MCP_TOOL_LISTING_MAX_PAGES):
+ try:
+ page = await fetch_page( # rebind-ok: each SDK page replaces the previous one
+ None if cursor is None else PaginatedRequestParams(cursor=cursor)
+ )
+ except MCPError as error:
+ if page_index > 0 and error.error.code == METHOD_NOT_FOUND:
+ raise RuntimeError("MCP list operation became unavailable during pagination") from error
+ raise
+ items.extend(items_of(page))
+ if not page.next_cursor:
+ return items
+ if page.next_cursor in cursors:
+ raise RuntimeError("MCP list pagination repeated a cursor")
+ cursors.add(page.next_cursor)
+ cursor = page.next_cursor
+ raise RuntimeError(f"MCP list pagination exceeded {MCP_TOOL_LISTING_MAX_PAGES} pages")
+
async def list_prompts(self, *, raise_on_error: bool = False) -> list[Prompt]:
"""List available prompts from the server."""
verbose_logger.debug("MCP client listing tools from %s", self.server_url or "stdio")
@@ -802,7 +839,11 @@ class MCPClient:
if capabilities is not None and capabilities.prompts is None:
return ListPromptsResult(prompts=[])
try:
- return await session.list_prompts()
+ return ListPromptsResult(
+ prompts=await self._list_optional_pages(
+ lambda params: session.list_prompts(params=params), lambda page: page.prompts
+ )
+ )
except MCPError as error:
if error.error.code != METHOD_NOT_FOUND:
raise
@@ -892,7 +933,11 @@ class MCPClient:
if capabilities is not None and capabilities.resources is None:
return ListResourcesResult(resources=[])
try:
- return await session.list_resources()
+ return ListResourcesResult(
+ resources=await self._list_optional_pages(
+ lambda params: session.list_resources(params=params), lambda page: page.resources
+ )
+ )
except MCPError as error:
if error.error.code != METHOD_NOT_FOUND:
raise
@@ -941,7 +986,12 @@ class MCPClient:
if capabilities is not None and capabilities.resources is None:
return ListResourceTemplatesResult(resource_templates=[]) # mutable-ok: MCP result payload
try:
- return await session.list_resource_templates()
+ return ListResourceTemplatesResult(
+ resource_templates=await self._list_optional_pages(
+ lambda params: session.list_resource_templates(params=params),
+ lambda page: page.resource_templates,
+ )
+ )
except MCPError as error:
if error.error.code != METHOD_NOT_FOUND:
raise
diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py
index 6c1b7946394..bf37b1be2e4 100644
--- a/litellm/litellm_core_utils/token_counter.py
+++ b/litellm/litellm_core_utils/token_counter.py
@@ -46,6 +46,8 @@ from litellm.types.llms.openai import (
AllMessageValues,
ChatCompletionDocumentObject,
ChatCompletionNamedToolChoiceParam,
+ ChatCompletionRedactedThinkingBlock,
+ ChatCompletionThinkingBlock,
ChatCompletionToolParam,
OpenAIMessageContentListBlock,
)
@@ -854,6 +856,8 @@ def _count_content_list(
content_list: str
| Iterable[
OpenAIMessageContentListBlock
+ | ChatCompletionThinkingBlock
+ | ChatCompletionRedactedThinkingBlock
| AnthropicMessagesTextParam
| AnthropicMessagesImageParam
| AnthropicMessagesDocumentParam
@@ -898,9 +902,9 @@ def _count_content_list(
use_default_image_token_count,
default_token_count,
)
- elif c["type"] == "thinking":
+ elif c["type"] in ("thinking", "redacted_thinking"):
# Claude extended thinking content block
- # Count the thinking text and skip signature (opaque signature blob)
+ # Count the thinking text and skip the opaque blobs (signature, redacted data)
thinking_text = str(c.get("thinking", ""))
if thinking_text:
num_tokens += count_function(thinking_text)
@@ -920,7 +924,8 @@ def _count_content_list(
raise ValueError(
f"Invalid content item type: {content_type}. "
f"Expected str or dict with 'type' field "
- f"(text, image_url, image, document, file, tool_use, tool_result, thinking, tool_reference)."
+ f"(text, image_url, image, document, file, tool_use, tool_result, thinking, redacted_thinking, "
+ f"tool_reference)."
)
return num_tokens
except Exception as e:
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
index 87a4801f987..d87cb0a64f5 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
@@ -651,6 +651,11 @@ def anthropic_messages_handler(
"display": "summarized",
}
+ resolved_api_base: Final = (
+ dynamic_api_base
+ if dynamic_api_base is not None and anthropic_messages_provider_config.uses_get_llm_provider_api_base()
+ else api_base
+ )
return base_llm_http_handler.anthropic_messages_handler(
model=model,
messages=strip_provider_specific_fields_from_anthropic_messages(messages),
@@ -662,7 +667,7 @@ def anthropic_messages_handler(
litellm_params=litellm_params,
logging_obj=litellm_logging_obj,
api_key=api_key,
- api_base=api_base,
+ api_base=resolved_api_base,
stream=stream,
kwargs=kwargs,
)
diff --git a/litellm/llms/base_llm/anthropic_messages/transformation.py b/litellm/llms/base_llm/anthropic_messages/transformation.py
index 8e7c22930fa..101a5e6c58c 100644
--- a/litellm/llms/base_llm/anthropic_messages/transformation.py
+++ b/litellm/llms/base_llm/anthropic_messages/transformation.py
@@ -128,6 +128,9 @@ class BaseAnthropicMessagesConfig(ABC):
"""
return True
+ def uses_get_llm_provider_api_base(self) -> bool:
+ return False
+
def get_async_streaming_response_iterator(
self,
model: str,
diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
index d2be1ad9156..4b52a3bafe6 100644
--- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
+++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
@@ -1,4 +1,4 @@
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Mapping
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, cast
@@ -445,13 +445,16 @@ class AmazonAnthropicClaudeMessagesConfig(
# Bedrock InvokeModel DOES support ``clear_tool_uses_20250919`` under the
# ``context-management-2025-06-27`` beta. AWS docs:
# https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages-tool-use.md
- _BEDROCK_INVOKE_SUPPORTED_CONTEXT_MANAGEMENT_EDITS: dict[str, str] = {
- "compact_20260112": ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value,
- "clear_tool_uses_20250919": ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value,
- }
+ _BEDROCK_INVOKE_SUPPORTED_CONTEXT_MANAGEMENT_EDITS: Mapping[str, str] = MappingProxyType(
+ {
+ "compact_20260112": ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value,
+ "clear_tool_uses_20250919": ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value,
+ }
+ )
- @staticmethod
+ @classmethod
def _filter_context_management_for_bedrock_invoke(
+ cls,
anthropic_messages_request: dict,
beta_set: set,
) -> None:
@@ -481,7 +484,7 @@ class AmazonAnthropicClaudeMessagesConfig(
anthropic_messages_request.pop("context_management", None)
return
- supported: Final = AmazonAnthropicClaudeMessagesConfig._BEDROCK_INVOKE_SUPPORTED_CONTEXT_MANAGEMENT_EDITS
+ supported: Final = cls._BEDROCK_INVOKE_SUPPORTED_CONTEXT_MANAGEMENT_EDITS
retained_edits: Final = [e for e in edits if isinstance(e, dict) and e.get("type") in supported]
if not retained_edits:
anthropic_messages_request.pop("context_management", None)
@@ -546,15 +549,16 @@ class AmazonAnthropicClaudeMessagesConfig(
if "tool-search-tool-2025-10-19" in beta_set:
beta_set.add("tool-examples-2025-10-29")
+ beta_provider: Final = self.custom_llm_provider or "bedrock"
filtered_betas: Final = sorted(
filter_and_transform_beta_headers(
beta_headers=list(beta_set),
- provider="bedrock",
+ provider=beta_provider,
)
)
dropped_user_betas: Final = sorted(
- b for b in user_beta_set if not filter_and_transform_beta_headers([b], provider="bedrock")
+ b for b in user_beta_set if not filter_and_transform_beta_headers([b], provider=beta_provider)
)
if dropped_user_betas:
verbose_logger.warning(
diff --git a/litellm/llms/bedrock_mantle/messages/__init__.py b/litellm/llms/bedrock_mantle/messages/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/llms/bedrock_mantle/messages/transformation.py b/litellm/llms/bedrock_mantle/messages/transformation.py
new file mode 100644
index 00000000000..6e975d072ed
--- /dev/null
+++ b/litellm/llms/bedrock_mantle/messages/transformation.py
@@ -0,0 +1,127 @@
+from collections.abc import Mapping
+from types import MappingProxyType
+from typing import Final
+
+from pydantic import TypeAdapter
+
+from litellm.llms.anthropic.experimental_pass_through.messages.transformation import (
+ DEFAULT_ANTHROPIC_API_VERSION,
+)
+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
+from litellm.llms.bedrock.common_utils import MANTLE_MESSAGES_PATH
+from litellm.llms.bedrock.messages.mantle_transformation import AmazonMantleMessagesConfig
+from litellm.llms.bedrock_mantle.common_utils import (
+ MANTLE_HOST_RE,
+ BedrockMantleAuthMixin,
+ resolve_mantle_region,
+)
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES
+from litellm.types.router import GenericLiteLLMParams
+
+_BASE_SUFFIXES_TO_STRIP: Final = (
+ MANTLE_MESSAGES_PATH,
+ "/v1/messages",
+ "/messages",
+ "/anthropic/v1",
+ "/openai/v1",
+ "/v1",
+)
+_BODY_FIELDS_MANTLE_READS_FROM_HEADERS: Final = frozenset({"anthropic_version", "anthropic_beta"})
+_ANTHROPIC_BETAS: Final = TypeAdapter(tuple[str, ...])
+_MANTLE_REQUEST: Final = TypeAdapter(dict[str, object])
+
+
+def build_mantle_native_messages_url(api_base: str | None, litellm_params: Mapping[str, object]) -> str:
+ region: Final = resolve_mantle_region(MappingProxyType({**litellm_params, "api_base": api_base}))
+ configured: Final = (
+ api_base or get_secret_str("BEDROCK_MANTLE_API_BASE") or f"https://bedrock-mantle.{region}.api.aws"
+ ).rstrip("/")
+ stripped: Final = next(
+ (configured[: -len(suffix)] for suffix in _BASE_SUFFIXES_TO_STRIP if configured.endswith(suffix)),
+ configured,
+ )
+ host: Final = f"https://bedrock-mantle.{region}.api.aws" if MANTLE_HOST_RE.match(stripped) else stripped
+ return f"{host}{MANTLE_MESSAGES_PATH}"
+
+
+class BedrockMantleAnthropicMessagesConfig(BedrockMantleAuthMixin, AmazonMantleMessagesConfig):
+ _BEDROCK_INVOKE_SUPPORTED_CONTEXT_MANAGEMENT_EDITS: Mapping[str, str] = MappingProxyType(
+ {
+ **AmazonMantleMessagesConfig._BEDROCK_INVOKE_SUPPORTED_CONTEXT_MANAGEMENT_EDITS,
+ "clear_thinking_20251015": ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value,
+ }
+ )
+
+ def __init__(self, aws_signer: BaseAWSLLM | None = None) -> None:
+ AmazonMantleMessagesConfig.__init__(self)
+ self._aws_signer = aws_signer or self
+
+ @property
+ def custom_llm_provider(self) -> str | None:
+ return "bedrock_mantle"
+
+ def uses_get_llm_provider_api_base(self) -> bool:
+ return True
+
+ def get_complete_url(
+ self,
+ api_base: str | None,
+ api_key: str | None,
+ model: str,
+ optional_params: dict,
+ litellm_params: dict,
+ stream: bool | None = None,
+ ) -> str:
+ return build_mantle_native_messages_url(api_base=api_base, litellm_params=litellm_params)
+
+ def validate_anthropic_messages_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: list[dict],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: str | None = None,
+ api_base: str | None = None,
+ ) -> tuple[dict, str | None]:
+ merged_headers, resolved_api_base = super().validate_anthropic_messages_environment(
+ headers=headers,
+ model=model,
+ messages=messages,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ api_key=api_key,
+ api_base=api_base,
+ )
+ if any(name.lower() == "anthropic-version" for name in merged_headers):
+ return merged_headers, resolved_api_base
+ return { # mutable-ok: the base class contract returns a dict the handler signs into in place
+ **merged_headers,
+ "anthropic-version": DEFAULT_ANTHROPIC_API_VERSION,
+ }, resolved_api_base
+
+ def transform_anthropic_messages_request(
+ self,
+ model: str,
+ messages: list[dict],
+ anthropic_messages_optional_request_params: dict,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> dict:
+ request: Final = _MANTLE_REQUEST.validate_python(
+ super().transform_anthropic_messages_request(
+ model=model,
+ messages=messages,
+ anthropic_messages_optional_request_params=anthropic_messages_optional_request_params,
+ litellm_params=litellm_params,
+ headers=headers,
+ ),
+ )
+ betas: Final = request.get("anthropic_beta")
+ if betas is not None:
+ header_betas: Final = ",".join(_ANTHROPIC_BETAS.validate_python(betas))
+ headers["anthropic-beta"] = header_betas # rebind-ok: the handler signs and sends this same dict
+ return { # mutable-ok: the base class contract returns the dict the handler serializes as the body
+ key: value for key, value in request.items() if key not in _BODY_FIELDS_MANTLE_READS_FROM_HEADERS
+ }
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index aa67dc58d69..97a38ac1657 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -42971,21 +42971,21 @@
"supports_web_search": false
},
"openrouter/deepseek/deepseek-v4-pro": {
- "input_cost_per_token": 9.22722e-07,
+ "input_cost_per_token": 9.19242e-07,
"input_cost_per_token_cache_hit": 4.4e-08,
"litellm_provider": "openrouter",
"max_input_tokens": 1048576,
"max_output_tokens": 384000,
"max_tokens": 384000,
"mode": "chat",
- "output_cost_per_token": 1.845444e-06,
+ "output_cost_per_token": 1.838484e-06,
"source": "https://openrouter.ai/api/v1/models",
"supports_function_calling": true,
"supports_prompt_caching": true,
"supports_reasoning": true,
"supports_response_schema": true,
"supports_tool_choice": true,
- "cache_read_input_token_cost": 7.68935e-08,
+ "cache_read_input_token_cost": 7.66035e-08,
"supports_audio_input": false,
"supports_pdf_input": false,
"supports_vision": false,
@@ -54441,16 +54441,19 @@
"zai.glm-4.7": {
"input_cost_per_token": 6e-07,
"litellm_provider": "bedrock_converse",
- "max_input_tokens": 200000,
- "max_output_tokens": 128000,
- "max_tokens": 128000,
+ "max_input_tokens": 203000,
+ "max_output_tokens": 4000,
+ "max_tokens": 4000,
"mode": "chat",
"output_cost_per_token": 2.2e-06,
"supports_function_calling": true,
"supports_reasoning": true,
"supports_system_messages": true,
"supports_tool_choice": true,
- "source": "https://aws.amazon.com/bedrock/pricing/"
+ "source": "https://aws.amazon.com/bedrock/pricing/",
+ "supports_audio_input": false,
+ "supports_response_schema": true,
+ "supports_vision": false
},
"zai.glm-5": {
"input_cost_per_token": 1e-06,
@@ -54470,16 +54473,19 @@
"zai.glm-4.7-flash": {
"input_cost_per_token": 7e-08,
"litellm_provider": "bedrock_converse",
- "max_input_tokens": 200000,
- "max_output_tokens": 128000,
- "max_tokens": 128000,
+ "max_input_tokens": 203000,
+ "max_output_tokens": 4000,
+ "max_tokens": 4000,
"mode": "chat",
"output_cost_per_token": 4e-07,
"supports_function_calling": true,
"supports_reasoning": true,
"supports_system_messages": true,
"supports_tool_choice": true,
- "source": "https://aws.amazon.com/bedrock/pricing/"
+ "source": "https://aws.amazon.com/bedrock/pricing/",
+ "supports_audio_input": false,
+ "supports_response_schema": true,
+ "supports_vision": false
},
"zai/glm-5": {
"cache_creation_input_token_cost": 0,
@@ -60558,6 +60564,34 @@
"supports_tool_choice": true,
"supports_vision": true
},
+ "bedrock_mantle/anthropic.claude-haiku-4-5": {
+ "cache_creation_input_token_cost": 1.25e-06,
+ "cache_creation_input_token_cost_above_1hr": 2e-06,
+ "cache_read_input_token_cost": 1e-07,
+ "input_cost_per_token": 1e-06,
+ "litellm_provider": "bedrock_mantle",
+ "supports_tool_search": true,
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 5e-06,
+ "source": "https://aws.amazon.com/about-aws/whats-new/2025/10/claude-4-5-haiku-anthropic-amazon-bedrock",
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "supports_native_structured_output": true,
+ "supports_parallel_tool_use_config": true,
+ "prompt_cache_min_tokens": 4096,
+ "input_cost_per_token_batches": 5e-07,
+ "output_cost_per_token_batches": 2.5e-06
+ },
"us.xai.grok-4.6": {
"input_cost_per_token": 2.2e-06,
"output_cost_per_token": 6.6e-06,
@@ -76803,7 +76837,7 @@
"max_tokens": 131072,
"mode": "chat",
"output_cost_per_token": 1.65e-05,
- "source": "https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-moonshot-ai-kimi-k3.html",
+ "source": "https://aws.amazon.com/bedrock/pricing/",
"supports_audio_input": false,
"supports_function_calling": true,
"supports_prompt_caching": true,
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 3a9bca926b0..397a82cfa45 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -3865,7 +3865,7 @@ if MCP_AVAILABLE:
try:
data: Final = json.loads(body)
return isinstance(data, dict) and data.get("method") == "initialize"
- except (json.JSONDecodeError, TypeError):
+ except (json.JSONDecodeError, UnicodeDecodeError, TypeError):
return False
def _extract_initialize_client_info(body: bytes) -> Implementation | None:
@@ -4791,7 +4791,7 @@ if MCP_AVAILABLE:
"MCP: detected JSON-RPC response POST (id=%s), skipping session lock to avoid deadlock",
_peeked.get("id"),
)
- except (json.JSONDecodeError, TypeError):
+ except (json.JSONDecodeError, UnicodeDecodeError, TypeError):
# Peek cap truncated the body, so it can't be fully parsed.
# Scan the top-level keys (depth-aware) instead of a flat
# substring search: a response's result payload may nest a
diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.json
index 06e157498aa..6f9a2d8c96d 100644
--- a/litellm/proxy/_lazy_openapi_snapshot.json
+++ b/litellm/proxy/_lazy_openapi_snapshot.json
@@ -34982,6 +34982,12 @@
"PolicyAttachmentCreateRequest": {
"description": "Request body for creating a policy attachment.",
"properties": {
+ "default": {
+ "default": false,
+ "description": "Apply this attachment only when no non-default attachment matches the request.",
+ "title": "Default",
+ "type": "boolean"
+ },
"keys": {
"anyOf": [
{
@@ -35113,6 +35119,12 @@
"description": "Who created the attachment.",
"title": "Created By"
},
+ "default": {
+ "default": false,
+ "description": "Apply this attachment only when no non-default attachment matches the request.",
+ "title": "Default",
+ "type": "boolean"
+ },
"definition_location": {
"default": "db",
"description": "Where this attachment is defined: 'db' (database) or 'config' (config.yaml).",
@@ -37141,6 +37153,12 @@
"PolicyAttachmentCreateRequest": {
"description": "Request body for creating a policy attachment.",
"properties": {
+ "default": {
+ "default": false,
+ "description": "Apply this attachment only when no non-default attachment matches the request.",
+ "title": "Default",
+ "type": "boolean"
+ },
"keys": {
"anyOf": [
{
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index 9a973755894..44d45dcd687 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -3216,7 +3216,9 @@ def _match_and_track_policies(
attachment_registry: Final = (
attachment_registry_override if attachment_registry_override is not None else get_attachment_registry()
)
- matches_with_reasons: Final = attachment_registry.get_attached_policies_with_reasons(context)
+ matches_with_reasons: Final = attachment_registry.get_attached_policies_with_reasons(
+ context, PolicyMatcher.policy_applies(context, policies_override)
+ )
matching_policy_names: Final = [m["policy_name"] for m in matches_with_reasons]
policy_reasons: Final = {m["policy_name"]: m["matched_via"] for m in matches_with_reasons}
@@ -3418,7 +3420,12 @@ async def add_guardrails_from_policy_engine(
_ANTHROPIC_API_HEADER_PROVIDERS: Final = ",".join(
- (LlmProviders.ANTHROPIC.value, LlmProviders.BEDROCK.value, LlmProviders.VERTEX_AI.value)
+ (
+ LlmProviders.ANTHROPIC.value,
+ LlmProviders.BEDROCK.value,
+ LlmProviders.BEDROCK_MANTLE.value,
+ LlmProviders.VERTEX_AI.value,
+ )
)
_ANTHROPIC_OAUTH_CREDENTIAL_PROVIDERS: Final = LlmProviders.ANTHROPIC.value
diff --git a/litellm/proxy/management_endpoints/prompt_caching_requests.py b/litellm/proxy/management_endpoints/prompt_caching_requests.py
new file mode 100644
index 00000000000..41255bd49b8
--- /dev/null
+++ b/litellm/proxy/management_endpoints/prompt_caching_requests.py
@@ -0,0 +1,184 @@
+from collections.abc import Callable, Mapping
+from datetime import datetime, timezone
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Annotated, Final
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, Json, TypeAdapter
+
+from litellm.proxy._types import CommonProxyErrors, UserAPIKeyAuth, user_api_key_has_admin_view
+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+from litellm.proxy.spend_tracking.savings import (
+ extract_cache_creation_tokens,
+ extract_cache_read_tokens,
+ marks_gateway_injection,
+ prompt_caching_savings_for_request,
+)
+from litellm.proxy.spend_tracking.spend_tracking_utils import (
+ _query_raw_rows, # pyright: ignore[reportPrivateUsage] # existing typed spend-query adapter; rows validated below
+)
+from litellm.types.integrations.anthropic_cache_control_hook import GATEWAY_INJECTED_CACHE_METADATA_KEY
+from litellm.types.management_endpoints.prompt_caching_requests import (
+ PromptCachingRequest,
+ PromptCachingRequestCursor,
+ PromptCachingRequestFilter,
+ PromptCachingRequestsResponse,
+)
+
+if TYPE_CHECKING:
+ from litellm.router import Router
+
+router: Final = APIRouter()
+
+
+def _numeric_token_sql(path: str) -> str:
+ value: Final = f"metadata #> '{{usage_object,{path}}}'"
+ return (
+ f"CASE WHEN jsonb_typeof({value}) = 'number' THEN ({value} #>> '{{}}')::numeric "
+ f"WHEN {value} = 'true'::jsonb THEN 1 WHEN {value} = 'false'::jsonb THEN 0 END"
+ )
+
+
+def _cache_tokens_sql(*paths: str) -> str:
+ candidates: Final = ", ".join(f"NULLIF(({_numeric_token_sql(path)}), 0)" for path in paths)
+ return f"TRUNC(COALESCE({candidates}, 0))"
+
+
+_CACHE_READ_SQL: Final = _cache_tokens_sql("cache_read_input_tokens", "prompt_tokens_details,cached_tokens")
+_CACHE_CREATION_SQL: Final = _cache_tokens_sql(
+ "cache_creation_input_tokens",
+ "prompt_tokens_details,cache_write_tokens",
+ "prompt_tokens_details,cache_creation_tokens",
+)
+_GATEWAY_INJECTED_SQL: Final = (
+ f"(jsonb_typeof(metadata->'{GATEWAY_INJECTED_CACHE_METADATA_KEY}') = 'string' "
+ f"AND (metadata->>'{GATEWAY_INJECTED_CACHE_METADATA_KEY}' = '' "
+ f"OR metadata->>'{GATEWAY_INJECTED_CACHE_METADATA_KEY}' = model_id))"
+)
+_FILTER_SQL: Final = MappingProxyType(
+ {
+ "all": f"({_GATEWAY_INJECTED_SQL} OR {_CACHE_READ_SQL} > 0 OR {_CACHE_CREATION_SQL} > 0)",
+ "injected": _GATEWAY_INJECTED_SQL,
+ "hits": f"{_CACHE_READ_SQL} > 0",
+ }
+)
+
+
+def prompt_caching_requests_sql(filter: PromptCachingRequestFilter) -> str:
+ return f"""
+ SELECT request_id, "startTime" AS start_time, "endTime" AS end_time,
+ model, model_id, custom_llm_provider, spend,
+ CASE WHEN jsonb_typeof(metadata->'usage_object') = 'object'
+ THEN metadata->'usage_object' END AS usage_object,
+ CASE WHEN jsonb_typeof(metadata->'cost_breakdown') = 'object'
+ THEN metadata->'cost_breakdown' END AS cost_breakdown,
+ CASE WHEN jsonb_typeof(metadata->'{GATEWAY_INJECTED_CACHE_METADATA_KEY}') = 'string'
+ THEN metadata->>'{GATEWAY_INJECTED_CACHE_METADATA_KEY}' END AS gateway_marker
+ FROM "LiteLLM_SpendLogs"
+ WHERE "startTime" >= ($1::text::timestamptz AT TIME ZONE 'UTC')
+ AND "startTime" <= ($2::text::timestamptz AT TIME ZONE 'UTC')
+ AND COALESCE(LOWER(cache_hit), 'false') != 'true'
+ AND {_FILTER_SQL[filter]}
+ AND ($4::text::timestamptz IS NULL OR
+ ("startTime", request_id) < (($4::text::timestamptz AT TIME ZONE 'UTC'), $5::text))
+ ORDER BY "startTime" DESC, request_id DESC
+ LIMIT $3::integer
+ """
+
+
+class _PromptCachingRow(BaseModel):
+ request_id: str
+ start_time: datetime
+ end_time: datetime
+ model: str
+ model_id: str | None
+ custom_llm_provider: str | None
+ spend: float
+ usage_object: Json[Mapping[str, object]] | Mapping[str, object] | None
+ cost_breakdown: Json[Mapping[str, object]] | Mapping[str, object] | None
+ gateway_marker: str | None
+
+
+_REQUEST_ROWS: Final = TypeAdapter(tuple[_PromptCachingRow, ...])
+
+
+def _request_result(row: _PromptCachingRow, llm_router: "Callable[[], Router | None]") -> PromptCachingRequest:
+ return PromptCachingRequest(
+ request_id=row.request_id,
+ start_time=row.start_time.replace(tzinfo=timezone.utc) if row.start_time.tzinfo is None else row.start_time,
+ model=row.model,
+ gateway_injected=marks_gateway_injection(
+ MappingProxyType({GATEWAY_INJECTED_CACHE_METADATA_KEY: row.gateway_marker}), row.model_id
+ ),
+ cache_read_tokens=extract_cache_read_tokens(row.usage_object),
+ cache_creation_tokens=extract_cache_creation_tokens(row.usage_object),
+ spend=row.spend,
+ net_savings=prompt_caching_savings_for_request(
+ model=row.model,
+ custom_llm_provider=row.custom_llm_provider,
+ usage_object=row.usage_object,
+ model_id=row.model_id,
+ llm_router=llm_router,
+ cost_breakdown=row.cost_breakdown,
+ billed_at=row.end_time,
+ ),
+ )
+
+
+@router.get(
+ "/cost_optimization/prompt_caching/requests",
+ tags=["Cost Optimization"], # mutable-ok: FastAPI's route API requires a list
+ response_model=PromptCachingRequestsResponse,
+)
+async def get_prompt_caching_requests(
+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
+ start_date: datetime,
+ end_date: datetime,
+ page_size: Annotated[int, Query(ge=1, le=100)] = 50,
+ filter: PromptCachingRequestFilter = "all",
+ cursor_start_time: datetime | None = None,
+ cursor_request_id: Annotated[str | None, Query(min_length=1)] = None,
+) -> PromptCachingRequestsResponse:
+ from litellm.proxy.proxy_server import llm_router, prisma_client
+
+ if not user_api_key_has_admin_view(user_api_key_dict):
+ raise HTTPException(status_code=403, detail="Only proxy admin roles can view prompt caching requests")
+ if (cursor_start_time is None) != (cursor_request_id is None):
+ raise HTTPException(status_code=400, detail="cursor_start_time and cursor_request_id must be provided together")
+ if prisma_client is None:
+ raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value)
+ start: Final = start_date.replace(tzinfo=timezone.utc) if start_date.tzinfo is None else start_date
+ end: Final = end_date.replace(tzinfo=timezone.utc) if end_date.tzinfo is None else end_date
+ if end < start:
+ raise HTTPException(status_code=400, detail="end_date must not be earlier than start_date")
+ cursor_time: Final = (
+ cursor_start_time.replace(tzinfo=timezone.utc)
+ if cursor_start_time is not None and cursor_start_time.tzinfo is None
+ else cursor_start_time
+ )
+ rows: Final = _REQUEST_ROWS.validate_python(
+ await _query_raw_rows(
+ prisma_client,
+ prompt_caching_requests_sql(filter),
+ start.isoformat(),
+ end.isoformat(),
+ page_size + 1,
+ cursor_time.isoformat() if cursor_time is not None else None,
+ cursor_request_id,
+ )
+ or ()
+ )
+
+ def current_router() -> "Router | None":
+ return llm_router
+
+ requests: Final = tuple(_request_result(row, current_router) for row in rows[:page_size])
+ has_more: Final = len(rows) > page_size
+ return PromptCachingRequestsResponse(
+ requests=requests,
+ page_size=page_size,
+ has_more=has_more,
+ next_cursor=PromptCachingRequestCursor(start_time=requests[-1].start_time, request_id=requests[-1].request_id)
+ if has_more
+ else None,
+ )
diff --git a/litellm/proxy/policy_engine/attachment_registry.py b/litellm/proxy/policy_engine/attachment_registry.py
index 3735c335bd4..d81471b3c1a 100644
--- a/litellm/proxy/policy_engine/attachment_registry.py
+++ b/litellm/proxy/policy_engine/attachment_registry.py
@@ -5,6 +5,7 @@ Attachments define WHERE policies apply, separate from the policy definitions.
This allows the same policy to be attached to multiple scopes.
"""
+from collections.abc import Callable
from datetime import datetime, timezone
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, TypedDict
@@ -119,35 +120,49 @@ class AttachmentRegistry:
models=attachment_data.get("models"),
tags=attachment_data.get("tags"),
priority=attachment_data.get("priority"),
+ default=attachment_data.get("default", False),
)
- def get_attached_policies(self, context: PolicyMatchContext) -> list[str]:
+ def get_attached_policies(
+ self,
+ context: PolicyMatchContext,
+ policy_applies: Callable[[str], bool] | None = None,
+ ) -> list[str]:
"""
Get list of policy names attached to the given context.
Args:
context: The request context to match against
+ policy_applies: Optional predicate; attachments whose policy does not apply are ignored
Returns:
List of policy names that are attached to matching scopes
"""
- return [r["policy_name"] for r in self.get_attached_policies_with_reasons(context)]
+ return [r["policy_name"] for r in self.get_attached_policies_with_reasons(context, policy_applies)]
- def get_attached_policies_with_reasons(self, context: PolicyMatchContext) -> list[PolicyAttachmentMatch]:
+ def get_attached_policies_with_reasons(
+ self,
+ context: PolicyMatchContext,
+ policy_applies: Callable[[str], bool] | None = None,
+ ) -> list[PolicyAttachmentMatch]:
"""
Get list of policy names and match reasons for the given context.
Returns a list of dicts with 'policy_name' and 'matched_via' keys.
The 'matched_via' describes which dimension caused the match.
+ Attachments whose policy fails `policy_applies` are dropped before defaults are considered.
"""
from litellm.proxy.policy_engine.policy_matcher import PolicyMatcher
+ in_scope: Final = tuple(
+ attachment
+ for attachment in self._attachments
+ if PolicyMatcher.scope_matches(scope=attachment.to_policy_scope(), context=context)
+ and (policy_applies is None or policy_applies(attachment.policy))
+ )
+ non_default: Final = tuple(attachment for attachment in in_scope if not attachment.default)
matching_attachments: Final = sorted(
- (
- attachment
- for attachment in self._attachments
- if PolicyMatcher.scope_matches(scope=attachment.to_policy_scope(), context=context)
- ),
+ non_default or tuple(attachment for attachment in in_scope if attachment.default),
key=_attachment_sort_key,
)
broadest_attachment_by_policy: Final = MappingProxyType(
@@ -169,6 +184,11 @@ class AttachmentRegistry:
@staticmethod
def _describe_match_reason(attachment: PolicyAttachment, context: PolicyMatchContext) -> str:
"""Describe why an attachment matched the context."""
+ reason: Final = AttachmentRegistry._describe_scope_match(attachment, context)
+ return f"default:{reason}" if attachment.default else reason
+
+ @staticmethod
+ def _describe_scope_match(attachment: PolicyAttachment, context: PolicyMatchContext) -> str:
from litellm.proxy.policy_engine.policy_matcher import PolicyMatcher
if attachment.is_global():
@@ -324,6 +344,7 @@ class AttachmentRegistry:
"models": attachment_request.models or [],
"tags": attachment_request.tags or [],
"priority": attachment_request.priority,
+ "is_default": attachment_request.default,
"created_at": datetime.now(timezone.utc),
"updated_at": datetime.now(timezone.utc),
"created_by": created_by,
@@ -340,6 +361,7 @@ class AttachmentRegistry:
models=attachment_request.models,
tags=attachment_request.tags,
priority=attachment_request.priority,
+ default=attachment_request.default,
)
self.add_attachment(attachment)
@@ -352,6 +374,7 @@ class AttachmentRegistry:
models=created_attachment.models or [],
tags=created_attachment.tags or [],
priority=created_attachment.priority,
+ default=created_attachment.is_default,
created_at=created_attachment.created_at,
updated_at=created_attachment.updated_at,
created_by=created_attachment.created_by,
@@ -429,6 +452,7 @@ class AttachmentRegistry:
models=attachment.models or [],
tags=attachment.tags or [],
priority=attachment.priority,
+ default=attachment.is_default,
created_at=attachment.created_at,
updated_at=attachment.updated_at,
created_by=attachment.created_by,
@@ -468,6 +492,7 @@ class AttachmentRegistry:
models=a.models or [],
tags=a.tags or [],
priority=a.priority,
+ default=a.is_default,
created_at=a.created_at,
updated_at=a.updated_at,
created_by=a.created_by,
@@ -502,6 +527,7 @@ class AttachmentRegistry:
models=(attachment_response.models if attachment_response.models else None),
tags=attachment_response.tags if attachment_response.tags else None,
priority=attachment_response.priority,
+ default=attachment_response.default,
)
for attachment_response in attachments
]
diff --git a/litellm/proxy/policy_engine/policy_endpoints.py b/litellm/proxy/policy_engine/policy_endpoints.py
index 1e30238c8b4..f4b38bea14e 100644
--- a/litellm/proxy/policy_engine/policy_endpoints.py
+++ b/litellm/proxy/policy_engine/policy_endpoints.py
@@ -61,6 +61,7 @@ def _config_attachment_to_db_response(index: int, attachment: PolicyAttachment)
models=attachment.models or [],
tags=attachment.tags or [],
priority=attachment.priority,
+ default=attachment.default,
definition_location="config",
)
diff --git a/litellm/proxy/policy_engine/policy_matcher.py b/litellm/proxy/policy_engine/policy_matcher.py
index 001e4115374..e0f558b5085 100644
--- a/litellm/proxy/policy_engine/policy_matcher.py
+++ b/litellm/proxy/policy_engine/policy_matcher.py
@@ -7,6 +7,7 @@ apply to a given request based on team alias, key alias, and model.
Policies are matched via policy_attachments which define WHERE each policy applies.
"""
+from collections.abc import Callable, Sequence
from typing import Final
from litellm._logging import verbose_proxy_logger
@@ -113,7 +114,7 @@ class PolicyMatcher:
verbose_proxy_logger.debug("AttachmentRegistry not initialized, returning empty list")
return []
- return registry.get_attached_policies(context)
+ return registry.get_attached_policies(context, PolicyMatcher.policy_applies(context))
@staticmethod
def get_matching_policies_from_registry(
@@ -130,9 +131,31 @@ class PolicyMatcher:
"""
return PolicyMatcher.get_matching_policies(context=context)
+ @staticmethod
+ def policy_applies(
+ context: PolicyMatchContext,
+ policies: dict[str, Policy] | None = None,
+ ) -> Callable[[str], bool]:
+ """Predicate telling whether a policy exists and its condition matches the context."""
+ resolved: Final = policies if policies is not None else PolicyMatcher._registry_policies()
+ return lambda policy_name: bool(
+ PolicyMatcher.get_policies_with_matching_conditions(
+ policy_names=(policy_name,),
+ context=context,
+ policies=resolved,
+ )
+ )
+
+ @staticmethod
+ def _registry_policies() -> dict[str, Policy]:
+ from litellm.proxy.policy_engine.policy_registry import get_policy_registry
+
+ registry: Final = get_policy_registry()
+ return registry.get_all_policies() if registry.is_initialized() else {}
+
@staticmethod
def get_policies_with_matching_conditions(
- policy_names: list[str],
+ policy_names: Sequence[str],
context: PolicyMatchContext,
policies: dict[str, Policy] | None = None,
) -> list[str]:
@@ -152,17 +175,12 @@ class PolicyMatcher:
List of policy names whose conditions match the context
"""
from litellm.proxy.policy_engine.condition_evaluator import ConditionEvaluator
- from litellm.proxy.policy_engine.policy_registry import get_policy_registry
- if policies is None:
- registry: Final = get_policy_registry()
- if not registry.is_initialized():
- return []
- policies = registry.get_all_policies()
+ resolved: Final = policies if policies is not None else PolicyMatcher._registry_policies()
matching_policies: Final = []
for policy_name in policy_names:
- policy = policies.get(policy_name)
+ policy = resolved.get(policy_name)
if policy is None:
continue
# Policy matches if it has no condition OR condition evaluates to True
diff --git a/litellm/proxy/policy_engine/policy_resolve_endpoints.py b/litellm/proxy/policy_engine/policy_resolve_endpoints.py
index a8a9856b833..898e42635c5 100644
--- a/litellm/proxy/policy_engine/policy_resolve_endpoints.py
+++ b/litellm/proxy/policy_engine/policy_resolve_endpoints.py
@@ -265,7 +265,9 @@ async def resolve_policies_for_context(
)
# Get matching policies with reasons
- match_results: Final = get_attachment_registry().get_attached_policies_with_reasons(context=context)
+ match_results: Final = get_attachment_registry().get_attached_policies_with_reasons(
+ context=context, policy_applies=PolicyMatcher.policy_applies(context)
+ )
if not match_results:
return PolicyResolveResponse(
diff --git a/litellm/proxy/policy_engine/response_retrieval.py b/litellm/proxy/policy_engine/response_retrieval.py
index d284c44397e..0f373b08056 100644
--- a/litellm/proxy/policy_engine/response_retrieval.py
+++ b/litellm/proxy/policy_engine/response_retrieval.py
@@ -84,7 +84,9 @@ def _retrieval_context(
def _post_call_pipelines_for_context(context: PolicyMatchContext) -> tuple[PolicyPipelines, Mapping[str, str]]:
- matches: Final = get_attachment_registry().get_attached_policies_with_reasons(context)
+ matches: Final = get_attachment_registry().get_attached_policies_with_reasons(
+ context, PolicyMatcher.policy_applies(context)
+ )
if not matches:
return (), MappingProxyType({})
applied_policy_names: Final = PolicyMatcher.get_policies_with_matching_conditions(
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 3a06753834a..04e6ee1d23c 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -601,6 +601,9 @@ from litellm.proxy.management_endpoints.model_management_endpoints import (
from litellm.proxy.management_endpoints.organization_endpoints import (
router as organization_router,
)
+from litellm.proxy.management_endpoints.prompt_caching_requests import (
+ router as prompt_caching_requests_router,
+)
from litellm.proxy.management_endpoints.router_settings_endpoints import (
router as router_settings_router,
)
@@ -19274,6 +19277,7 @@ app.include_router(workflow_management_router)
app.include_router(memory_router)
app.include_router(plugin_router)
app.include_router(cost_tracking_settings_router)
+app.include_router(prompt_caching_requests_router)
app.include_router(router_settings_router)
app.include_router(fallback_management_router)
app.include_router(cache_settings_router)
diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prisma
index d2032cec0d0..2d7e557a9d1 100644
--- a/litellm/proxy/schema.prisma
+++ b/litellm/proxy/schema.prisma
@@ -1419,6 +1419,7 @@ model LiteLLM_PolicyAttachmentTable {
models String[] @default([]) // Model names or patterns
tags String[] @default([]) // Tag patterns (e.g., ["healthcare", "prod-*"])
priority Int? // Explicit execution order
+ is_default Boolean @default(false) // Applied only when no non-default attachment matches
created_at DateTime @default(now())
created_by String?
updated_at DateTime @default(now()) @updatedAt
diff --git a/litellm/proxy/spend_tracking/savings.py b/litellm/proxy/spend_tracking/savings.py
index b7a2ac62844..fbcf9c78d3e 100644
--- a/litellm/proxy/spend_tracking/savings.py
+++ b/litellm/proxy/spend_tracking/savings.py
@@ -578,6 +578,56 @@ def autorouter_savings_for_logging_payload(
)
+def _request_savings_pricing(
+ model: str | None,
+ custom_llm_provider: str | None,
+ model_id: str | None,
+ llm_router: "Callable[[], Router | None] | None",
+) -> tuple[str | None, ModelInfo | None]:
+ router_instance: Final = llm_router() if llm_router else None
+ identity: Final = _resolve_model(model, custom_llm_provider)
+ pricing: Final = _effective_model_info(router_instance, model_id, model or "") or (
+ _model_info(identity) if identity else None
+ )
+ return identity.provider if identity else custom_llm_provider, pricing
+
+
+def _prompt_caching_savings(
+ pricing: ModelInfo | None,
+ provider: str | None,
+ usage_object: Mapping[str, object] | None,
+ cost_breakdown: Mapping[str, object] | None,
+ billed_at: datetime | str | None,
+) -> float | None:
+ usage: Final = _usage_from_spend_log(usage_object)
+ if pricing is None or usage is None:
+ return None
+ basis: Final = _pricing_basis(cost_breakdown)
+ result: Final = calculate_prompt_caching_savings(
+ model_info=pricing,
+ usage=usage,
+ custom_llm_provider=provider,
+ service_tier=basis.service_tier,
+ data_residency=basis.data_residency,
+ vertex_location=basis.vertex_location,
+ billed_at=_coerce_billed_at(billed_at),
+ )
+ return result if isfinite(result) else None
+
+
+def prompt_caching_savings_for_request(
+ model: str | None,
+ custom_llm_provider: str | None,
+ usage_object: Mapping[str, object] | None,
+ model_id: str | None = None,
+ llm_router: "Callable[[], Router | None] | None" = None,
+ cost_breakdown: Mapping[str, object] | None = None,
+ billed_at: datetime | str | None = None,
+) -> float | None:
+ request_pricing: Final = _request_savings_pricing(model, custom_llm_provider, model_id, llm_router)
+ return _prompt_caching_savings(request_pricing[1], request_pricing[0], usage_object, cost_breakdown, billed_at)
+
+
def compute_savings_spend(
model: str | None,
custom_llm_provider: str | None,
@@ -639,29 +689,12 @@ def compute_savings_spend(
# Deployment rates when the request came through one, public rates otherwise --
# `_effective_model_info` merges a deployment's configured prices over the built-in
# map, so a negotiated price is not silently replaced by the list rate.
- router_instance: Router | None = llm_router() if llm_router else None
- identity: Final = _resolve_model(model, custom_llm_provider)
- pricing: Final = _effective_model_info(router_instance, model_id, model or "") or (
- _model_info(identity) if identity else None
- )
+ request_pricing: Final = _request_savings_pricing(model, custom_llm_provider, model_id, llm_router)
+ provider: Final = request_pricing[0]
+ pricing: Final = request_pricing[1]
input_cost: Final = (_get_cost_per_unit(pricing, "input_cost_per_token") or 0.0) if pricing else 0.0
compression: Final = max(compression_saved_tokens, 0) * input_cost
- usage: Final = _usage_from_spend_log(usage_object)
- basis: Final = _pricing_basis(cost_breakdown)
- billed_at_datetime: Final = _coerce_billed_at(billed_at)
- prompt_caching: Final = (
- calculate_prompt_caching_savings(
- model_info=pricing,
- usage=usage,
- custom_llm_provider=identity.provider if identity else custom_llm_provider,
- service_tier=basis.service_tier,
- data_residency=basis.data_residency,
- vertex_location=basis.vertex_location,
- billed_at=billed_at_datetime,
- )
- if pricing is not None and usage is not None
- else 0.0
- )
+ prompt_caching: Final = _prompt_caching_savings(pricing, provider, usage_object, cost_breakdown, billed_at) or 0.0
gateway_injected_caching: Final = prompt_caching if gateway_injected_cache else 0.0
# The figure the logging path recorded wins, before the usage gate on purpose: a row
diff --git a/litellm/router_utils/prompt_caching_cache.py b/litellm/router_utils/prompt_caching_cache.py
index 39708e168f5..78fc5e3fe6d 100644
--- a/litellm/router_utils/prompt_caching_cache.py
+++ b/litellm/router_utils/prompt_caching_cache.py
@@ -4,12 +4,19 @@ Wrapper around router cache. Meant to store model id when prompt caching support
import hashlib
import json
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass
+from itertools import accumulate
from typing import TYPE_CHECKING, Any, Final, cast
+from pydantic import JsonValue, TypeAdapter
+from pydantic_core import to_jsonable_python
from typing_extensions import TypedDict
from litellm.caching.caching import DualCache
-from litellm.caching.in_memory_cache import InMemoryCache
+from litellm.constants import PROMPT_CACHE_LOOKBACK_POSITIONS
+from litellm.litellm_core_utils.logging_utils import truncate_base64_in_messages
+from litellm.litellm_core_utils.token_counter import offload_token_count
from litellm.types.llms.openai import AllMessageValues, ChatCompletionToolParam
if TYPE_CHECKING:
@@ -28,27 +35,102 @@ class PromptCachingCacheValue(TypedDict):
model_id: str
+PROMPT_CACHE_PIN_TTL_SECONDS: Final = 300
+_TOOL_RUN_BLOCK_TYPES: Final = frozenset({"tool_use", "tool_result"})
+_PREFIX_ADAPTER: Final = TypeAdapter(tuple[Mapping[str, JsonValue], ...])
+_TOOLS_ADAPTER: Final = TypeAdapter(tuple[JsonValue, ...])
+_PINS_ADAPTER: Final[TypeAdapter[tuple[JsonValue, ...] | None]] = TypeAdapter(tuple[JsonValue, ...] | None)
+
+
+@dataclass(frozen=True, slots=True)
+class PrefixPosition:
+ cache_key: str
+ position: int
+
+
+def _sorted_pairs(pairs: Iterable[tuple[str, JsonValue]]) -> tuple[tuple[str, JsonValue], ...]:
+ return tuple(sorted(pairs, key=lambda pair: pair[0]))
+
+
+def _canonical_bytes(value: object) -> bytes:
+ return json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
+
+
+def _block_unit(
+ envelope: tuple[tuple[str, JsonValue], ...], message_run_type: str | None, block: JsonValue
+) -> tuple[bytes, str | None]:
+ if not isinstance(block, dict):
+ return _canonical_bytes((envelope, block)), message_run_type
+ block_type: Final = block.get("type")
+ block_run_type: Final = block_type if isinstance(block_type, str) and block_type in _TOOL_RUN_BLOCK_TYPES else None
+ stripped: Final = _sorted_pairs(item for item in block.items() if item[0] != "cache_control")
+ return _canonical_bytes((envelope, stripped)), message_run_type or block_run_type
+
+
+def _message_units(message: Mapping[str, JsonValue]) -> tuple[tuple[bytes, str | None], ...]:
+ envelope: Final = _sorted_pairs(item for item in message.items() if item[0] not in ("content", "cache_control"))
+ message_run_type: Final = "tool_result" if message.get("role") == "tool" else None
+ content: Final = message.get("content")
+ if isinstance(content, list) and content:
+ return tuple(_block_unit(envelope, message_run_type, block) for block in content)
+ if isinstance(content, str) and content:
+ return ((_canonical_bytes((envelope, (("text", content), ("type", "text")))), message_run_type),)
+ return ((_canonical_bytes((envelope, None)), message_run_type),)
+
+
+def _chain_digest(digest: bytes, unit: bytes) -> bytes:
+ return hashlib.sha256(digest + unit).digest()
+
+
+def _seed(tools: Sequence[ChatCompletionToolParam] | None) -> bytes:
+ if tools is None:
+ return hashlib.sha256(b"").digest()
+ return hashlib.sha256(
+ _canonical_bytes(
+ _TOOLS_ADAPTER.validate_python(to_jsonable_python(tools, serialize_unknown=True, bytes_mode="base64"))
+ )
+ ).digest()
+
+
+def _positions_of(
+ prefix: tuple[Mapping[str, JsonValue], ...], tools: Sequence[ChatCompletionToolParam] | None
+) -> tuple[PrefixPosition, ...]:
+ units: Final = tuple(unit for message in prefix for unit in _message_units(message))
+ digests: Final = tuple(accumulate((unit_bytes for unit_bytes, _ in units), _chain_digest, initial=_seed(tools)))[1:]
+ run_types: Final = tuple(run_type for _, run_type in units)
+ positions: Final = accumulate(
+ 0 if run_type is not None and run_type == previous else 1
+ for run_type, previous in zip(run_types, (None, *run_types[:-1]))
+ )
+ return tuple(
+ PrefixPosition(cache_key=f"deployment:{digest.hex()}:prompt_caching", position=position)
+ for digest, position in zip(digests, positions)
+ )
+
+
+def _lookback_keys(positions: tuple[PrefixPosition, ...]) -> tuple[str, ...]:
+ if not positions:
+ return ()
+ oldest_probed_position: Final = positions[-1].position - PROMPT_CACHE_LOOKBACK_POSITIONS
+ return tuple(entry.cache_key for entry in reversed(positions) if entry.position > oldest_probed_position)
+
+
+def _pinned_value(value: JsonValue) -> PromptCachingCacheValue | None:
+ if not isinstance(value, dict):
+ return None
+ model_id: Final = value.get("model_id")
+ return PromptCachingCacheValue(model_id=model_id) if isinstance(model_id, str) else None
+
+
+def _first_pin(values: tuple[JsonValue, ...] | None) -> PromptCachingCacheValue | None:
+ if values is None:
+ return None
+ return next((pin for pin in map(_pinned_value, values) if pin is not None), None)
+
+
class PromptCachingCache:
def __init__(self, cache: DualCache):
self.cache = cache
- self.in_memory_cache = InMemoryCache()
-
- @staticmethod
- def serialize_object(obj: Any) -> object:
- """Helper function to serialize Pydantic objects, dictionaries, or fallback to string."""
- if hasattr(obj, "dict"):
- # If the object is a Pydantic model, use its `dict()` method
- return obj.dict()
- elif isinstance(obj, dict):
- # If the object is a dictionary, serialize it with sorted keys
- return json.dumps(obj, sort_keys=True, separators=(",", ":")) # Standardize serialization
-
- elif isinstance(obj, list):
- # Serialize lists by ensuring each element is handled properly
- return [PromptCachingCache.serialize_object(item) for item in obj]
- elif isinstance(obj, (int, float, bool)):
- return obj # Keep primitive types as-is
- return str(obj)
@staticmethod
def extract_cacheable_prefix(
@@ -140,114 +222,116 @@ class PromptCachingCache:
return cacheable_prefix
@staticmethod
- def get_prompt_caching_cache_key(
+ def prefix_positions(
messages: list[AllMessageValues] | None,
- tools: list[ChatCompletionToolParam] | None,
- ) -> str | None:
- if messages is None and tools is None:
- return None
+ tools: Sequence[ChatCompletionToolParam] | None,
+ ) -> tuple[PrefixPosition, ...]:
+ """
+ One cache key per content block of the cacheable prefix, oldest block first.
- # Extract cacheable prefix from messages (only include up to last cache_control block)
- cacheable_messages = None
- if messages is not None:
- cacheable_messages = PromptCachingCache.extract_cacheable_prefix(messages)
- # If no cacheable prefix found, return None (can't cache)
- if not cacheable_messages:
- return None
+ Each key hashes the prefix content up to and including that block, with cache_control markers
+ left out, so the key of a block is the same whichever turn's breakpoint the prefix ends at.
+ String content hashes like a single text block, which is how the provider treats it and how
+ Claude Code re-sends a previously marked message. `position` counts a run of consecutive
+ tool_use (or tool_result) blocks as one, matching the provider's lookback window.
- # Use serialize_object for consistent and stable serialization
- data_to_hash: Final = {}
- if cacheable_messages is not None:
- serialized_messages: Final = PromptCachingCache.serialize_object(cacheable_messages)
- data_to_hash["messages"] = serialized_messages
- if tools is not None:
- serialized_tools: Final = PromptCachingCache.serialize_object(tools)
- data_to_hash["tools"] = serialized_tools
-
- # Combine serialized data into a single string
- data_to_hash_str: Final = json.dumps(
- data_to_hash,
- sort_keys=True,
- separators=(",", ":"),
+ The prefix is hashed in the shape the success event sees it, with long base64 data URIs
+ already replaced by their size placeholder, so a request carrying the raw image bytes
+ derives the same keys the write side stored.
+ """
+ if not messages:
+ return ()
+ return _positions_of(
+ _PREFIX_ADAPTER.validate_python(
+ to_jsonable_python(
+ truncate_base64_in_messages(PromptCachingCache.extract_cacheable_prefix(messages)),
+ serialize_unknown=True,
+ bytes_mode="base64",
+ )
+ ),
+ tools,
)
- # Create a hash of the serialized data for a stable cache key
- hashed_data: Final = hashlib.sha256(data_to_hash_str.encode()).hexdigest()
- return f"deployment:{hashed_data}:prompt_caching"
+ @staticmethod
+ async def async_prefix_positions(
+ messages: list[AllMessageValues] | None,
+ tools: Sequence[ChatCompletionToolParam] | None,
+ ) -> tuple[PrefixPosition, ...]:
+ if not messages:
+ return ()
+ return await offload_token_count(PromptCachingCache.prefix_positions)(messages, tools)
+
+ @staticmethod
+ def get_prompt_caching_cache_key(
+ messages: list[AllMessageValues] | None,
+ tools: Sequence[ChatCompletionToolParam] | None,
+ ) -> str | None:
+ positions: Final = PromptCachingCache.prefix_positions(messages, tools)
+ return positions[-1].cache_key if positions else None
def add_model_id(
self,
model_id: str,
messages: list[AllMessageValues] | None,
- tools: list[ChatCompletionToolParam] | None,
+ tools: Sequence[ChatCompletionToolParam] | None,
) -> None:
- if messages is None and tools is None:
- return
-
cache_key: Final = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
- # If no cacheable prefix found, don't cache (can't generate cache key)
if cache_key is None:
return
- self.cache.set_cache(cache_key, PromptCachingCacheValue(model_id=model_id), ttl=300)
- return
+ self.cache.set_cache(cache_key, PromptCachingCacheValue(model_id=model_id), ttl=PROMPT_CACHE_PIN_TTL_SECONDS)
async def async_add_model_id(
self,
model_id: str,
messages: list[AllMessageValues] | None,
- tools: list[ChatCompletionToolParam] | None,
+ tools: Sequence[ChatCompletionToolParam] | None,
) -> None:
- if messages is None and tools is None:
- return
-
- cache_key: Final = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
- # If no cacheable prefix found, don't cache (can't generate cache key)
- if cache_key is None:
+ positions: Final = await PromptCachingCache.async_prefix_positions(messages, tools)
+ if not positions:
return
await self.cache.async_set_cache(
- cache_key,
+ positions[-1].cache_key,
PromptCachingCacheValue(model_id=model_id),
- ttl=300, # store for 5 minutes
+ ttl=PROMPT_CACHE_PIN_TTL_SECONDS,
)
- return
async def async_get_model_id(
self,
messages: list[AllMessageValues] | None,
- tools: list[ChatCompletionToolParam] | None,
+ tools: Sequence[ChatCompletionToolParam] | None,
) -> PromptCachingCacheValue | None:
"""
- Get model ID from cache using the cacheable prefix.
-
- The cache key is based on the cacheable prefix (everything up to and including
- the last cache_control block), so requests with the same cacheable prefix but
- different user messages will have the same cache key.
+ Find the deployment that last served this prefix, walking back from the breakpoint the
+ same way the provider cache does, so a breakpoint that moved forward since the last
+ turn still lands on the deployment whose cache holds the earlier prefix.
"""
- if messages is None and tools is None:
+ cache_keys: Final = _lookback_keys(await PromptCachingCache.async_prefix_positions(messages, tools))
+ if not cache_keys:
return None
- # Generate cache key using cacheable prefix
- cache_key: Final = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
- if cache_key is None:
- return None
-
- # Perform cache lookup
- cache_result: Final = await self.cache.async_get_cache(key=cache_key)
- return cache_result
+ return _first_pin(
+ _PINS_ADAPTER.validate_python(
+ await self.cache.async_batch_get_cache(
+ keys=list(cache_keys), # mutable-ok: DualCache.async_batch_get_cache only takes a list
+ )
+ )
+ )
def get_model_id(
self,
messages: list[AllMessageValues] | None,
- tools: list[ChatCompletionToolParam] | None,
+ tools: Sequence[ChatCompletionToolParam] | None,
) -> PromptCachingCacheValue | None:
- if messages is None and tools is None:
+ cache_keys: Final = _lookback_keys(PromptCachingCache.prefix_positions(messages, tools))
+ if not cache_keys:
return None
- cache_key: Final = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
- # If no cacheable prefix found, return None (can't cache)
- if cache_key is None:
- return None
-
- return self.cache.get_cache(cache_key)
+ return _first_pin(
+ _PINS_ADAPTER.validate_python(
+ self.cache.batch_get_cache(
+ keys=list(cache_keys), # mutable-ok: DualCache.batch_get_cache only takes a list
+ )
+ )
+ )
diff --git a/litellm/types/management_endpoints/prompt_caching_requests.py b/litellm/types/management_endpoints/prompt_caching_requests.py
new file mode 100644
index 00000000000..e72183a113b
--- /dev/null
+++ b/litellm/types/management_endpoints/prompt_caching_requests.py
@@ -0,0 +1,35 @@
+from datetime import datetime
+from typing import Literal, TypeAlias
+
+from pydantic import BaseModel, ConfigDict
+
+PromptCachingRequestFilter: TypeAlias = Literal["all", "injected", "hits"]
+
+
+class PromptCachingRequest(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ request_id: str
+ start_time: datetime
+ model: str
+ gateway_injected: bool
+ cache_read_tokens: int
+ cache_creation_tokens: int
+ spend: float
+ net_savings: float | None
+
+
+class PromptCachingRequestCursor(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ start_time: datetime
+ request_id: str
+
+
+class PromptCachingRequestsResponse(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ requests: tuple[PromptCachingRequest, ...]
+ page_size: int
+ has_more: bool
+ next_cursor: PromptCachingRequestCursor | None
diff --git a/litellm/types/proxy/policy_engine/policy_types.py b/litellm/types/proxy/policy_engine/policy_types.py
index 66e5fbb4b49..73eeffa3585 100644
--- a/litellm/types/proxy/policy_engine/policy_types.py
+++ b/litellm/types/proxy/policy_engine/policy_types.py
@@ -294,6 +294,10 @@ class PolicyAttachment(BaseModel):
le=2147483647,
description="Explicit execution order, lower runs first. Prioritised attachments run before those without one.",
)
+ default: bool = Field(
+ default=False,
+ description="Apply this attachment only when no non-default attachment matches the request.",
+ )
model_config = ConfigDict(extra="forbid")
diff --git a/litellm/types/proxy/policy_engine/resolver_types.py b/litellm/types/proxy/policy_engine/resolver_types.py
index e6f501ed4b5..ebdedb98b12 100644
--- a/litellm/types/proxy/policy_engine/resolver_types.py
+++ b/litellm/types/proxy/policy_engine/resolver_types.py
@@ -311,6 +311,10 @@ class PolicyAttachmentCreateRequest(BaseModel):
le=2147483647,
description="Explicit execution order, lower runs first. Prioritised attachments run before those without one.",
)
+ default: bool = Field(
+ default=False,
+ description="Apply this attachment only when no non-default attachment matches the request.",
+ )
class PolicyAttachmentDBResponse(BaseModel):
@@ -327,6 +331,10 @@ class PolicyAttachmentDBResponse(BaseModel):
default=None,
description="Explicit execution order, lower runs first. Prioritised attachments run before those without one.",
)
+ default: bool = Field(
+ default=False,
+ description="Apply this attachment only when no non-default attachment matches the request.",
+ )
created_at: datetime | None = Field(default=None, description="When the attachment was created.")
updated_at: datetime | None = Field(default=None, description="When the attachment was last updated.")
created_by: str | None = Field(default=None, description="Who created the attachment.")
diff --git a/litellm/utils.py b/litellm/utils.py
index 9a80b115d4b..da2b3da6302 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -5624,6 +5624,12 @@ def _get_model_info_from_generalization(
return None
+def _strip_mantle_region_prefix(model: str) -> str:
+ from litellm.llms.bedrock_mantle.common_utils import split_mantle_region_prefix
+
+ return split_mantle_region_prefix(model)[1]
+
+
def _get_potential_model_names(model: str, custom_llm_provider: str | None) -> PotentialModelNamesAndCustomLLMProvider:
if custom_llm_provider is None:
# Get custom_llm_provider
@@ -5656,20 +5662,30 @@ def _get_potential_model_names(model: str, custom_llm_provider: str | None) -> P
split_model = strip_bedrock_routing_prefix(split_model)
+ region_free_split_model: Final = (
+ _strip_mantle_region_prefix(split_model) if custom_llm_provider == "bedrock_mantle" else split_model
+ )
+ region_free_combined_stripped_model_name: Final = (
+ f"bedrock_mantle/{_strip_model_name(model=region_free_split_model, custom_llm_provider=custom_llm_provider)}"
+ if custom_llm_provider == "bedrock_mantle"
+ else combined_stripped_model_name
+ )
provider_model_info: Final = (
- ProviderConfigManager.get_provider_model_info(model=split_model, provider=LlmProviders(custom_llm_provider))
+ ProviderConfigManager.get_provider_model_info(
+ model=region_free_split_model, provider=LlmProviders(custom_llm_provider)
+ )
if custom_llm_provider in LlmProvidersSet
else None
)
provider_cost_key: Final = (
- provider_model_info.get_model_cost_key(split_model) if provider_model_info is not None else None
+ provider_model_info.get_model_cost_key(region_free_split_model) if provider_model_info is not None else None
)
return PotentialModelNamesAndCustomLLMProvider(
- split_model=split_model,
+ split_model=region_free_split_model,
combined_model_name=combined_model_name,
stripped_model_name=stripped_model_name,
- combined_stripped_model_name=combined_stripped_model_name,
+ combined_stripped_model_name=region_free_combined_stripped_model_name,
provider_prefixed_model_name=provider_cost_key or provider_prefixed_model_name,
custom_llm_provider=cast(str, custom_llm_provider),
)
@@ -8681,6 +8697,13 @@ class ProviderConfigManager:
from litellm.llms.bedrock.common_utils import BedrockModelInfo
return BedrockModelInfo.get_bedrock_provider_config_for_messages_api(model)
+ elif litellm.LlmProviders.BEDROCK_MANTLE == provider:
+ if "claude" in model_lower:
+ from litellm.llms.bedrock_mantle.messages.transformation import (
+ BedrockMantleAnthropicMessagesConfig,
+ )
+
+ return BedrockMantleAnthropicMessagesConfig()
elif litellm.LlmProviders.VERTEX_AI == provider:
if "claude" in model_lower:
from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.experimental_pass_through.transformation import (
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index aa67dc58d69..97a38ac1657 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -42971,21 +42971,21 @@
"supports_web_search": false
},
"openrouter/deepseek/deepseek-v4-pro": {
- "input_cost_per_token": 9.22722e-07,
+ "input_cost_per_token": 9.19242e-07,
"input_cost_per_token_cache_hit": 4.4e-08,
"litellm_provider": "openrouter",
"max_input_tokens": 1048576,
"max_output_tokens": 384000,
"max_tokens": 384000,
"mode": "chat",
- "output_cost_per_token": 1.845444e-06,
+ "output_cost_per_token": 1.838484e-06,
"source": "https://openrouter.ai/api/v1/models",
"supports_function_calling": true,
"supports_prompt_caching": true,
"supports_reasoning": true,
"supports_response_schema": true,
"supports_tool_choice": true,
- "cache_read_input_token_cost": 7.68935e-08,
+ "cache_read_input_token_cost": 7.66035e-08,
"supports_audio_input": false,
"supports_pdf_input": false,
"supports_vision": false,
@@ -54441,16 +54441,19 @@
"zai.glm-4.7": {
"input_cost_per_token": 6e-07,
"litellm_provider": "bedrock_converse",
- "max_input_tokens": 200000,
- "max_output_tokens": 128000,
- "max_tokens": 128000,
+ "max_input_tokens": 203000,
+ "max_output_tokens": 4000,
+ "max_tokens": 4000,
"mode": "chat",
"output_cost_per_token": 2.2e-06,
"supports_function_calling": true,
"supports_reasoning": true,
"supports_system_messages": true,
"supports_tool_choice": true,
- "source": "https://aws.amazon.com/bedrock/pricing/"
+ "source": "https://aws.amazon.com/bedrock/pricing/",
+ "supports_audio_input": false,
+ "supports_response_schema": true,
+ "supports_vision": false
},
"zai.glm-5": {
"input_cost_per_token": 1e-06,
@@ -54470,16 +54473,19 @@
"zai.glm-4.7-flash": {
"input_cost_per_token": 7e-08,
"litellm_provider": "bedrock_converse",
- "max_input_tokens": 200000,
- "max_output_tokens": 128000,
- "max_tokens": 128000,
+ "max_input_tokens": 203000,
+ "max_output_tokens": 4000,
+ "max_tokens": 4000,
"mode": "chat",
"output_cost_per_token": 4e-07,
"supports_function_calling": true,
"supports_reasoning": true,
"supports_system_messages": true,
"supports_tool_choice": true,
- "source": "https://aws.amazon.com/bedrock/pricing/"
+ "source": "https://aws.amazon.com/bedrock/pricing/",
+ "supports_audio_input": false,
+ "supports_response_schema": true,
+ "supports_vision": false
},
"zai/glm-5": {
"cache_creation_input_token_cost": 0,
@@ -60558,6 +60564,34 @@
"supports_tool_choice": true,
"supports_vision": true
},
+ "bedrock_mantle/anthropic.claude-haiku-4-5": {
+ "cache_creation_input_token_cost": 1.25e-06,
+ "cache_creation_input_token_cost_above_1hr": 2e-06,
+ "cache_read_input_token_cost": 1e-07,
+ "input_cost_per_token": 1e-06,
+ "litellm_provider": "bedrock_mantle",
+ "supports_tool_search": true,
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "mode": "chat",
+ "output_cost_per_token": 5e-06,
+ "source": "https://aws.amazon.com/about-aws/whats-new/2025/10/claude-4-5-haiku-anthropic-amazon-bedrock",
+ "supports_assistant_prefill": true,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "supports_native_structured_output": true,
+ "supports_parallel_tool_use_config": true,
+ "prompt_cache_min_tokens": 4096,
+ "input_cost_per_token_batches": 5e-07,
+ "output_cost_per_token_batches": 2.5e-06
+ },
"us.xai.grok-4.6": {
"input_cost_per_token": 2.2e-06,
"output_cost_per_token": 6.6e-06,
@@ -76803,7 +76837,7 @@
"max_tokens": 131072,
"mode": "chat",
"output_cost_per_token": 1.65e-05,
- "source": "https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-moonshot-ai-kimi-k3.html",
+ "source": "https://aws.amazon.com/bedrock/pricing/",
"supports_audio_input": false,
"supports_function_calling": true,
"supports_prompt_caching": true,
diff --git a/schema.prisma b/schema.prisma
index d2032cec0d0..2d7e557a9d1 100644
--- a/schema.prisma
+++ b/schema.prisma
@@ -1419,6 +1419,7 @@ model LiteLLM_PolicyAttachmentTable {
models String[] @default([]) // Model names or patterns
tags String[] @default([]) // Tag patterns (e.g., ["healthcare", "prod-*"])
priority Int? // Explicit execution order
+ is_default Boolean @default(false) // Applied only when no non-default attachment matches
created_at DateTime @default(now())
created_by String?
updated_at DateTime @default(now()) @updatedAt
diff --git a/tests/proxy_unit_tests/test_proxy_utils.py b/tests/proxy_unit_tests/test_proxy_utils.py
index 7cdd7365209..1134f41a940 100644
--- a/tests/proxy_unit_tests/test_proxy_utils.py
+++ b/tests/proxy_unit_tests/test_proxy_utils.py
@@ -2003,7 +2003,7 @@ def test_provider_specific_header():
)
# Verify multi-provider support: anthropic headers work across multiple providers
assert data["provider_specific_header"] == {
- "custom_llm_provider": "anthropic,bedrock,vertex_ai",
+ "custom_llm_provider": "anthropic,bedrock,bedrock_mantle,vertex_ai",
"extra_headers": {
"anthropic-beta": "prompt-caching-2024-07-31",
},
@@ -2075,7 +2075,7 @@ def test_provider_specific_header_multi_provider():
assert "provider_specific_header" in data
assert (
data["provider_specific_header"]["custom_llm_provider"]
- == "anthropic,bedrock,vertex_ai"
+ == "anthropic,bedrock,bedrock_mantle,vertex_ai"
)
assert data["provider_specific_header"]["extra_headers"] == {
"anthropic-beta": "context-1m-2025-08-07",
diff --git a/tests/router_unit_tests/test_router_prompt_caching.py b/tests/router_unit_tests/test_router_prompt_caching.py
index 5c36c30e818..879264ca502 100644
--- a/tests/router_unit_tests/test_router_prompt_caching.py
+++ b/tests/router_unit_tests/test_router_prompt_caching.py
@@ -11,57 +11,9 @@ from unittest.mock import patch, MagicMock, AsyncMock
from create_mock_standard_logging_payload import create_standard_logging_payload
from litellm.types.utils import StandardLoggingPayload
import unittest
-from pydantic import BaseModel
from litellm.router_utils.prompt_caching_cache import PromptCachingCache
-class ExampleModel(BaseModel):
- field1: str
- field2: int
-
-
-def test_serialize_pydantic_object():
- model = ExampleModel(field1="value", field2=42)
- serialized = PromptCachingCache.serialize_object(model)
- assert serialized == {"field1": "value", "field2": 42}
-
-
-def test_serialize_dict():
- obj = {"b": 2, "a": 1}
- serialized = PromptCachingCache.serialize_object(obj)
- assert serialized == '{"a":1,"b":2}' # JSON string with sorted keys
-
-
-def test_serialize_nested_dict():
- obj = {"z": {"b": 2, "a": 1}, "x": [1, 2, {"c": 3}]}
- serialized = PromptCachingCache.serialize_object(obj)
- expected = '{"x":[1,2,{"c":3}],"z":{"a":1,"b":2}}' # JSON string with sorted keys
- assert serialized == expected
-
-
-def test_serialize_list():
- obj = ["item1", {"a": 1, "b": 2}, 42]
- serialized = PromptCachingCache.serialize_object(obj)
- expected = ["item1", '{"a":1,"b":2}', 42]
- assert serialized == expected
-
-
-def test_serialize_fallback():
- obj = 12345 # Simple non-serializable object
- serialized = PromptCachingCache.serialize_object(obj)
- assert serialized == 12345
-
-
-def test_serialize_non_serializable():
- class CustomClass:
- def __str__(self):
- return "custom_object"
-
- obj = CustomClass()
- serialized = PromptCachingCache.serialize_object(obj)
- assert serialized == "custom_object" # Fallback to string conversion
-
-
@pytest.mark.asyncio
async def test_router_prompt_caching_same_cacheable_prefix_routes_to_same_deployment():
"""
diff --git a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py b/tests/test_litellm/experimental_mcp_client/test_mcp_client.py
index 4b698f1258d..6c20ef135ba 100644
--- a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py
+++ b/tests/test_litellm/experimental_mcp_client/test_mcp_client.py
@@ -2036,6 +2036,15 @@ async def test_optional_discovery_preserves_cancellation(method: str) -> None:
},
},
)
+ if not (payload.params or {}).get("cursor"):
+ field: Final = {
+ "prompts/list": "prompts",
+ "resources/list": "resources",
+ "resources/templates/list": "resourceTemplates",
+ }[method]
+ return httpx2.Response(
+ 200, json={"jsonrpc": "2.0", "id": payload.id, "result": {field: [], "nextCursor": "pending-page"}}
+ )
ready.set()
await pending.wait()
return httpx2.Response(202)
@@ -2055,6 +2064,255 @@ async def test_optional_discovery_preserves_cancellation(method: str) -> None:
await asyncio.wait_for(task, timeout=3)
+@pytest.mark.asyncio
+@pytest.mark.parametrize("method", ("prompts/list", "resources/list", "resources/templates/list"))
+@pytest.mark.parametrize("session_id", (None, "pagination-session"))
+@pytest.mark.parametrize("empty_middle", (False, True))
+async def test_optional_discovery_collects_all_pages(method: str, session_id: str | None, empty_middle: bool) -> None:
+ from mcp.types import Prompt, PromptArgument, Resource, ResourceTemplate
+
+ field: Final = {
+ "prompts/list": "prompts",
+ "resources/list": "resources",
+ "resources/templates/list": "resourceTemplates",
+ }[method]
+ entries: Final = tuple(
+ {
+ "prompts/list": Prompt(
+ name=f"item-{index}",
+ description="prompt description",
+ arguments=[PromptArgument(name="query", required=True)],
+ ),
+ "resources/list": Resource(
+ name=f"item-{index}",
+ uri=f"test://item/{index}",
+ mime_type="text/plain",
+ description="resource description",
+ ),
+ "resources/templates/list": ResourceTemplate(
+ name=f"item-{index}", uri_template=f"test://item/{index}/{{query}}", mime_type="text/plain"
+ ),
+ }[method]
+ for index in range(5)
+ )
+
+ def respond(request: httpx2.Request) -> httpx2.Response:
+ if request.method == "GET":
+ return httpx2.Response(405)
+ if request.method == "DELETE":
+ return httpx2.Response(200)
+ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)
+ if not isinstance(payload, JSONRPCRequest):
+ return httpx2.Response(202)
+ if payload.method == "initialize":
+ return httpx2.Response(
+ 200,
+ headers={"mcp-session-id": session_id} if session_id else {},
+ json={
+ "jsonrpc": "2.0",
+ "id": payload.id,
+ "result": {
+ "protocolVersion": payload.params["protocolVersion"],
+ "capabilities": {"prompts": {}, "resources": {}},
+ "serverInfo": {"name": "paged", "version": "1"},
+ },
+ },
+ )
+ assert payload.method == method
+ assert request.headers.get("mcp-session-id") == session_id
+ cursor: Final = (payload.params or {}).get("cursor")
+ assert cursor in (None, "opaque:/second+page", "opaque:/last+page")
+ page: Final = (
+ entries[:3] if cursor is None else (() if empty_middle and cursor == "opaque:/second+page" else entries[3:])
+ )
+ next_cursor: Final = (
+ "opaque:/second+page"
+ if cursor is None
+ else "opaque:/last+page"
+ if empty_middle and cursor == "opaque:/second+page"
+ else ""
+ )
+ return httpx2.Response(
+ 200,
+ json={
+ "jsonrpc": "2.0",
+ "id": payload.id,
+ "result": {
+ field: [item.model_dump(mode="json", by_alias=True) for item in page],
+ "nextCursor": next_cursor,
+ },
+ },
+ )
+
+ responder: Final = Mock(side_effect=respond)
+ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp")
+ operation: Final = {
+ "prompts/list": client.list_prompts,
+ "resources/list": client.list_resources,
+ "resources/templates/list": client.list_resource_templates,
+ }[method]
+ assert await operation(raise_on_error=True) == list(entries)
+ requests: Final = tuple(
+ _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content)
+ for call in responder.call_args_list
+ if call.args[0].method == "POST"
+ )
+ assert sum(isinstance(request, JSONRPCRequest) and request.method == "initialize" for request in requests) == 1
+ assert tuple(
+ (request.params or {}).get("cursor")
+ for request in requests
+ if isinstance(request, JSONRPCRequest) and request.method == method
+ ) == ((None, "opaque:/second+page", "opaque:/last+page") if empty_middle else (None, "opaque:/second+page"))
+ assert sum(call.args[0].method == "DELETE" for call in responder.call_args_list) == (1 if session_id else 0)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("method", ("prompts/list", "resources/list", "resources/templates/list"))
+@pytest.mark.parametrize(
+ "failure", ("repeat", "cycle", "cap", "method_not_found", "internal_error", "unauthorized", "deadline")
+)
+@pytest.mark.parametrize("strict", (False, True))
+async def test_optional_discovery_rejects_incomplete_walks(
+ method: str, failure: str, strict: bool, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(mcp_client_module, "MCP_TOOL_LISTING_MAX_PAGES", 3 if failure == "cycle" else 2, raising=False)
+ monkeypatch.setattr(mcp_client_module, "MCP_TOOL_LISTING_TIMEOUT", 0.05)
+ field: Final = {
+ "prompts/list": "prompts",
+ "resources/list": "resources",
+ "resources/templates/list": "resourceTemplates",
+ }[method]
+ entry: Final = {
+ "prompts/list": {"name": "first"},
+ "resources/list": {"name": "first", "uri": "test://first"},
+ "resources/templates/list": {"name": "first", "uriTemplate": "test://{name}"},
+ }[method]
+ cancelled: Final = asyncio.Event()
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)
+ if not isinstance(payload, JSONRPCRequest):
+ return httpx2.Response(202)
+ if payload.method == "initialize":
+ return httpx2.Response(
+ 200,
+ json={
+ "jsonrpc": "2.0",
+ "id": payload.id,
+ "result": {
+ "protocolVersion": payload.params["protocolVersion"],
+ "capabilities": {"prompts": {}, "resources": {}},
+ "serverInfo": {"name": "interrupted", "version": "1"},
+ },
+ },
+ )
+ assert payload.method == method
+ cursor: Final = (payload.params or {}).get("cursor")
+ if cursor is not None:
+ if failure == "deadline":
+ try:
+ await asyncio.Event().wait()
+ finally:
+ cancelled.set()
+ if failure == "unauthorized":
+ return httpx2.Response(401)
+ if failure in ("method_not_found", "internal_error"):
+ return httpx2.Response(
+ 200,
+ json={
+ "jsonrpc": "2.0",
+ "id": payload.id,
+ "error": {
+ "code": -32601 if failure == "method_not_found" else -32603,
+ "message": "Later page unavailable",
+ },
+ },
+ )
+ next_cursor: Final = (
+ "private-cursor-2" if cursor == "private-cursor-1" and failure != "repeat" else "private-cursor-1"
+ )
+ return httpx2.Response(
+ 200, json={"jsonrpc": "2.0", "id": payload.id, "result": {field: [entry], "nextCursor": next_cursor}}
+ )
+
+ responder: Final = AsyncMock(side_effect=respond)
+ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp", timeout=0.2)
+ operation: Final = {
+ "prompts/list": client.list_prompts,
+ "resources/list": client.list_resources,
+ "resources/templates/list": client.list_resource_templates,
+ }[method]
+ if strict:
+ error_type: Final = {
+ "internal_error": MCPError,
+ "unauthorized": httpx2.HTTPStatusError,
+ "deadline": TimeoutError,
+ }.get(failure, RuntimeError)
+ with pytest.raises(error_type):
+ await operation(raise_on_error=True)
+ else:
+ assert await operation() == []
+ assert len(
+ tuple(
+ payload
+ for call in responder.call_args_list
+ if isinstance(payload := _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content), JSONRPCRequest)
+ and payload.method == method
+ )
+ ) == (3 if failure == "cycle" else 2)
+ assert "private-cursor" not in caplog.text
+ if failure == "deadline":
+ assert cancelled.is_set()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("method", ("prompts/list", "resources/list", "resources/templates/list"))
+async def test_optional_discovery_allows_exhaustion_at_page_cap(method: str, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(mcp_client_module, "MCP_TOOL_LISTING_MAX_PAGES", 2, raising=False)
+ field: Final = {
+ "prompts/list": "prompts",
+ "resources/list": "resources",
+ "resources/templates/list": "resourceTemplates",
+ }[method]
+
+ def respond(request: httpx2.Request) -> httpx2.Response:
+ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)
+ if not isinstance(payload, JSONRPCRequest):
+ return httpx2.Response(202)
+ if payload.method == "initialize":
+ result: Final = {
+ "protocolVersion": payload.params["protocolVersion"],
+ "capabilities": {"prompts": {}, "resources": {}},
+ "serverInfo": {"name": "empty-pages", "version": "1"},
+ }
+ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": result})
+ assert payload.method == method
+ return httpx2.Response(
+ 200,
+ json={
+ "jsonrpc": "2.0",
+ "id": payload.id,
+ "result": {field: [], "nextCursor": None if (payload.params or {}).get("cursor") else "last-page"},
+ },
+ )
+
+ responder: Final = Mock(side_effect=respond)
+ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp")
+ operation: Final = {
+ "prompts/list": client.list_prompts,
+ "resources/list": client.list_resources,
+ "resources/templates/list": client.list_resource_templates,
+ }[method]
+ assert await operation(raise_on_error=True) == []
+ assert (
+ sum(
+ isinstance(payload := _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content), JSONRPCRequest)
+ and payload.method == method
+ for call in responder.call_args_list
+ )
+ == 2
+ )
+
def test_client_import_before_proxy_credentials_succeeds_in_fresh_process():
import subprocess
diff --git a/tests/test_litellm/litellm_core_utils/test_token_counter.py b/tests/test_litellm/litellm_core_utils/test_token_counter.py
index ba3a6be609f..f19a8891609 100644
--- a/tests/test_litellm/litellm_core_utils/test_token_counter.py
+++ b/tests/test_litellm/litellm_core_utils/test_token_counter.py
@@ -1257,6 +1257,25 @@ def test_token_counter_with_thinking_content():
), f"Expected minimal token count for empty thinking block, got {tokens_no_thinking}"
+
+def test_token_counter_with_redacted_thinking_content():
+ """
+ A replayed redacted_thinking block (Anthropic redacted reasoning, or the /v1/messages bridge's stand-in
+ for a reasoning item with no summary) counts zero tokens for its encrypted payload, like a thinking
+ block with no text. It used to raise, which made is_prompt_caching_valid_prompt return False and the
+ prompt_caching pre-call check stop pinning the deployment that held the cached prefix.
+ """
+ model = "anthropic/claude-sonnet-4-5-20250929"
+ reply = {"type": "text", "text": "Draw from the box labeled Mixed, because that label must be wrong."}
+ redacted_block = {"type": "redacted_thinking", "data": "EqQBCkYIBRgCKkBjZ2xhc3M" * 30}
+ user_turn = {"role": "user", "content": [{"type": "text", "text": "Which box do you draw from?"}]}
+ follow_up = {"role": "user", "content": [{"type": "text", "text": "Restate that in one sentence."}]}
+
+ without_block = [user_turn, {"role": "assistant", "content": [reply]}, follow_up]
+ with_block = [user_turn, {"role": "assistant", "content": [redacted_block, reply]}, follow_up]
+
+ assert token_counter(model=model, messages=with_block) == token_counter(model=model, messages=without_block)
+
def test_token_counter_with_tool_reference_block():
"""
Regression test: a message containing an Anthropic tool-search
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
index e8bfcb86bf6..cc4eb1d4136 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
@@ -1440,6 +1440,46 @@ async def test_anthropic_messages_leaves_non_provider_failures_unmapped():
assert "Traceback" not in str(excinfo.value)
+def _recording_client(seen_urls: list[str]) -> AsyncHTTPHandler:
+ def record_and_answer(request: httpx.Request) -> httpx.Response:
+ seen_urls.append(str(request.url))
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": "deepseek-chat",
+ "content": [{"type": "text", "text": "pong"}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 3, "output_tokens": 1},
+ },
+ )
+
+ upstream = AsyncHTTPHandler()
+ upstream.client = httpx.AsyncClient(transport=httpx.MockTransport(record_and_answer))
+ return upstream
+
+
+@pytest.mark.asyncio
+async def test_provider_messages_api_base_env_is_not_shadowed_by_the_chat_default(monkeypatch):
+ from litellm.llms.anthropic.experimental_pass_through.messages import handler
+
+ monkeypatch.delenv("DEEPSEEK_API_BASE", raising=False)
+ monkeypatch.setenv("DEEPSEEK_ANTHROPIC_API_BASE", "https://deepseek.internal.example/anthropic")
+ seen_urls: list[str] = []
+
+ await handler.anthropic_messages(
+ max_tokens=16,
+ messages=[{"role": "user", "content": "ping"}],
+ model="deepseek/deepseek-chat",
+ api_key="sk-test",
+ client=_recording_client(seen_urls),
+ )
+
+ assert seen_urls == ["https://deepseek.internal.example/anthropic/v1/messages"]
+
@pytest.mark.asyncio
async def test_anthropic_messages_forwards_safeguards_and_unknown_beta_to_anthropic():
"""Shapes are what Claude Code 2.1.278 sends and api.anthropic.com returns, captured 2026-09-21."""
diff --git a/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_messages_transformation.py b/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_messages_transformation.py
new file mode 100644
index 00000000000..6bacf8f3d94
--- /dev/null
+++ b/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_messages_transformation.py
@@ -0,0 +1,484 @@
+"""
+Unit tests for the bedrock_mantle native Anthropic Messages route.
+
+Mantle serves its Claude models only on `/anthropic/v1/messages` (the OpenAI
+paths reject them), so `bedrock_mantle/anthropic.claude-*` requests on
+/v1/messages must hit that endpoint directly instead of the chat-completions
+bridge. These tests lock the dispatcher gate, the URL derivation from the
+OpenAI-surface base that get_llm_provider pre-fills, the version header, the
+Bearer/SigV4 auth chain, and the wire request through the public entrypoint.
+"""
+
+import json
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import respx
+
+import litellm
+from litellm.caching.llm_caching_handler import LLMClientCache
+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
+from litellm.llms.bedrock_mantle.messages.transformation import (
+ BedrockMantleAnthropicMessagesConfig,
+ build_mantle_native_messages_url,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.utils import ProviderConfigManager
+
+MESSAGES_PATH = "/anthropic/v1/messages"
+
+
+@pytest.fixture(autouse=True)
+def _httpx_transport_with_fresh_clients(monkeypatch):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.setattr(litellm, "in_memory_llm_clients_cache", LLMClientCache())
+
+
+@pytest.fixture(autouse=True)
+def _no_ambient_mantle_env(monkeypatch):
+ monkeypatch.delenv("AWS_BEARER_TOKEN_BEDROCK", raising=False)
+ monkeypatch.delenv("BEDROCK_MANTLE_API_KEY", raising=False)
+ monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
+ monkeypatch.delenv("BEDROCK_MANTLE_REGION", raising=False)
+ monkeypatch.delenv("AWS_REGION_NAME", raising=False)
+ monkeypatch.delenv("AWS_REGION", raising=False)
+
+
+def _anthropic_response() -> httpx.Response:
+ return httpx.Response(
+ status_code=200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": "anthropic.claude-sonnet-5",
+ "content": [{"type": "text", "text": "pong"}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 3, "output_tokens": 1},
+ },
+ )
+
+
+_SSE_EVENTS = (
+ (
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_stream",
+ "type": "message",
+ "role": "assistant",
+ "model": "anthropic.claude-sonnet-5",
+ "content": [],
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": {"input_tokens": 3, "output_tokens": 1},
+ },
+ },
+ ),
+ ("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
+ (
+ "content_block_delta",
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "pong"}},
+ ),
+ ("content_block_stop", {"type": "content_block_stop", "index": 0}),
+ ("message_delta", {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 1}}),
+ ("message_stop", {"type": "message_stop"}),
+)
+
+
+def _sse_response() -> httpx.Response:
+ body = "".join(f"event: {event}\ndata: {json.dumps(payload)}\n\n" for event, payload in _SSE_EVENTS).encode()
+ return httpx.Response(status_code=200, content=body, headers={"content-type": "text/event-stream"})
+
+
+def _mantle_messages_route(region: str) -> respx.Route:
+ return respx.post(f"https://bedrock-mantle.{region}.api.aws{MESSAGES_PATH}")
+
+
+def _sent_body(route: respx.Route) -> dict:
+ return json.loads(route.calls.last.request.content)
+
+
+class TestDispatch:
+ def test_claude_models_get_the_native_messages_config(self):
+ config = ProviderConfigManager.get_provider_anthropic_messages_config(
+ model="anthropic.claude-sonnet-5", provider=litellm.LlmProviders.BEDROCK_MANTLE
+ )
+ assert isinstance(config, BedrockMantleAnthropicMessagesConfig)
+ assert config.custom_llm_provider == "bedrock_mantle"
+
+ @pytest.mark.parametrize("model", ["openai.gpt-5.6-sol", "openai.gpt-oss-120b-1:0", "google.gemma-4-31b"])
+ def test_non_claude_models_keep_the_bridge(self, model):
+ assert (
+ ProviderConfigManager.get_provider_anthropic_messages_config(
+ model=model, provider=litellm.LlmProviders.BEDROCK_MANTLE
+ )
+ is None
+ )
+
+
+class TestURL:
+ @pytest.mark.parametrize(
+ "api_base",
+ [
+ "https://bedrock-mantle.us-east-1.api.aws/v1",
+ "https://bedrock-mantle.us-east-1.api.aws/openai/v1",
+ "https://bedrock-mantle.us-east-1.api.aws/openai/v1/",
+ "https://bedrock-mantle.us-east-1.api.aws",
+ "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages",
+ ],
+ )
+ def test_prefilled_openai_base_becomes_the_messages_endpoint(self, api_base):
+ url = build_mantle_native_messages_url(api_base, {"aws_region_name": "us-east-1"})
+ assert url == f"https://bedrock-mantle.us-east-1.api.aws{MESSAGES_PATH}"
+
+ def test_aws_region_name_wins_over_the_prefilled_host_region(self):
+ url = build_mantle_native_messages_url(
+ "https://bedrock-mantle.us-east-1.api.aws/v1", {"aws_region_name": "us-east-2"}
+ )
+ assert url == f"https://bedrock-mantle.us-east-2.api.aws{MESSAGES_PATH}"
+
+ def test_host_region_is_used_when_no_region_param(self):
+ url = build_mantle_native_messages_url("https://bedrock-mantle.eu-west-1.api.aws/v1", {})
+ assert url == f"https://bedrock-mantle.eu-west-1.api.aws{MESSAGES_PATH}"
+
+ def test_custom_host_is_preserved(self):
+ url = build_mantle_native_messages_url("https://vpce-abc.bedrock-mantle.example.com/v1", {})
+ assert url == f"https://vpce-abc.bedrock-mantle.example.com{MESSAGES_PATH}"
+
+ def test_env_base_is_used_without_api_base(self, monkeypatch):
+ monkeypatch.setenv("BEDROCK_MANTLE_API_BASE", "https://mantle-proxy.internal/openai/v1")
+ assert build_mantle_native_messages_url(None, {}) == f"https://mantle-proxy.internal{MESSAGES_PATH}"
+
+ def test_default_host_comes_from_mantle_region_env(self, monkeypatch):
+ monkeypatch.setenv("BEDROCK_MANTLE_REGION", "ap-northeast-1")
+ assert (
+ build_mantle_native_messages_url(None, {})
+ == f"https://bedrock-mantle.ap-northeast-1.api.aws{MESSAGES_PATH}"
+ )
+
+ def test_config_get_complete_url_reads_litellm_params(self):
+ config = BedrockMantleAnthropicMessagesConfig()
+ url = config.get_complete_url(
+ api_base="https://bedrock-mantle.us-east-1.api.aws/v1",
+ api_key=None,
+ model="anthropic.claude-sonnet-5",
+ optional_params={},
+ litellm_params={"aws_region_name": "us-west-2"},
+ )
+ assert url == f"https://bedrock-mantle.us-west-2.api.aws{MESSAGES_PATH}"
+
+
+class TestEnvironment:
+ def _validate(self, headers: dict, litellm_params: dict) -> dict:
+ config = BedrockMantleAnthropicMessagesConfig()
+ merged, _ = config.validate_anthropic_messages_environment(
+ headers=headers,
+ model="anthropic.claude-sonnet-5",
+ messages=[],
+ optional_params={},
+ litellm_params=litellm_params,
+ )
+ return merged
+
+ def test_adds_the_anthropic_version_header(self):
+ assert self._validate({}, {})["anthropic-version"] == "2023-06-01"
+
+ def test_keeps_a_caller_supplied_version_header(self):
+ merged = self._validate({"Anthropic-Version": "2024-01-01"}, {})
+ assert merged["Anthropic-Version"] == "2024-01-01"
+ assert "anthropic-version" not in merged
+
+ def test_project_id_becomes_the_workspace_header(self):
+ assert self._validate({}, {"aws_bedrock_project_id": "proj_123"})["anthropic-workspace"] == "proj_123"
+
+
+class TestRequestBody:
+ def test_body_carries_model_and_stream_but_not_the_invoke_version(self):
+ config = BedrockMantleAnthropicMessagesConfig()
+ body = config.transform_anthropic_messages_request(
+ model="anthropic.claude-sonnet-5",
+ messages=[{"role": "user", "content": "ping"}],
+ anthropic_messages_optional_request_params={"max_tokens": 8, "stream": True},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+ assert body["model"] == "anthropic.claude-sonnet-5"
+ assert body["stream"] is True
+ assert body["max_tokens"] == 8
+ assert "anthropic_version" not in body
+
+ def test_body_omits_stream_when_not_streaming(self):
+ config = BedrockMantleAnthropicMessagesConfig()
+ body = config.transform_anthropic_messages_request(
+ model="anthropic.claude-sonnet-5",
+ messages=[{"role": "user", "content": "ping"}],
+ anthropic_messages_optional_request_params={"max_tokens": 8},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+ assert "stream" not in body
+
+
+class TestAuth:
+ def test_bearer_from_api_key_skips_aws_credentials(self):
+ signer = BaseAWSLLM()
+ signer.get_credentials = MagicMock(side_effect=AssertionError("must not resolve AWS credentials"))
+ config = BedrockMantleAnthropicMessagesConfig(aws_signer=signer)
+ headers, signed = config.sign_request(
+ headers={"anthropic-version": "2023-06-01"},
+ optional_params={},
+ request_data={"model": "anthropic.claude-sonnet-5"},
+ api_base=f"https://bedrock-mantle.us-east-1.api.aws{MESSAGES_PATH}",
+ api_key="arg-bearer",
+ )
+ assert headers["Authorization"] == "Bearer arg-bearer"
+ assert headers["anthropic-version"] == "2023-06-01"
+ assert signed == b'{"model": "anthropic.claude-sonnet-5"}'
+
+ def test_bearer_from_mantle_env_key(self, monkeypatch):
+ monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "env-bearer")
+ config = BedrockMantleAnthropicMessagesConfig()
+ headers, _ = config.sign_request(
+ headers={},
+ optional_params={},
+ request_data={},
+ api_base=f"https://bedrock-mantle.us-east-1.api.aws{MESSAGES_PATH}",
+ api_key=None,
+ )
+ assert headers["Authorization"] == "Bearer env-bearer"
+
+ def test_sigv4_scope_is_pinned_to_the_url_host_region(self):
+ config = BedrockMantleAnthropicMessagesConfig()
+ headers, signed = config.sign_request(
+ headers={"anthropic-version": "2023-06-01"},
+ optional_params={
+ "aws_access_key_id": "AKIAEXAMPLE",
+ "aws_secret_access_key": "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0",
+ "aws_region_name": "us-east-1",
+ },
+ request_data={"model": "anthropic.claude-sonnet-5"},
+ api_base=f"https://bedrock-mantle.us-west-2.api.aws{MESSAGES_PATH}",
+ api_key=None,
+ )
+ assert headers["Authorization"].startswith("AWS4-HMAC-SHA256")
+ assert "/us-west-2/bedrock/aws4_request" in headers["Authorization"]
+ assert signed == b'{"model": "anthropic.claude-sonnet-5"}'
+
+
+class TestWireRequest:
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_claude_request_hits_the_native_messages_endpoint(self):
+ route = _mantle_messages_route("us-east-1").mock(return_value=_anthropic_response())
+
+ response = await litellm.anthropic_messages(
+ model="bedrock_mantle/anthropic.claude-sonnet-5",
+ messages=[{"role": "user", "content": "ping"}],
+ max_tokens=8,
+ api_key="test-bearer",
+ aws_region_name="us-east-1",
+ )
+
+ assert response["content"][0]["text"] == "pong"
+ assert route.call_count == 1
+ sent = route.calls.last.request
+ assert sent.headers["authorization"] == "Bearer test-bearer"
+ assert sent.headers["anthropic-version"] == "2023-06-01"
+ assert "x-api-key" not in sent.headers
+ body = _sent_body(route)
+ assert body["model"] == "anthropic.claude-sonnet-5"
+ assert body["messages"] == [{"role": "user", "content": "ping"}]
+ assert "anthropic_version" not in body
+ assert "stream" not in body
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_region_prefix_selects_the_host_and_is_not_sent_as_model(self):
+ route = _mantle_messages_route("us-east-2").mock(return_value=_anthropic_response())
+
+ await litellm.anthropic_messages(
+ model="bedrock_mantle/us-east-2/anthropic.claude-haiku-4-5",
+ messages=[{"role": "user", "content": "ping"}],
+ max_tokens=8,
+ api_key="test-bearer",
+ )
+
+ assert route.call_count == 1
+ assert _sent_body(route)["model"] == "anthropic.claude-haiku-4-5"
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_streaming_sends_stream_and_passes_the_sse_through(self):
+ route = _mantle_messages_route("us-east-1").mock(return_value=_sse_response())
+
+ response = await litellm.anthropic_messages(
+ model="bedrock_mantle/anthropic.claude-sonnet-5",
+ messages=[{"role": "user", "content": "ping"}],
+ max_tokens=8,
+ stream=True,
+ api_key="test-bearer",
+ aws_region_name="us-east-1",
+ )
+ raw = b"".join([chunk async for chunk in response])
+
+ assert route.call_count == 1
+ assert _sent_body(route)["stream"] is True
+ text = raw.decode()
+ assert "event: message_start" in text
+ assert '"text": "pong"' in text
+ assert "event: message_stop" in text
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_sigv4_request_signs_against_the_messages_url(self):
+ route = _mantle_messages_route("us-east-1").mock(return_value=_anthropic_response())
+
+ await litellm.anthropic_messages(
+ model="bedrock_mantle/anthropic.claude-sonnet-5",
+ messages=[{"role": "user", "content": "ping"}],
+ max_tokens=8,
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0",
+ aws_region_name="us-east-1",
+ )
+
+ assert route.call_count == 1
+ authorization = route.calls.last.request.headers["authorization"]
+ assert authorization.startswith("AWS4-HMAC-SHA256")
+ assert "/us-east-1/bedrock/aws4_request" in authorization
+
+
+def _sent_betas(route: respx.Route) -> list[str]:
+ return route.calls.last.request.headers["anthropic-beta"].split(",")
+
+
+@pytest.mark.usefixtures("local_beta_headers_config")
+class TestBetaHeadersOnTheWire:
+ async def _send(self, **request_params) -> respx.Route:
+ route = _mantle_messages_route("us-east-1").mock(return_value=_anthropic_response())
+ await litellm.anthropic_messages(
+ model="bedrock_mantle/anthropic.claude-sonnet-5",
+ messages=[{"role": "user", "content": "ping"}],
+ max_tokens=8,
+ api_key="test-bearer",
+ aws_region_name="us-east-1",
+ **request_params,
+ )
+ return route
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_betas_mantle_accepts_reach_it_in_the_header(self):
+ route = await self._send(
+ extra_headers={
+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14,context-management-2025-06-27"
+ }
+ )
+
+ assert _sent_betas(route) == [
+ "claude-code-20250219",
+ "context-management-2025-06-27",
+ "interleaved-thinking-2025-05-14",
+ ]
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_betas_a_proxy_client_sends_reach_mantle_filtered(self):
+ from litellm.proxy.litellm_pre_call_utils import add_provider_specific_headers_to_request
+
+ proxy_request_data: dict = {}
+ add_provider_specific_headers_to_request(
+ data=proxy_request_data,
+ headers={
+ "anthropic-beta": "claude-code-20250219,fast-mode-2026-02-01,interleaved-thinking-2025-05-14",
+ "anthropic-version": "2023-06-01",
+ "user-agent": "claude-cli/2.1.239",
+ },
+ )
+
+ route = await self._send(**proxy_request_data)
+
+ assert _sent_betas(route) == ["claude-code-20250219", "interleaved-thinking-2025-05-14"]
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_betas_mantle_rejects_are_dropped_before_the_request(self):
+ route = await self._send(
+ extra_headers={"anthropic-beta": "code-execution-2025-08-25,context-1m-2025-08-07,files-api-2025-04-14"}
+ )
+
+ assert _sent_betas(route) == ["context-1m-2025-08-07"]
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_no_beta_header_is_sent_when_every_value_is_rejected(self):
+ route = await self._send(extra_headers={"anthropic-beta": "code-execution-2025-08-25"})
+
+ assert "anthropic-beta" not in route.calls.last.request.headers
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_advanced_tool_use_is_renamed_to_the_beta_mantle_knows(self):
+ route = await self._send(extra_headers={"anthropic-beta": "advanced-tool-use-2025-11-20"})
+
+ assert "tool-search-tool-2025-10-19" in _sent_betas(route)
+ assert "advanced-tool-use-2025-11-20" not in _sent_betas(route)
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_feature_beta_joins_the_callers_betas_in_the_header(self):
+ route = await self._send(
+ extra_headers={"anthropic-beta": "context-1m-2025-08-07"},
+ context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
+ )
+
+ assert _sent_betas(route) == ["context-1m-2025-08-07", "context-management-2025-06-27"]
+ assert _sent_body(route)["context_management"] == {"edits": [{"type": "clear_tool_uses_20250919"}]}
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_betas_and_version_never_travel_in_the_body(self):
+ route = await self._send(
+ extra_headers={"anthropic-beta": "context-1m-2025-08-07"},
+ context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
+ anthropic_version="bedrock-2023-05-31",
+ )
+
+ body = _sent_body(route)
+ assert "anthropic_beta" not in body
+ assert "anthropic_version" not in body
+ assert route.calls.last.request.headers["anthropic-version"] == "2023-06-01"
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_clear_thinking_edit_is_forwarded_with_thinking_on(self):
+ edits = [{"type": "clear_thinking_20251015", "keep": "all"}, {"type": "clear_tool_uses_20250919"}]
+ route = await self._send(
+ context_management={"edits": edits},
+ thinking={"type": "adaptive"},
+ )
+
+ body = _sent_body(route)
+ assert body["context_management"] == {"edits": edits}
+ assert body["thinking"] == {"type": "adaptive"}
+ assert "context-management-2025-06-27" in _sent_betas(route)
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_tools_reach_mantle_unchanged(self):
+ tools = [
+ {
+ "name": "get_weather",
+ "description": "Look up the weather",
+ "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+ }
+ ]
+ route = await self._send(tools=tools, tool_choice={"type": "auto"})
+
+ body = _sent_body(route)
+ assert body["tools"] == tools
+ assert body["tool_choice"] == {"type": "auto"}
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
index 3668a06203c..b2eded67430 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
@@ -1992,6 +1992,7 @@ async def test_streamable_http_session_manager_is_stateless():
(
("POST", b'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}', True),
("POST", b'{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}', False),
+ ("POST", b"", False),
("GET", b"", False),
("DELETE", b"", False),
),
@@ -2465,6 +2466,68 @@ async def test_mcp_routing_caps_body_peek_for_oversized_chunked_body():
assert total_streamed == len(first_chunk) + sum(len(b) for b in oversized_tail)
+@pytest.mark.asyncio
+@pytest.mark.parametrize("method", ("initialize", "tools/call"))
+@pytest.mark.parametrize("chunked", (False, True))
+@pytest.mark.parametrize(
+ ("character", "bytes_before_cap"),
+ (("é", 0), ("é", 1), ("ä¸", 1), ("ä¸", 2), ("😀", 1), ("😀", 2), ("😀", 3)),
+)
+async def test_mcp_routing_peek_survives_multibyte_char_split_at_cap(
+ method: str, chunked: bool, character: str, bytes_before_cap: int
+) -> None:
+ from litellm.proxy._experimental.mcp_server import server as mcp_module
+
+ params: Final = (
+ {
+ "protocolVersion": LATEST_HANDSHAKE_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "<
+ Requests with recorded LiteLLM injection or provider cache reads or writes. A cache hit alone does not + establish LiteLLM injection; older logs may not record it. +
++ Net savings are estimated from logged usage and current configured pricing, after cache-write premiums. + Negative values mean caching cost more; unavailable means the request could not be priced. +
+Select a date range to view requests
} + {enabled && requests.isPending && ( ++ Loading requests... +
+ )} + {enabled && requests.isError && ( +Could not load prompt caching requests
+ ++ No matching prompt caching requests in this range +
+ ) : ( +Date range for requests and cache leakage
+