Skip to content

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

chore: litellm oss staging 250626 (#31305)

Sameer Kankute7eacdd5258e9
diff --git a/litellm/caching/_embedding_router.py b/litellm/caching/_embedding_router.py
new file mode 100644
index 00000000000..1ec898012e9
--- /dev/null
+++ b/litellm/caching/_embedding_router.py
@@ -0,0 +1,45 @@
+"""Shared selection of the embedding path for semantic caches.
+
+Both the Redis and qdrant semantic caches need the same decision: when the
+configured embedding model is a proxy Router deployment, embeddings must run
+through the Router so per-deployment auth (e.g. Bedrock aws_role_name) is
+applied. Otherwise fall back to a direct litellm embedding call.
+
+This module is dependency-injected: callers pass the proxy ``llm_router`` and
+``llm_model_list`` in, so the decision logic is unit-testable without importing
+``litellm.proxy.proxy_server``.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from litellm.router import Router
+
+
+def resolve_embedding_router(
+ embedding_model: str,
+ llm_router: Router | None,
+ llm_model_list: list[dict[str, Any]] | None,
+) -> Router | None:
+ """Return ``llm_router`` iff it serves ``embedding_model`` as a deployment."""
+ if llm_router is None:
+ return None
+ router_model_names: list[str] = (
+ [m["model_name"] for m in llm_model_list if "model_name" in m]
+ if llm_model_list is not None
+ else []
+ )
+ if embedding_model in router_model_names:
+ return llm_router
+ return None
+
+
+def build_router_embedding_metadata(
+ request_metadata: dict[str, Any] | None,
+) -> dict[str, Any]:
+ """Forward the caller's full metadata, flagged as a semantic-cache embedding."""
+ metadata: dict[str, Any] = dict(request_metadata or {})
+ metadata["semantic-cache-embedding"] = True
+ return metadata
diff --git a/litellm/caching/caching.py b/litellm/caching/caching.py
index cb122e90102..5f2269d1945 100644
--- a/litellm/caching/caching.py
+++ b/litellm/caching/caching.py
@@ -574,8 +574,9 @@ class Cache:
if prompt_kwarg in kwargs:
cache_lookup_kwargs[prompt_kwarg] = kwargs[prompt_kwarg]
- if isinstance(kwargs.get("metadata"), dict):
- cache_lookup_kwargs["metadata"] = {}
+ metadata = kwargs.get("metadata")
+ if isinstance(metadata, dict):
+ cache_lookup_kwargs["metadata"] = dict(metadata)
return cache_lookup_kwargs
diff --git a/litellm/caching/qdrant_semantic_cache.py b/litellm/caching/qdrant_semantic_cache.py
index 68d3b8c20b3..504ef8a54eb 100644
--- a/litellm/caching/qdrant_semantic_cache.py
+++ b/litellm/caching/qdrant_semantic_cache.py
@@ -22,6 +22,7 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import (
)
from litellm.types.utils import EmbeddingResponse
+from ._embedding_router import build_router_embedding_metadata, resolve_embedding_router
from .base_cache import BaseCache
@@ -219,37 +220,50 @@ class QdrantSemanticCache(BaseCache):
cached_key = payload.get(self.CACHE_KEY_FIELD_NAME)
return cached_key is not None and str(cached_key) == str(key)
- async def _get_async_embedding(self, prompt: str, **kwargs) -> Any:
- llm_model_list = None
- llm_router = None
-
+ def _get_embedding(
+ self, prompt: str, metadata: Dict[str, Any] | None = None
+ ) -> EmbeddingResponse:
+ """Embed via the proxy Router when it serves the model, else direct."""
try:
- from litellm.proxy.proxy_server import (
- llm_model_list as proxy_llm_model_list,
- llm_router as proxy_llm_router,
+ from litellm.proxy.proxy_server import llm_model_list, llm_router
+ except ImportError:
+ llm_model_list = None
+ llm_router = None
+
+ router = resolve_embedding_router(
+ self.embedding_model, llm_router, llm_model_list
+ )
+ if router is not None:
+ return router.embedding(
+ model=self.embedding_model,
+ input=prompt,
+ cache={"no-store": True, "no-cache": True},
+ metadata=build_router_embedding_metadata(metadata),
)
+ return litellm.embedding(
+ model=self.embedding_model,
+ input=prompt,
+ cache={"no-store": True, "no-cache": True},
+ )
- llm_model_list = proxy_llm_model_list
- llm_router = proxy_llm_router
+ async def _get_async_embedding(
+ self, prompt: str, metadata: Dict[str, Any] | None = None
+ ) -> EmbeddingResponse:
+ try:
+ from litellm.proxy.proxy_server import llm_model_list, llm_router
except ImportError:
- pass
+ llm_model_list = None
+ llm_router = None
- router_model_names = (
- [m["model_name"] for m in llm_model_list]
- if llm_model_list is not None
- else []
+ router = resolve_embedding_router(
+ self.embedding_model, llm_router, llm_model_list
)
- if llm_router is not None and self.embedding_model in router_model_names:
- user_api_key = kwargs.get("metadata", {}).get("user_api_key", "")
- return await llm_router.aembedding(
+ if router is not None:
+ return await router.aembedding(
model=self.embedding_model,
input=prompt,
cache={"no-store": True, "no-cache": True},
- metadata={
- "user_api_key": user_api_key,
- "semantic-cache-embedding": True,
- "trace_id": kwargs.get("metadata", {}).get("trace_id", None),
- },
+ metadata=build_router_embedding_metadata(metadata),
)
return await litellm.aembedding(
@@ -269,11 +283,7 @@ class QdrantSemanticCache(BaseCache):
# create an embedding for prompt
embedding_response = cast(
EmbeddingResponse,
- litellm.embedding(
- model=self.embedding_model,
- input=prompt,
- cache={"no-store": True, "no-cache": True},
- ),
+ self._get_embedding(prompt, metadata=kwargs.get("metadata")),
)
# get the embedding
@@ -312,11 +322,7 @@ class QdrantSemanticCache(BaseCache):
# convert to embedding
embedding_response = cast(
EmbeddingResponse,
- litellm.embedding(
- model=self.embedding_model,
- input=prompt,
- cache={"no-store": True, "no-cache": True},
- ),
+ self._get_embedding(prompt, metadata=kwargs.get("metadata")),
)
# get the embedding
@@ -388,7 +394,9 @@ class QdrantSemanticCache(BaseCache):
# get the prompt
messages = kwargs["messages"]
prompt = get_str_from_messages(messages)
- embedding_response = await self._get_async_embedding(prompt, **kwargs)
+ embedding_response = await self._get_async_embedding(
+ prompt, metadata=kwargs.get("metadata")
+ )
# get the embedding
embedding = embedding_response["data"][0]["embedding"]
@@ -424,7 +432,9 @@ class QdrantSemanticCache(BaseCache):
messages = kwargs["messages"]
prompt = get_str_from_messages(messages)
- embedding_response = await self._get_async_embedding(prompt, **kwargs)
+ embedding_response = await self._get_async_embedding(
+ prompt, metadata=kwargs.get("metadata")
+ )
# get the embedding
embedding = embedding_response["data"][0]["embedding"]
diff --git a/litellm/caching/redis_semantic_cache.py b/litellm/caching/redis_semantic_cache.py
index cce4b75795f..e79392bb7f0 100644
--- a/litellm/caching/redis_semantic_cache.py
+++ b/litellm/caching/redis_semantic_cache.py
@@ -16,12 +16,13 @@ import os
from typing import Any, Dict, List, Optional, Tuple, cast
import litellm
-from litellm._logging import print_verbose
+from litellm._logging import print_verbose, verbose_logger
from litellm.litellm_core_utils.prompt_templates.common_utils import (
get_str_from_messages,
)
from litellm.types.utils import EmbeddingResponse
+from ._embedding_router import build_router_embedding_metadata, resolve_embedding_router
from .base_cache import BaseCache
@@ -67,9 +68,6 @@ class RedisSemanticCache(BaseCache):
Exception: If similarity_threshold is not provided or required Redis
connection information is missing
"""
- from redisvl.extensions.llmcache import SemanticCache # type: ignore[import-not-found, import-untyped]
- from redisvl.utils.vectorize import CustomTextVectorizer # type: ignore[import-not-found, import-untyped]
-
if index_name is None:
index_name = self.DEFAULT_REDIS_INDEX_NAME
@@ -107,15 +105,42 @@ class RedisSemanticCache(BaseCache):
print_verbose(f"Redis semantic-cache redis_url: {redis_url}")
- # Initialize the Redis vectorizer and cache
- cache_vectorizer = CustomTextVectorizer(self._get_embedding)
+ # Defer redisvl index construction until first use. redisvl's
+ # CustomTextVectorizer eagerly embeds a probe string at construction;
+ # building lazily ensures that probe runs after llm_router is wired so
+ # per-deployment auth (e.g. Bedrock aws_role_name) is applied.
+ self._index_name = index_name
+ self._redis_url = redis_url
+ self._llmcache = None
+
+ @property
+ def llmcache(self) -> object:
+ if getattr(self, "_llmcache", None) is None:
+ self._llmcache = self._build_llmcache()
+ return self._llmcache
+
+ @llmcache.setter
+ def llmcache(self, value: object) -> None:
+ self._llmcache = value
+
+ def _build_llmcache(self) -> object:
+ # CustomTextVectorizer probes its embedding dimension at construction by
+ # embedding "dimension test", so the first cache request issues one extra
+ # billable embedding on top of the request's own.
+ from redisvl.extensions.llmcache import SemanticCache # type: ignore[import-not-found, import-untyped]
+ from redisvl.utils.vectorize import CustomTextVectorizer # type: ignore[import-not-found, import-untyped]
- self.llmcache = self._init_semantic_cache(
- semantic_cache_cls=SemanticCache,
- index_name=index_name,
- redis_url=redis_url,
- cache_vectorizer=cache_vectorizer,
- )
+ try:
+ cache_vectorizer = CustomTextVectorizer(self._get_embedding)
+ return self._init_semantic_cache(
+ semantic_cache_cls=SemanticCache,
+ index_name=self._index_name,
+ redis_url=self._redis_url,
+ cache_vectorizer=cache_vectorizer,
+ )
+ except Exception as e:
+ verbose_logger.error(f"Redis semantic-cache index build failed: {e}")
+ raise
@classmethod
def _cache_key_filterable_field(cls) -> Dict[str, str]:
@@ -285,27 +310,43 @@ class RedisSemanticCache(BaseCache):
return dict_method()
return value
- def _get_embedding(self, prompt: str) -> List[float]:
+ def _get_embedding(
+ self, prompt: str, metadata: Dict[str, Any] | None = None
+ ) -> List[float]:
"""
- Generate an embedding vector for the given prompt using the configured embedding model.
-
- Args:
- prompt: The text to generate an embedding for
-
- Returns:
- List[float]: The embedding vector
+ Routes through the proxy Router when the embedding model is a Router
+ deployment so per-deployment auth (e.g. Bedrock aws_role_name) applies,
+ mirroring ``_get_async_embedding``; otherwise embeds directly.
"""
- # Create an embedding from prompt
- embedding_response = cast(
- EmbeddingResponse,
- litellm.embedding(
- model=self.embedding_model,
- input=prompt,
- cache={"no-store": True, "no-cache": True},
- ),
+ try:
+ from litellm.proxy.proxy_server import llm_model_list, llm_router
+ except ImportError:
+ llm_model_list = None
+ llm_router = None
+
+ router = resolve_embedding_router(
+ self.embedding_model, llm_router, llm_model_list
)
- embedding = embedding_response["data"][0]["embedding"]
- return embedding
+ if router is not None:
+ embedding_response = cast(
+ EmbeddingResponse,
+ router.embedding(
+ model=self.embedding_model,
+ input=prompt,
+ cache={"no-store": True, "no-cache": True},
+ metadata=build_router_embedding_metadata(metadata),
+ ),
+ )
+ else:
+ embedding_response = cast(
+ EmbeddingResponse,
+ litellm.embedding(
+ model=self.embedding_model,
+ input=prompt,
+ cache={"no-store": True, "no-cache": True},
+ ),
+ )
+ return embedding_response["data"][0]["embedding"]
def _get_cache_logic(self, cached_response: Any) -> Any:
"""
@@ -357,7 +398,12 @@ class RedisSemanticCache(BaseCache):
value_str = str(value)
- store_kwargs: Dict[str, Any] = {
+ prompt_embedding = self._get_embedding(
+ prompt, metadata=kwargs.get("metadata")
+ )
+
+ store_kwargs: dict[str, Any] = {
+ "vector": prompt_embedding,
"filters": self._get_cache_filters(key),
}
@@ -393,8 +439,12 @@ class RedisSemanticCache(BaseCache):
# Check the cache for semantically similar prompts in this exact
# LiteLLM cache-key scope.
- check_kwargs: Dict[str, Any] = {
+ prompt_embedding = self._get_embedding(
+ prompt, metadata=kwargs.get("metadata")
+ )
+ check_kwargs: dict[str, Any] = {
"prompt": prompt,
+ "vector": prompt_embedding,
"filter_expression": self._get_cache_key_filter_expression(key),
}
results = self.llmcache.check(**check_kwargs)
@@ -435,49 +485,42 @@ class RedisSemanticCache(BaseCache):
print_verbose(f"Error retrieving from Redis semantic cache: {str(e)}")
kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
- async def _get_async_embedding(self, prompt: str, **kwargs) -> List[float]:
+ async def _get_async_embedding(
+ self, prompt: str, metadata: Dict[str, Any] | None = None
+ ) -> List[float]:
"""
Asynchronously generate an embedding for the given prompt.
Args:
prompt: The text to generate an embedding for
- **kwargs: Additional arguments that may contain metadata
+ metadata: Request metadata forwarded to the Router embedding call
Returns:
List[float]: The embedding vector
"""
- from litellm.proxy.proxy_server import llm_model_list, llm_router
+ try:
+ from litellm.proxy.proxy_server import llm_model_list, llm_router
+ except ImportError:
+ llm_model_list = None
+ llm_router = None
- # Route the embedding request through the proxy if appropriate
- router_model_names = (
- [m["model_name"] for m in llm_model_list]
- if llm_model_list is not None
- else []
+ router = resolve_embedding_router(
+ self.embedding_model, llm_router, llm_model_list
)
-
try:
- if llm_router is not None and self.embedding_model in router_model_names:
- # Use the router for embedding generation
- user_api_key = kwargs.get("metadata", {}).get("user_api_key", "")
- embedding_response = await llm_router.aembedding(
+ if router is not None:
+ embedding_response = await router.aembedding(
model=self.embedding_model,
input=prompt,
cache={"no-store": True, "no-cache": True},
- metadata={
- "user_api_key": user_api_key,
- "semantic-cache-embedding": True,
- "trace_id": kwargs.get("metadata", {}).get("trace_id", None),
- },
+ metadata=build_router_embedding_metadata(metadata),
)
else:
- # Generate embedding directly
embedding_response = await litellm.aembedding(
model=self.embedding_model,
input=prompt,
cache={"no-store": True, "no-cache": True},
)
-
- # Extract and return the embedding vector
return embedding_response["data"][0]["embedding"]
except Exception as e:
print_verbose(f"Error generating async embedding: {str(e)}")
@@ -504,9 +547,11 @@ class RedisSemanticCache(BaseCache):
value_str = str(value)
# Generate embedding for the value (response) to cache
- prompt_embedding = await self._get_async_embedding(prompt, **kwargs)
+ prompt_embedding = await self._get_async_embedding(
+ prompt, metadata=kwargs.get("metadata")
+ )
- store_kwargs: Dict[str, Any] = {
+ store_kwargs: dict[str, Any] = {
"vector": prompt_embedding,
"filters": self._get_cache_filters(key),
}
@@ -544,11 +589,13 @@ class RedisSemanticCache(BaseCache):
return None
# Generate embedding for the prompt
- prompt_embedding = await self._get_async_embedding(prompt, **kwargs)
+ prompt_embedding = await self._get_async_embedding(
+ prompt, metadata=kwargs.get("metadata")
+ )
# Check the cache for semantically similar prompts in this exact
# LiteLLM cache-key scope.
- check_kwargs: Dict[str, Any] = {
+ check_kwargs: dict[str, Any] = {
"prompt": prompt,
"vector": prompt_embedding,
"filter_expression": self._get_cache_key_filter_expression(key),
diff --git a/litellm/google_genai/main.py b/litellm/google_genai/main.py
index bdbb483dcf6..d35601c7e13 100644
--- a/litellm/google_genai/main.py
+++ b/litellm/google_genai/main.py
@@ -49,6 +49,7 @@ class GenerateContentSetupResult(BaseModel):
custom_llm_provider: str
generate_content_provider_config: Optional[BaseGoogleGenAIGenerateContentConfig]
generate_content_config_dict: Dict[str, Any]
+ native_request_fields: dict[str, object]
litellm_params: GenericLiteLLMParams
litellm_logging_obj: LiteLLMLoggingObj
litellm_call_id: Optional[str]
@@ -152,6 +153,7 @@ class GenerateContentHelper:
request_body={}, # Will be handled by adapter
generate_content_provider_config=None, # type: ignore
generate_content_config_dict=dict(config or {}),
+ native_request_fields={},
litellm_params=litellm_params,
litellm_logging_obj=litellm_logging_obj,
litellm_call_id=litellm_call_id,
@@ -171,6 +173,12 @@ class GenerateContentHelper:
system_instruction = kwargs.get("systemInstruction") or kwargs.get(
"system_instruction"
)
+ # Native top-level REST fields arrive as loose kwargs and are otherwise dropped.
+ native_request_fields: dict[str, object] = {
+ field: kwargs[field]
+ for field in generate_content_provider_config.get_generate_content_request_top_level_fields()
+ if field in kwargs
+ }
request_body = (
generate_content_provider_config.transform_generate_content_request(
model=model,
@@ -201,12 +209,29 @@ class GenerateContentHelper:
request_body=request_body,
generate_content_provider_config=generate_content_provider_config,
generate_content_config_dict=generate_content_config_dict,
+ native_request_fields=native_request_fields,
litellm_params=litellm_params,
litellm_logging_obj=litellm_logging_obj,
litellm_call_id=litellm_call_id,
)
+def _merge_native_request_fields(
+ native_request_fields: dict[str, object],
+ extra_body: dict[str, object] | None,
+) -> dict[str, object] | None:
+ """
+ Merge native top-level request fields into ``extra_body`` so the HTTP handler
+ forwards them verbatim onto the outgoing request body. An explicit ``extra_body``
+ value wins on conflict. Returns ``None`` only when there is genuinely nothing to
+ forward (no native fields and no caller-supplied ``extra_body``), preserving the
+ prior behavior without discarding an explicit ``extra_body={}``.
+ """
+ if not native_request_fields and extra_body is None:
+ return None
+ return {**native_request_fields, **(extra_body or {})}
+
+
@client
async def agenerate_content(
model: str,
@@ -350,7 +375,9 @@ def generate_content(
litellm_params=setup_result.litellm_params,
logging_obj=setup_result.litellm_logging_obj,
extra_headers=extra_headers,
- extra_body=extra_body,
+ extra_body=_merge_native_request_fields(
+ setup_result.native_request_fields, extra_body
+ ),
timeout=timeout or request_timeout,
_is_async=_is_async,
client=kwargs.get("client"),
@@ -447,7 +474,9 @@ async def agenerate_content_stream(
litellm_params=setup_result.litellm_params,
logging_obj=setup_result.litellm_logging_obj,
extra_headers=extra_headers,
- extra_body=extra_body,
+ extra_body=_merge_native_request_fields(
+ setup_result.native_request_fields, extra_body
+ ),
timeout=timeout or request_timeout,
_is_async=True,
client=kwargs.get("client"),
@@ -503,6 +532,11 @@ def generate_content_stream(
**kwargs,
)
+ # Extract systemInstruction from kwargs to pass to handler
+ system_instruction = kwargs.get("systemInstruction") or kwargs.get(
+ "system_instruction"
+ )
+
# Check if we should use the adapter (when provider config is None)
if setup_result.generate_content_provider_config is None:
if "stream" in kwargs:
@@ -531,12 +565,15 @@ def generate_content_stream(
litellm_params=setup_result.litellm_params,
logging_obj=setup_result.litellm_logging_obj,
extra_headers=extra_headers,
- extra_body=extra_body,
+ extra_body=_merge_native_request_fields(
+ setup_result.native_request_fields, extra_body
+ ),
timeout=timeout or request_timeout,
_is_async=_is_async,
client=kwargs.get("client"),
stream=True,
litellm_metadata=kwargs.get("litellm_metadata", {}),
+ system_instruction=system_instruction,
)
except Exception as e:
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index bf9ce3b0acb..4bdda6de2c8 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -466,7 +466,7 @@ def get_format_from_file_id(file_id: Optional[str]) -> Optional[str]:
def update_messages_with_model_file_ids(
messages: List[AllMessageValues],
- model_id: str,
+ model_id: str | None,
model_file_id_mapping: Dict[str, Dict[str, str]],
) -> List[AllMessageValues]:
"""
@@ -519,7 +519,7 @@ def update_messages_with_model_file_ids(
if file_id:
provider_file_id = (
model_file_id_mapping.get(file_id, {}).get(model_id)
- if model_file_id_mapping
+ if model_file_id_mapping and model_id is not None
else None
)
if (
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index 66abb824610..1b1b652eaa0 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -585,6 +585,17 @@ class ChunkProcessor:
# # Update usage information if needed
prompt_tokens = 0
completion_tokens = 0
+ # Anthropic's `message_start` SSE event carries usage.output_tokens=1 as a
+ # cursor/placeholder; the real value only arrives in `message_delta`.
+ # If a stream is cancelled before `message_delta` lands, the last-wins
+ # accumulator below leaves completion_tokens stuck at 1 — which then
+ # bypasses the `completion_tokens or token_counter(...)` fallback in
+ # calculate_usage() because 1 is truthy. Count the completion-bearing
+ # usage events so `_reset_anthropic_cursor_completion_tokens` can tell a
+ # legitimate single-token reply (Anthropic emits 1 in BOTH message_start
+ # AND message_delta, so >=2 events is positive evidence message_delta
+ # arrived) from a stale lone cursor.
+ completion_usage_updates = 0
## anthropic prompt caching information ##
cache_creation_input_tokens: Optional[int] = None
cache_read_input_tokens: Optional[int] = None
@@ -617,6 +628,7 @@ class ChunkProcessor:
and usage_chunk_dict["completion_tokens"] > 0
):
completion_tokens = usage_chunk_dict["completion_tokens"]
+ completion_usage_updates += 1
if usage_chunk_dict["cache_creation_input_tokens"] is not None and (
usage_chunk_dict["cache_creation_input_tokens"] > 0
or cache_creation_input_tokens is None
@@ -667,6 +679,12 @@ class ChunkProcessor:
prompt_tokens_details = usage_chunk_dict["prompt_tokens_details"]
+ completion_tokens = self._reset_anthropic_cursor_completion_tokens(
+ chunks=chunks,
+ completion_tokens=completion_tokens,
+ completion_usage_updates=completion_usage_updates,
+ )
+
return UsagePerChunk(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
@@ -678,6 +696,47 @@ class ChunkProcessor:
prompt_tokens_details=prompt_tokens_details,
)
+ @staticmethod
+ def _reset_anthropic_cursor_completion_tokens(
+ chunks: list[dict[str, Any] | ModelResponse],
+ completion_tokens: int,
+ completion_usage_updates: int,
+ ) -> int:
+ """Reset a stale Anthropic ``message_start`` cursor placeholder to 0.
+
+ See the ``completion_usage_updates`` comment in
+ ``_calculate_usage_per_chunk``. The accumulated value is NOT a stale
+ cursor when either it is > 1 (definitely not a placeholder) or we saw
+ >= 2 completion-bearing usage events (positive evidence ``message_delta``
+ arrived). Otherwise — the only completion update we ever saw was the
+ Anthropic ``message_start`` cursor (=1) — reset to 0 so
+ ``calculate_usage()``'s ``or token_counter(text=...)`` fallback estimates
+ from the actually-received completion text instead of trusting the
+ placeholder. Gated on ``custom_llm_provider == "anthropic"`` so the
+ heuristic (which encodes Anthropic's specific message_start SSE shape)
+ does not silently affect other providers that may legitimately report
+ ``completion_tokens=1`` from a single usage event.
+ """
+ saw_non_cursor_completion = (
+ completion_tokens > 1 or completion_usage_updates >= 2
+ )
+ if saw_non_cursor_completion:
+ return completion_tokens
+
+ custom_llm_provider: Optional[str] = None
+ if chunks:
+ first_chunk = chunks[0]
+ if isinstance(first_chunk, dict):
+ hp = first_chunk.get("_hidden_params")
+ else:
+ hp = getattr(first_chunk, "_hidden_params", None)
+ if isinstance(hp, dict):
+ custom_llm_provider = hp.get("custom_llm_provider")
+
+ if custom_llm_provider == "anthropic" and completion_tokens == 1:
+ return 0
+ return completion_tokens
+
def calculate_usage(
self,
chunks: List[Union[Dict[str, Any], ModelResponse]],
diff --git a/litellm/llms/anthropic/batches/transformation.py b/litellm/llms/anthropic/batches/transformation.py
index fd67a7fbaf1..7c4e9386d5f 100644
--- a/litellm/llms/anthropic/batches/transformation.py
+++ b/litellm/llms/anthropic/batches/transformation.py
@@ -43,7 +43,9 @@ class AnthropicBatchesConfig(BaseBatchesConfig):
api_base: Optional[str] = None,
) -> dict:
"""Validate and prepare environment-specific headers and parameters."""
- auth_header = self.anthropic_model_info.get_auth_header(api_key)
+ if api_base is None and isinstance(litellm_params, dict):
+ api_base = litellm_params.get("api_base")
+ auth_header = self.anthropic_model_info.get_auth_header(api_key, api_base)
if auth_header is None:
raise ValueError(
"Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params"
diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py
index e7e0f12c455..b1212f93059 100644
--- a/litellm/llms/anthropic/chat/handler.py
+++ b/litellm/llms/anthropic/chat/handler.py
@@ -364,6 +364,7 @@ class AnthropicChatCompletion(BaseLLM):
messages=messages,
optional_params={**optional_params, "is_vertex_request": is_vertex_request},
litellm_params=litellm_params,
+ api_base=api_base,
)
config = ProviderConfigManager.get_provider_chat_config(
diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py
index eaa762204f2..d27187cf2e7 100644
--- a/litellm/llms/anthropic/common_utils.py
+++ b/litellm/llms/anthropic/common_utils.py
@@ -548,6 +548,19 @@ class AnthropicModelInfo(BaseLLMModelInfo):
return list(set(betas))
+ @staticmethod
+ def _make_api_key_auth_header(
+ api_key: str, api_base: str | None, use_bearer_for_custom_base: bool = False
+ ) -> dict:
+ if use_bearer_for_custom_base and (
+ api_base
+ and "api.anthropic.com" not in api_base
+ and not api_key.startswith("sk-ant-")
+ ):
+ value = api_key if api_key.startswith("Bearer ") else f"Bearer {api_key}"
+ return {"authorization": value}
+ return {"x-api-key": api_key}
+
def get_anthropic_headers(
self,
api_key: Optional[str] = None,
@@ -567,6 +580,8 @@ class AnthropicModelInfo(BaseLLMModelInfo):
user_anthropic_beta_headers: Optional[List[str]] = None,
code_execution_tool_used: bool = False,
container_with_skills_used: bool = False,
+ api_base: str | None = None,
+ use_bearer_for_custom_base: bool = False,
) -> dict:
betas = set()
# Anthropic no longer requires the prompt-caching beta header
@@ -615,7 +630,11 @@ class AnthropicModelInfo(BaseLLMModelInfo):
elif auth_token and not api_key:
headers["authorization"] = f"Bearer {auth_token}"
elif api_key:
- headers["x-api-key"] = api_key
+ headers.update(
+ self._make_api_key_auth_header(
+ api_key, api_base, use_bearer_for_custom_base
+ )
+ )
if user_anthropic_beta_headers is not None:
betas.update(user_anthropic_beta_headers)
@@ -644,6 +663,12 @@ class AnthropicModelInfo(BaseLLMModelInfo):
api_key: Optional[str] = None,
api_base: Optional[str] = None,
) -> Dict:
+ if api_base is None and isinstance(litellm_params, dict):
+ api_base = litellm_params.get("api_base")
+ use_bearer_for_custom_base: bool = bool(
+ isinstance(litellm_params, dict)
+ and litellm_params.get("use_bearer_for_custom_base", False)
+ )
# Check for Anthropic OAuth token in headers
headers, api_key = optionally_handle_anthropic_oauth(
headers=headers, api_key=api_key
@@ -699,6 +724,8 @@ class AnthropicModelInfo(BaseLLMModelInfo):
effort_used=effort_used,
code_execution_tool_used=code_execution_tool_used,
container_with_skills_used=container_with_skills_used,
+ api_base=api_base,
+ use_bearer_for_custom_base=use_bearer_for_custom_base,
)
headers = {**headers, **anthropic_headers}
@@ -734,18 +761,24 @@ class AnthropicModelInfo(BaseLLMModelInfo):
return auth_token or get_secret_str("ANTHROPIC_AUTH_TOKEN")
@staticmethod
- def get_auth_header(api_key: Optional[str] = None) -> Optional[dict]:
+ def get_auth_header(
+ api_key: str | None = None,
+ api_base: str | None = None,
+ use_bearer_for_custom_base: bool = False,
+ ) -> dict | None:
"""Resolve Anthropic credentials and return the appropriate auth header dict.
- Checks ANTHROPIC_API_KEY first (-> x-api-key), then
- ANTHROPIC_AUTH_TOKEN (-> Authorization: Bearer).
+ Checks ANTHROPIC_API_KEY first (-> x-api-key or Bearer depending on
+ use_bearer_for_custom_base), then ANTHROPIC_AUTH_TOKEN (-> Authorization: Bearer).
Returns None if neither is available.
"""
resolved_key = AnthropicModelInfo.get_api_key(api_key)
if resolved_key is not None:
if is_anthropic_oauth_key(resolved_key):
return {"authorization": f"Bearer {resolved_key}"}
- return {"x-api-key": resolved_key}
+ return AnthropicModelInfo._make_api_key_auth_header(
+ resolved_key, api_base, use_bearer_for_custom_base
+ )
auth_token = AnthropicModelInfo.get_auth_token()
if auth_token is not None:
return {"authorization": f"Bearer {auth_token}"}
@@ -759,7 +792,7 @@ class AnthropicModelInfo(BaseLLMModelInfo):
self, api_key: Optional[str] = None, api_base: Optional[str] = None
) -> List[str]:
api_base = AnthropicModelInfo.get_api_base(api_base)
- auth_header = AnthropicModelInfo.get_auth_header(api_key)
+ auth_header = AnthropicModelInfo.get_auth_header(api_key, api_base)
if api_base is None or auth_header is None:
raise ValueError(
"ANTHROPIC_API_BASE/ANTHROPIC_BASE_URL or ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN is not set. Please set the environment variable, to query Anthropic's `/models` endpoint."
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
index 9860997b1cd..a92834b5d71 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
@@ -205,32 +205,11 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
if "delta" not in merged_chunk:
merged_chunk["delta"] = {}
- uncached_input_tokens = chunk.usage.prompt_tokens or 0
- if (
- hasattr(chunk.usage, "prompt_tokens_details")
- and chunk.usage.prompt_tokens_details
- ):
- cached_tokens = (
- getattr(chunk.usage.prompt_tokens_details, "cached_tokens", 0) or 0
- )
- uncached_input_tokens -= cached_tokens
+ from .transformation import LiteLLMAnthropicMessagesAdapter
- usage_dict: UsageDelta = {
- "input_tokens": uncached_input_tokens,
- "output_tokens": chunk.usage.completion_tokens or 0,
- }
- if (
- hasattr(chunk.usage, "_cache_creation_input_tokens")
- and chunk.usage._cache_creation_input_tokens > 0
- ):
- usage_dict["cache_creation_input_tokens"] = (
- chunk.usage._cache_creation_input_tokens
- )
- if (
- hasattr(chunk.usage, "_cache_read_input_tokens")
- and chunk.usage._cache_read_input_tokens > 0
- ):
- usage_dict["cache_read_input_tokens"] = chunk.usage._cache_read_input_tokens
+ usage_dict: UsageDelta = LiteLLMAnthropicMessagesAdapter._translate_openai_usage_to_anthropic_usage_delta(
+ chunk.usage
+ )
merged_chunk["usage"] = usage_dict
if self.applied_edits and "context_management" not in merged_chunk:
merged_chunk["context_management"] = ContextManagementResponse(
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index 46564a565ce..1fd593f63c8 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@ -1399,6 +1399,95 @@ class LiteLLMAnthropicMessagesAdapter:
return "tool_use"
return "end_turn"
+ @staticmethod
+ def _positive_int(value: object) -> int:
+ if isinstance(value, bool):
+ return 0
+ if isinstance(value, int) and value > 0:
+ return value
+ if isinstance(value, float) and value.is_integer() and value > 0:
+ return int(value)
+ return 0
+
+ @classmethod
+ def _first_positive_usage_value(
+ cls, usage: Usage, field_names: tuple[str, ...]
+ ) -> int:
+ for field_name in field_names:
+ value = cls._positive_int(getattr(usage, field_name, None))
+ if value > 0:
+ return value
+ return 0
+
+ @classmethod
+ def _first_positive_prompt_tokens_detail_value(
+ cls, usage: Usage, field_names: tuple[str, ...]
+ ) -> int:
+ prompt_tokens_details = getattr(usage, "prompt_tokens_details", None)
+ if prompt_tokens_details is None:
+ return 0
+
+ for field_name in field_names:
+ if isinstance(prompt_tokens_details, dict):
+ value = cls._positive_int(prompt_tokens_details.get(field_name))
+ else:
+ value = cls._positive_int(
+ getattr(prompt_tokens_details, field_name, None)
+ )
+ if value > 0:
+ return value
+ return 0
+
+ @classmethod
+ def _get_cache_read_input_tokens(cls, usage: Usage) -> int:
+ explicit_value = cls._first_positive_usage_value(
+ usage, ("cache_read_input_tokens", "_cache_read_input_tokens")
+ )
+ if explicit_value > 0:
+ return explicit_value
+ return cls._first_positive_prompt_tokens_detail_value(usage, ("cached_tokens",))
+
+ @classmethod
+ def _get_cache_creation_input_tokens(cls, usage: Usage) -> int:
+ explicit_value = cls._first_positive_usage_value(
+ usage, ("cache_creation_input_tokens", "_cache_creation_input_tokens")
+ )
+ if explicit_value > 0:
+ return explicit_value
+ return cls._first_positive_prompt_tokens_detail_value(
+ usage, ("cache_creation_tokens", "cache_write_tokens")
+ )
+
+ @classmethod
+ def _translate_openai_usage_to_anthropic_usage_delta(
+ cls, usage: Usage
+ ) -> UsageDelta:
+ cache_read_input_tokens = cls._get_cache_read_input_tokens(usage)
+ cache_creation_input_tokens = cls._get_cache_creation_input_tokens(usage)
+ input_tokens = max(
+ (usage.prompt_tokens or 0)
+ - cache_read_input_tokens
+ - cache_creation_input_tokens,
+ 0,
+ )
+
+ usage_delta = UsageDelta(
+ input_tokens=input_tokens,
+ output_tokens=usage.completion_tokens or 0,
+ )
+ if cache_creation_input_tokens > 0:
+ usage_delta["cache_creation_input_tokens"] = cache_creation_input_tokens
+ if cache_read_input_tokens > 0:
+ usage_delta["cache_read_input_tokens"] = cache_read_input_tokens
+ return usage_delta
+
+ @classmethod
+ def _translate_openai_usage_to_anthropic_usage(cls, usage: Usage) -> AnthropicUsage:
+ return cast(
+ AnthropicUsage,
+ cls._translate_openai_usage_to_anthropic_usage_delta(usage),
+ )
+
def translate_openai_response_to_anthropic(
self,
response: ModelResponse,
@@ -1430,32 +1519,12 @@ class LiteLLMAnthropicMessagesAdapter:
)
# extract usage
usage: Usage = getattr(response, "usage")
- uncached_input_tokens = usage.prompt_tokens or 0
- cached_tokens = 0
- if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details:
- cached_tokens = (
- getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0
- )
- uncached_input_tokens -= cached_tokens
-
- anthropic_usage = AnthropicUsage(
- input_tokens=uncached_input_tokens,
- output_tokens=usage.completion_tokens or 0,
- )
- if (
- hasattr(usage, "_cache_creation_input_tokens")
- and usage._cache_creation_input_tokens > 0
- ):
- anthropic_usage["cache_creation_input_tokens"] = (
- usage._cache_creation_input_tokens
- )
- if cached_tokens > 0:
- anthropic_usage["cache_read_input_tokens"] = cached_tokens
+ anthropic_usage = self._translate_openai_usage_to_anthropic_usage(usage)
if polyfill_result is not None and polyfill_result.iterations_usage is not None:
message_iteration: UsageIteration = {
"type": "message",
- "input_tokens": uncached_input_tokens,
+ "input_tokens": anthropic_usage["input_tokens"],
"output_tokens": usage.completion_tokens or 0,
}
anthropic_usage["iterations"] = list(polyfill_result.iterations_usage) + [
@@ -1644,35 +1713,9 @@ class LiteLLMAnthropicMessagesAdapter:
else:
litellm_usage_chunk = None
if litellm_usage_chunk is not None:
- uncached_input_tokens = litellm_usage_chunk.prompt_tokens or 0
- cached_tokens = 0
- if (
- hasattr(litellm_usage_chunk, "prompt_tokens_details")
- and litellm_usage_chunk.prompt_tokens_details
- ):
- cached_tokens = (
- getattr(
- litellm_usage_chunk.prompt_tokens_details,
- "cached_tokens",
- 0,
- )
- or 0
- )
- uncached_input_tokens -= cached_tokens
-
- usage_delta = UsageDelta(
- input_tokens=uncached_input_tokens,
- output_tokens=litellm_usage_chunk.completion_tokens or 0,
+ usage_delta = self._translate_openai_usage_to_anthropic_usage_delta(
+ litellm_usage_chunk
)
- if (
- hasattr(litellm_usage_chunk, "_cache_creation_input_tokens")
- and litellm_usage_chunk._cache_creation_input_tokens > 0
- ):
- usage_delta["cache_creation_input_tokens"] = (
- litellm_usage_chunk._cache_creation_input_tokens
- )
- if cached_tokens > 0:
- usage_delta["cache_read_input_tokens"] = cached_tokens
else:
usage_delta = UsageDelta(input_tokens=0, output_tokens=0)
message_block = MessageBlockDelta(
diff --git a/litellm/llms/anthropic/files/handler.py b/litellm/llms/anthropic/files/handler.py
index 56296df94a1..170cb086bb0 100644
--- a/litellm/llms/anthropic/files/handler.py
+++ b/litellm/llms/anthropic/files/handler.py
@@ -84,7 +84,7 @@ class AnthropicFilesHandler:
# Get Anthropic API credentials
api_base = self.anthropic_model_info.get_api_base(api_base)
- auth_header = self.anthropic_model_info.get_auth_header(api_key)
+ auth_header = self.anthropic_model_info.get_auth_header(api_key, api_base)
if auth_header is None:
raise ValueError("Missing Anthropic API Key")
diff --git a/litellm/llms/anthropic/files/transformation.py b/litellm/llms/anthropic/files/transformation.py
index ea9bf00f505..7ffb6beb4c7 100644
--- a/litellm/llms/anthropic/files/transformation.py
+++ b/litellm/llms/anthropic/files/transformation.py
@@ -95,7 +95,9 @@ class AnthropicFilesConfig(BaseFilesConfig):
api_key: Optional[str] = None,
api_base: Optional[str] = None,
) -> dict:
- auth_header = AnthropicModelInfo.get_auth_header(api_key)
+ if api_base is None and isinstance(litellm_params, dict):
+ api_base = litellm_params.get("api_base")
+ auth_header = AnthropicModelInfo.get_auth_header(api_key, api_base)
if auth_header is None:
raise ValueError(
"Anthropic API key is required. Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN environment variable or pass api_key parameter."
diff --git a/litellm/llms/anthropic/skills/transformation.py b/litellm/llms/anthropic/skills/transformation.py
index 4ea768b02af..2bfdf7ef4ba 100644
--- a/litellm/llms/anthropic/skills/transformation.py
+++ b/litellm/llms/anthropic/skills/transformation.py
@@ -38,10 +38,12 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig):
# Get API key from litellm_params if available
api_key = None
+ api_base = None
if litellm_params is not None:
api_key = litellm_params.api_key
+ api_base = litellm_params.api_base
- auth_header = AnthropicModelInfo.get_auth_header(api_key)
+ auth_header = AnthropicModelInfo.get_auth_header(api_key, api_base)
if auth_header is None:
raise ValueError(
"ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN is required for Skills API"
diff --git a/litellm/llms/base_llm/google_genai/transformation.py b/litellm/llms/base_llm/google_genai/transformation.py
index e8b3bf1a576..8fb7eb9fde0 100644
--- a/litellm/llms/base_llm/google_genai/transformation.py
+++ b/litellm/llms/base_llm/google_genai/transformation.py
@@ -62,6 +62,19 @@ class BaseGoogleGenAIGenerateContentConfig(ABC):
"get_supported_generate_content_optional_params is not implemented"
)
+ def get_generate_content_request_top_level_fields(self) -> tuple[str, ...]:
+ """
+ Native Google ``GenerateContentRequest`` fields that sit at the top level
+ (siblings of ``generationConfig``) rather than inside it. The proxy forwards
+ these verbatim from a native request so ``generateContent`` is a drop-in for
+ Google's REST API.
+
+ Excludes ``contents``, ``model`` and ``tools`` (dedicated params),
+ ``systemInstruction`` (dedicated extraction) and ``generationConfig`` (mapped
+ to ``config``).
+ """
+ return ("safetySettings", "toolConfig", "cachedContent", "labels")
+
@abstractmethod
def map_generate_content_optional_params(
self,
diff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.py
index 5e97394f459..69c0a8529b4 100644
--- a/litellm/llms/bedrock/common_utils.py
+++ b/litellm/llms/bedrock/common_utils.py
@@ -904,9 +904,12 @@ class BedrockModelInfo(BaseLLMModelInfo):
"mantle/": "mantle",
}
- # Check explicit routes first
+ # Check explicit routes first. Match each prefix only as a leading path
+ # segment so the `bedrock_mantle/` provider prefix is never mistaken for
+ # the `mantle/` invoke route (which would mangle
+ # `bedrock_mantle/openai.gpt-5.5` into `bedrock_openai.gpt-5.5`).
for prefix, route_type in route_mappings.items():
- if prefix in model:
+ if BedrockModelInfo._model_has_route_prefix(model, prefix):
return route_type
# Check for nova spec prefixes (nova/ and nova-2/)
@@ -930,14 +933,14 @@ class BedrockModelInfo(BaseLLMModelInfo):
"""
Check if the model is an explicit converse route.
"""
- return "converse/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "converse/")
@staticmethod
def _explicit_claude_platform_route(model: str) -> bool:
"""
Check if the model is an explicit Claude Platform on AWS route.
"""
- return "claude_platform/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "claude_platform/")
@staticmethod
def get_claude_platform_model(model: str) -> str:
@@ -967,42 +970,58 @@ class BedrockModelInfo(BaseLLMModelInfo):
"""
Check if the model is an explicit invoke route.
"""
- return "invoke/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "invoke/")
@staticmethod
def _explicit_agent_route(model: str) -> bool:
"""
Check if the model is an explicit agent route.
"""
- return "agent/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "agent/")
@staticmethod
def _explicit_agentcore_route(model: str) -> bool:
"""
Check if the model is an explicit agentcore route.
"""
- return "agentcore/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "agentcore/")
+
+ @staticmethod
+ def _model_has_route_prefix(model: str, prefix: str) -> bool:
+ """Whether a route prefix (e.g. ``mantle/``) appears as a leading path segment.
+
+ A route token is only valid at the start of the model id or immediately
+ after a ``/``. A plain substring check matches the ``bedrock_mantle/``
+ provider prefix against the ``mantle/`` route, so the body model gets
+ mangled to ``bedrock_openai.gpt-5.5``; anchoring to a segment boundary
+ keeps the bare model id intact.
+
+ ``f"/{prefix}" in model`` matches the token as a segment at any path
+ depth, not just the second segment; that is intentional and acceptable
+ for these short, unambiguous route tokens.
+ """
+ return model.startswith(prefix) or f"/{prefix}" in model
@staticmethod
def _explicit_mantle_route(model: str) -> bool:
"""
Check if the model is an explicit mantle route (bedrock-mantle endpoint).
"""
- return "mantle/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "mantle/")
@staticmethod
def _explicit_converse_like_route(model: str) -> bool:
"""
Check if the model is an explicit converse like route.
"""
- return "converse_like/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "converse_like/")
@staticmethod
def _explicit_async_invoke_route(model: str) -> bool:
"""
Check if the model is an explicit async invoke route.
"""
- return "async_invoke/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "async_invoke/")
@staticmethod
def _explicit_openai_route(model: str) -> bool:
@@ -1010,7 +1029,7 @@ class BedrockModelInfo(BaseLLMModelInfo):
Check if the model is an explicit openai route.
Used for Bedrock imported models that use OpenAI Chat Completions format.
"""
- return "openai/" in model
+ return BedrockModelInfo._model_has_route_prefix(model, "openai/")
@staticmethod
def get_bedrock_provider_config_for_messages_api(
diff --git a/litellm/llms/vertex_ai/gemini/transformation.py b/litellm/llms/vertex_ai/gemini/transformation.py
index 79f006a83de..3bdcbd25949 100644
--- a/litellm/llms/vertex_ai/gemini/transformation.py
+++ b/litellm/llms/vertex_ai/gemini/transformation.py
@@ -1046,9 +1046,9 @@ def _gemini_convert_messages_with_history(
if invocation.get("tool_type"):
tr_dict["toolType"] = invocation["tool_type"]
tr_part: Dict[str, Any] = {"toolResponse": tr_dict}
- if "thought_signature" in invocation:
+ if "response_thought_signature" in invocation:
tr_part["thoughtSignature"] = invocation[
- "thought_signature"
+ "response_thought_signature"
]
assistant_content.append(tr_part) # type: ignore
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index 0de34ec257c..423a5dd5d17 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -1634,13 +1634,16 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
resp = tool_responses_by_id.pop(call_id, None)
if resp is not None:
merged["response"] = resp.get("response")
- # Keep response signature if call didn't have one
- if "thought_signature" not in merged and "thought_signature" in resp:
- merged["thought_signature"] = resp["thought_signature"]
+ if "thought_signature" in resp:
+ merged["response_thought_signature"] = resp["thought_signature"]
invocations.append(merged)
# Any orphan responses (shouldn't happen, but be safe)
for resp_id, resp_entry in tool_responses_by_id.items():
+ if "thought_signature" in resp_entry:
+ resp_entry["response_thought_signature"] = resp_entry[
+ "thought_signature"
+ ]
invocations.append(resp_entry)
return invocations if invocations else None
diff --git a/litellm/main.py b/litellm/main.py
index 1960c456f80..cdea7dbd684 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -633,6 +633,7 @@ async def acompletion(
try:
# Use a partial function to pass your keyword arguments
+ kwargs.pop("acompletion", None)
func = partial(completion, **completion_kwargs, **kwargs)
# Add the context to the function
@@ -5063,6 +5064,12 @@ def completion( # type: ignore
######### unpacking kwargs #####################
args = locals()
+ # Set by the responses->completion fallback so completion() does not bridge
+ # back to the Responses API: that round-trip mutually recurses forever for a
+ # model whose model_cost mode is "responses" but whose provider has no
+ # Responses API config (get_provider_responses_api_config -> None).
+ skip_responses_api_bridge = kwargs.pop("_skip_responses_api_bridge", False)
+
skip_mcp_handler = kwargs.pop("_skip_mcp_handler", False)
if not skip_mcp_handler and tools:
from litellm.responses.mcp.chat_completions_handler import acompletion_with_mcp
@@ -5358,7 +5365,7 @@ def completion( # type: ignore
messages = update_messages_with_model_file_ids(
messages=messages,
- model_id=kwargs.get("model_info", {}).get("id", None),
+ model_id=(kwargs.get("model_info") or {}).get("id", None),
model_file_id_mapping=cast(
Dict[str, Dict[str, str]],
kwargs.get("model_file_id_mapping") or {},
@@ -5560,7 +5567,10 @@ def completion( # type: ignore
# detection when the deployment name differs from the model name.
_azure_detection_model = base_model or model
- if responses_api_model_info.get("mode") == "responses":
+ if (
+ responses_api_model_info.get("mode") == "responses"
+ and not skip_responses_api_bridge
+ ):
from litellm.completion_extras import responses_api_bridge
optional_params, rs_val = (
diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
index 2149f079a3d..7b4f1e13a52 100644
--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
@@ -79,6 +79,7 @@ if MCP_AVAILABLE:
)
from litellm.proxy._experimental.mcp_server.server import (
ListMCPToolsRestAPIResponseObject,
+ MCPInfo,
MCPServer,
_tool_name_matches,
execute_mcp_tool,
@@ -238,14 +239,24 @@ if MCP_AVAILABLE:
)
return {}
- def _create_tool_response_objects(tools, server_mcp_info):
- """Helper function to create tool response objects."""
+ def _create_tool_response_objects(tools, server: MCPServer):
+ """Helper function to create tool response objects.
+
+ Enriches the server's ``mcp_info`` with ``server_id`` and ``alias`` so
+ REST clients can map the internal ``server_name`` to the user-facing
+ alias without needing access to the ``mcp_routes``-gated server listing.
+ """
+ enriched_mcp_info: MCPInfo = {
+ **(server.mcp_info or {}),
+ "server_id": server.server_id,
+ "alias": server.alias,
+ }
return [
ListMCPToolsRestAPIResponseObject(
name=tool.name,
description=tool.description,
inputSchema=tool.inputSchema,
- mcp_info=server_mcp_info,
+ mcp_info=enriched_mcp_info,
)
for tool in tools
]
@@ -405,7 +416,7 @@ if MCP_AVAILABLE:
)
if not apply_tool_filters:
- return _create_tool_response_objects(tools, server.mcp_info)
+ return _create_tool_response_objects(tools, server)
# Always apply allowed_tools/disallowed_tools so the blacklist is
# enforced even when no allowlist is set (matches the SSE/HTTP path).
@@ -436,7 +447,7 @@ if MCP_AVAILABLE:
if _tool_name_matches(tool.name, allowed_tools_for_server)
]
- return _create_tool_response_objects(tools, server.mcp_info)
+ return _create_tool_response_objects(tools, server)
async def _resolve_allowed_mcp_servers_for_tool_call(
user_api_key_dict: UserAPIKeyAuth,
@@ -587,6 +598,8 @@ if MCP_AVAILABLE:
"mcp_info": {
"server_name": "zapier",
"logo_url": "https://www.zapier.com/logo.png",
+ "server_id": "a1b2c3d4-...",
+ "alias": "zapier_prod",
}
}
],
diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.py
index 8a432eb2f42..928d00109fa 100644
--- a/litellm/proxy/health_endpoints/_health_endpoints.py
+++ b/litellm/proxy/health_endpoints/_health_endpoints.py
@@ -1849,7 +1849,10 @@ async def test_model_connection(
"responses",
"ocr",
]
- ] = fastapi.Body("chat", description="The mode to test the model with"),
+ ] = fastapi.Body(
+ None,
+ description="The mode to test the model with. If not provided, auto-detected from model capabilities.",
+ ),
litellm_params: Dict = fastapi.Body(
None,
description="Parameters for litellm.completion, litellm.embedding for the health check",
diff --git a/litellm/proxy/management_endpoints/common_utils.py b/litellm/proxy/management_endpoints/common_utils.py
index f28bcc2bcd4..bc2da33672f 100644
--- a/litellm/proxy/management_endpoints/common_utils.py
+++ b/litellm/proxy/management_endpoints/common_utils.py
@@ -1,8 +1,27 @@
+import math
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
from fastapi import HTTPException, status
from pydantic import BaseModel
+
+# Defined above the `litellm.proxy.*` imports so the name is bound even when
+# this module is imported first through the proxy import cycle (CodeQL:
+# module-level cyclic import). Depends only on `math` + `HTTPException`.
+def validate_finite_spend(spend: float | None) -> None:
+ """Reject NaN/±inf spend before it reaches the DB / spend counter.
+
+ A non-finite spend would otherwise slip past `spend >= max_budget`
+ enforcement, since any comparison with NaN (and `-inf >= max_budget`)
+ is False, letting the entity keep spending past its configured budget.
+ """
+ if spend is not None and not math.isfinite(spend):
+ raise HTTPException(
+ status_code=400,
+ detail={"error": f"spend must be a finite number. Received: {spend}"},
+ )
+
+
from litellm._logging import verbose_proxy_logger
from litellm.caching import DualCache
from litellm.proxy._types import (
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py
index 8548d1c672c..99e276cfbb4 100644
--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py
@@ -36,6 +36,7 @@ from litellm.proxy.management_endpoints.common_utils import (
_is_user_team_admin,
_user_has_admin_view,
require_caller_user_id_for_non_admin,
+ validate_finite_spend,
)
from litellm.proxy.management_endpoints.key_management_endpoints import (
generate_key_helper_fn,
@@ -1256,6 +1257,25 @@ def _check_user_update_authz(
)
+async def _invalidate_user_spend_counter_if_changed(
+ non_default_values: dict[str, Any],
+) -> None:
+ """Invalidate the cross-pod spend counter after a direct ``spend`` change.
+
+ A direct ``spend`` change must also invalidate the cross-pod spend counter
+ enforcement reads; the DB write alone leaves a warm counter at the stale
+ value. ``non_default_values["user_id"]`` is populated in every branch of the
+ caller (incl. the email-new-user insert path, whose response is a bare model
+ and not safely subscriptable).
+ """
+ if non_default_values.get("spend") is not None:
+ from litellm.proxy.proxy_server import _invalidate_spend_counter
+
+ await _invalidate_spend_counter(
+ counter_key=f"spend:user:{non_default_values['user_id']}"
+ )
+
+
async def _update_single_user_helper(
user_request: UpdateUserRequest,
user_api_key_dict: UserAPIKeyAuth,
@@ -1336,6 +1356,9 @@ async def _update_single_user_helper(
existing_metadata=existing_metadata or {},
)
+ # Reject NaN/±inf spend before it can reach the DB / spend counter.
+ validate_finite_spend(non_default_values.get("spend"))
+
# Perform the update
response: Optional[Dict[str, Any]] = None
@@ -1384,6 +1407,8 @@ async def _update_single_user_helper(
litellm_proxy_admin_name=litellm_proxy_admin_name,
)
+ await _invalidate_user_spend_counter_if_changed(non_default_values)
+
if response is None:
raise HTTPException(
status_code=400,
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index db205803a47..9f316256ac9 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -69,6 +69,7 @@ from litellm.proxy.management_endpoints.common_utils import (
_is_user_team_admin,
_set_object_metadata_field,
_team_member_has_permission,
+ validate_finite_spend,
)
from litellm.proxy.management_endpoints.model_management_endpoints import (
_add_model_to_db,
@@ -2210,6 +2211,9 @@ async def _validate_update_key_data(
user_api_key_cache: Any,
) -> None:
"""Validate permissions and constraints for key update."""
+ # Reject NaN/±inf spend before it can reach the DB / spend counter.
+ validate_finite_spend(data.spend)
+
_is_proxy_admin = user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN.value
_check_allowed_routes_caller_permission(
@@ -2269,12 +2273,14 @@ async def _validate_update_key_data(
# existing admin-only budget semantics). budget_limits uses
# model_fields_set because an explicit null/[] clears the field
# and must gate the same as setting or changing it.
+ # - spend gates on presence alone (not a value diff): the DB spend
+ # lags the live cross-pod counter, so letting an "unchanged" spend
+ # through the non-admin path would let a key owner / team member
+ # overwrite the live counter below real usage and silently weaken
+ # enforcement.
_is_budget_change = (
(data.max_budget is not None and data.max_budget != existing_key_row.max_budget)
- or (
- data.spend is not None
- and data.spend != getattr(existing_key_row, "spend", None)
- )
+ or data.spend is not None
or "budget_limits" in data.model_fields_set
)
@@ -2609,15 +2615,24 @@ async def update_key_fn(
)
if data.spend is not None:
- try:
- from litellm.proxy.proxy_server import _invalidate_spend_counter
+ from litellm.proxy.proxy_server import spend_counter_cache
- token_to_invalidate = _hash_token_if_needed(key)
- await _invalidate_spend_counter(
- counter_key=f"spend:key:{token_to_invalidate}"
- )
- except Exception:
- pass
+ counter_key = f"spend:key:{_hash_token_if_needed(key)}"
+ spend_counter_cache.in_memory_cache.set_cache(
+ key=counter_key, value=data.spend, ttl=60
+ )
+ if spend_counter_cache.redis_cache is not None:
+ try:
+ await spend_counter_cache.redis_cache.async_set_cache(
+ key=counter_key, value=data.spend, ttl=60
+ )
+ except Exception as redis_err:
+ verbose_proxy_logger.warning(
+ "Failed to update spend counter %s in Redis after key spend update: %s. "
+ "Budget checks may use stale value until counter expires.",
+ counter_key,
+ redis_err,
+ )
asyncio.create_task(
KeyManagementEventHooks.async_key_updated_hook(
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index b0beaae02cf..3c91f1bc1d7 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -1114,6 +1114,33 @@ _OPENAPI_HTTP_METHODS = {
# `_SSO_SENSITIVE_FIELDS` / `_CACHE_SENSITIVE_FIELDS` constants in the SSO
# and cache endpoint files.
_ALERTING_SENSITIVE_VARS: Set[str] = {"SLACK_WEBHOOK_URL", "SMTP_PASSWORD"}
+_DB_LITELLM_PARAM_ENV_REF_KEYS = frozenset(
+ {
+ "api_key",
+ "client_secret",
+ "vertex_credentials",
+ "vertex_ai_credentials",
+ "aws_access_key_id",
+ "aws_secret_access_key",
+ }
+)
+
+
+def _db_model_is_team_scoped(model: object) -> bool:
+ model_info = getattr(model, "model_info", None)
+ if isinstance(model_info, BaseModel):
+ return getattr(model_info, "team_id", None) is not None
+ if isinstance(model_info, str):
+ try:
+ model_info = json.loads(model_info)
+ except (TypeError, ValueError):
+ model_info = None
+ if isinstance(model_info, dict) and model_info.get("team_id") is not None:
+ return True
+ if getattr(model_info, "team_id", None) is not None:
+ return True
+ model_name = getattr(model, "model_name", None)
+ return isinstance(model_name, str) and model_name.startswith("model_name_")
def _strip_operation_id_method_suffix(operation_id: str) -> str:
@@ -5255,6 +5282,24 @@ class ProxyConfig:
deleted_deployments += 1
return deleted_deployments
+ def _resolve_db_litellm_param(
+ self, key: str, value: object, resolve_env_refs: bool = True
+ ) -> object:
+ if not isinstance(value, str):
+ return value
+
+ decrypted_value = decrypt_value_helper(
+ value=value, key=key, return_original_value=True
+ )
+ if (
+ resolve_env_refs
+ and key in _DB_LITELLM_PARAM_ENV_REF_KEYS
+ and isinstance(decrypted_value, str)
+ and decrypted_value.startswith("os.environ/")
+ ):
+ return get_secret(decrypted_value)
+ return decrypted_value
+
def _add_deployment(self, db_models: list) -> int:
"""
Iterate through db models
@@ -5272,15 +5317,13 @@ class ProxyConfig:
## ADD MODEL LOGIC
for m in db_models:
_litellm_params = m.litellm_params
+ resolve_env_refs = not _db_model_is_team_scoped(m)
if isinstance(_litellm_params, dict):
# decrypt values
for k, v in _litellm_params.items():
- if isinstance(v, str):
- # decrypt value - returns original value if decryption fails or no key is set
- _value = decrypt_value_helper(
- value=v, key=k, return_original_value=True
- )
- _litellm_params[k] = _value
+ _litellm_params[k] = self._resolve_db_litellm_param(
+ key=k, value=v, resolve_env_refs=resolve_env_refs
+ )
_litellm_params = LiteLLM_Params(**_litellm_params)
else:
@@ -5308,15 +5351,15 @@ class ProxyConfig:
_model_list: list = []
for m in new_models:
_litellm_params = m.litellm_params
+ resolve_env_refs = not _db_model_is_team_scoped(m)
if isinstance(_litellm_params, BaseModel):
_litellm_params = _litellm_params.model_dump()
if isinstance(_litellm_params, dict):
# decrypt values
for k, v in _litellm_params.items():
- decrypted_value = decrypt_value_helper(
- value=v, key=k, return_original_value=True
+ _litellm_params[k] = self._resolve_db_litellm_param(
+ key=k, value=v, resolve_env_refs=resolve_env_refs
)
- _litellm_params[k] = decrypted_value
_litellm_params = LiteLLM_Params(**_litellm_params)
else:
verbose_proxy_logger.error(
diff --git a/litellm/responses/litellm_completion_transformation/handler.py b/litellm/responses/litellm_completion_transformation/handler.py
index a29f0a01b7a..1187640bf0c 100644
--- a/litellm/responses/litellm_completion_transformation/handler.py
+++ b/litellm/responses/litellm_completion_transformation/handler.py
@@ -59,6 +59,7 @@ class LiteLLMCompletionTransformationHandler:
completion_args = {}
completion_args.update(kwargs)
completion_args.update(litellm_completion_request)
+ completion_args["_skip_responses_api_bridge"] = True
litellm_completion_response: Union[
ModelResponse, litellm.CustomStreamWrapper
@@ -107,6 +108,7 @@ class LiteLLMCompletionTransformationHandler:
acompletion_args = {}
acompletion_args.update(kwargs)
acompletion_args.update(litellm_completion_request)
+ acompletion_args["_skip_responses_api_bridge"] = True
litellm_completion_response: Union[
ModelResponse, litellm.CustomStreamWrapper
diff --git a/tests/mcp_tests/test_mcp_server.py b/tests/mcp_tests/test_mcp_server.py
index 5f8fcbf835e..bb13a7ce8cc 100644
--- a/tests/mcp_tests/test_mcp_server.py
+++ b/tests/mcp_tests/test_mcp_server.py
@@ -1883,10 +1883,11 @@ def test_get_server_auth_header_no_auth_headers():
def test_create_tool_response_objects():
- """Test _create_tool_response_objects function."""
+ """Test _create_tool_response_objects enriches mcp_info with server_id and alias."""
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
_create_tool_response_objects,
)
+ from litellm.types.mcp_server.mcp_server_manager import MCPServer
from mcp.types import Tool as MCPTool
# Create mock tools
@@ -1903,20 +1904,32 @@ def test_create_tool_response_objects():
),
]
- server_mcp_info = {
- "server_name": "zapier",
- "logo_url": "https://zapier.com/logo.png",
- }
+ server = MCPServer(
+ server_id="a1b2c3d4",
+ name="zapier_internal",
+ alias="zapier",
+ transport="http",
+ mcp_info={
+ "server_name": "zapier_internal",
+ "logo_url": "https://zapier.com/logo.png",
+ },
+ )
- result = _create_tool_response_objects(mock_tools, server_mcp_info)
+ result = _create_tool_response_objects(mock_tools, server)
+ expected_mcp_info = {
+ "server_name": "zapier_internal",
+ "logo_url": "https://zapier.com/logo.png",
+ "server_id": "a1b2c3d4",
+ "alias": "zapier",
+ }
assert len(result) == 2
assert result[0].name == "send_email"
assert result[0].description == "Send an email"
- assert result[0].mcp_info == server_mcp_info
+ assert result[0].mcp_info == expected_mcp_info
assert result[1].name == "create_event"
assert result[1].description == "Create a calendar event"
- assert result[1].mcp_info == server_mcp_info
+ assert result[1].mcp_info == expected_mcp_info
@pytest.mark.asyncio
@@ -1930,6 +1943,8 @@ async def test_get_tools_for_single_server():
# Create a mock server (pin allowlist fields; MagicMock auto-attrs are truthy)
mock_server = MagicMock()
mock_server.mcp_info = {"server_name": "zapier"}
+ mock_server.server_id = "zapier_id"
+ mock_server.alias = "zapier_alias"
mock_server.allowed_tools = None
mock_server.disallowed_tools = None
@@ -1963,7 +1978,11 @@ async def test_get_tools_for_single_server():
# Verify the result
assert len(result) == 1
assert result[0].name == "send_email"
- assert result[0].mcp_info == {"server_name": "zapier"}
+ assert result[0].mcp_info == {
+ "server_name": "zapier",
+ "server_id": "zapier_id",
+ "alias": "zapier_alias",
+ }
@pytest.mark.asyncio
diff --git a/tests/test_litellm/caching/test_embedding_router.py b/tests/test_litellm/caching/test_embedding_router.py
new file mode 100644
index 00000000000..550095a112a
--- /dev/null
+++ b/tests/test_litellm/caching/test_embedding_router.py
@@ -0,0 +1,67 @@
+import os
+import sys
+from unittest.mock import MagicMock
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+from litellm.caching._embedding_router import (
+ build_router_embedding_metadata,
+ resolve_embedding_router,
+)
+
+
+def test_resolve_returns_router_when_model_is_a_deployment():
+ router = MagicMock()
+ assert (
+ resolve_embedding_router("sem-embed", router, [{"model_name": "sem-embed"}])
+ is router
+ )
+
+
+def test_resolve_returns_none_when_model_not_in_router():
+ router = MagicMock()
+ assert (
+ resolve_embedding_router("sem-embed", router, [{"model_name": "other"}]) is None
+ )
+
+
+def test_resolve_returns_none_when_router_is_none():
+ assert (
+ resolve_embedding_router("sem-embed", None, [{"model_name": "sem-embed"}])
+ is None
+ )
+
+
+def test_resolve_returns_none_when_model_list_is_none():
+ router = MagicMock()
+ assert resolve_embedding_router("sem-embed", router, None) is None
+
+
+def test_resolve_skips_entries_missing_model_name():
+ router = MagicMock()
+ model_list = [
+ {"litellm_params": {"model": "bedrock/x"}},
+ {"model_name": "sem-embed"},
+ ]
+ assert resolve_embedding_router("sem-embed", router, model_list) is router
+ assert resolve_embedding_router("other", router, [{"litellm_params": {}}]) is None
+
+
+def test_build_metadata_preserves_request_fields_and_adds_flag():
+ md = build_router_embedding_metadata(
+ {"user_api_key": "sk-x", "user_api_key_team_id": "team-1", "trace_id": "t-1"}
+ )
+ assert md == {
+ "user_api_key": "sk-x",
+ "user_api_key_team_id": "team-1",
+ "trace_id": "t-1",
+ "semantic-cache-embedding": True,
+ }
+
+
+def test_build_metadata_handles_none_and_does_not_mutate_input():
+ original = {"user_api_key": "sk-x"}
+ md = build_router_embedding_metadata(original)
+ assert md == {"user_api_key": "sk-x", "semantic-cache-embedding": True}
+ assert original == {"user_api_key": "sk-x"}
+ assert build_router_embedding_metadata(None) == {"semantic-cache-embedding": True}
diff --git a/tests/test_litellm/caching/test_qdrant_semantic_cache.py b/tests/test_litellm/caching/test_qdrant_semantic_cache.py
index 949e6ccc292..67d4e2d9892 100644
--- a/tests/test_litellm/caching/test_qdrant_semantic_cache.py
+++ b/tests/test_litellm/caching/test_qdrant_semantic_cache.py
@@ -1,5 +1,6 @@
import os
import sys
+import types
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -806,3 +807,104 @@ def test_qdrant_semantic_cache_large_vector_size():
)
create_payload = put_call.kwargs["json"]
assert create_payload["vectors"]["size"] == 4096
+
+
+def _router_proxy_module(router, model_name):
+ mod = types.ModuleType("litellm.proxy.proxy_server")
+ mod.llm_router = router
+ mod.llm_model_list = [{"model_name": model_name}]
+ return mod
+
+
+def test_qdrant_sync_get_cache_routes_through_router(monkeypatch):
+ from litellm.caching.qdrant_semantic_cache import QdrantSemanticCache
+
+ cache = QdrantSemanticCache.__new__(QdrantSemanticCache)
+ cache.embedding_model = "sem-embed"
+ cache.qdrant_api_base = "http://test.qdrant.local"
+ cache.collection_name = "test_collection"
+ cache.headers = {"Content-Type": "application/json", "api-key": "test_key"}
+ cache.similarity_threshold = 0.8
+ cache.sync_client = MagicMock()
+ search_response = MagicMock()
+ search_response.status_code = 200
+ search_response.json.return_value = {"result": []}
+ cache.sync_client.post.return_value = search_response
+
+ router = MagicMock()
+ router.embedding = MagicMock(
+ return_value={"data": [{"embedding": [0.3, 0.3, 0.3]}]}
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "litellm.proxy.proxy_server",
+ _router_proxy_module(router, "sem-embed"),
+ )
+
+ with patch("litellm.embedding") as direct_embed:
+ result = cache.get_cache(
+ key="test_key",
+ messages=[{"content": "What is the capital of France?"}],
+ metadata={},
+ )
+
+ assert result is None
+ router.embedding.assert_called_once()
+ assert router.embedding.call_args.kwargs["model"] == "sem-embed"
+ direct_embed.assert_not_called()
+
+
+def test_qdrant_sync_set_cache_falls_back_to_direct(monkeypatch):
+ from litellm.caching.qdrant_semantic_cache import QdrantSemanticCache
+
+ cache = QdrantSemanticCache.__new__(QdrantSemanticCache)
+ cache.embedding_model = "text-embedding-ada-002"
+ cache.qdrant_api_base = "http://test.qdrant.local"
+ cache.collection_name = "test_collection"
+ cache.headers = {"Content-Type": "application/json", "api-key": "test_key"}
+ cache.sync_client = MagicMock()
+ put_response = MagicMock()
+ put_response.status_code = 200
+ cache.sync_client.put.return_value = put_response
+
+ fake_proxy = types.ModuleType("litellm.proxy.proxy_server")
+ fake_proxy.llm_router = None
+ fake_proxy.llm_model_list = None
+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy)
+
+ with patch(
+ "litellm.embedding", return_value={"data": [{"embedding": [0.1, 0.1, 0.1]}]}
+ ) as direct_embed:
+ cache.set_cache(
+ key="test_key",
+ value={"content": "Paris"},
+ messages=[{"content": "What is the capital of France?"}],
+ )
+
+ direct_embed.assert_called_once()
+
+
+async def test_qdrant_async_embedding_forwards_full_metadata(monkeypatch):
+ from litellm.caching.qdrant_semantic_cache import QdrantSemanticCache
+
+ cache = QdrantSemanticCache.__new__(QdrantSemanticCache)
+ cache.embedding_model = "sem-embed"
+
+ router = MagicMock()
+ router.aembedding = AsyncMock(return_value={"data": [{"embedding": [0.1, 0.2]}]})
+ monkeypatch.setitem(
+ sys.modules,
+ "litellm.proxy.proxy_server",
+ _router_proxy_module(router, "sem-embed"),
+ )
+
+ await cache._get_async_embedding(
+ "hello",
+ metadata={"user_api_key": "sk-x", "user_api_key_team_id": "team-1"},
+ )
+
+ md = router.aembedding.call_args.kwargs["metadata"]
+ assert md["user_api_key"] == "sk-x"
+ assert md["user_api_key_team_id"] == "team-1"
+ assert md["semantic-cache-embedding"] is True
diff --git a/tests/test_litellm/caching/test_redis_cache.py b/tests/test_litellm/caching/test_redis_cache.py
index 6aaadce93ce..37c938bb38d 100644
--- a/tests/test_litellm/caching/test_redis_cache.py
+++ b/tests/test_litellm/caching/test_redis_cache.py
@@ -3,7 +3,6 @@ import sys
from unittest.mock import MagicMock, patch
import pytest
-from fastapi.testclient import TestClient
sys.path.insert(
0, os.path.abspath("../../..")
@@ -94,6 +93,42 @@ async def test_redis_cache_async_increment_default_does_not_bump_existing_ttl(
mock_redis_instance.expire.assert_not_awaited()
[email protected]("namespace", [None, "litellm"])
+async def test_async_delete_cache_applies_namespace(
+ namespace, monkeypatch, redis_no_ping
+):
+ """async_delete_cache must prefix keys with the namespace, matching every
+ other cache operation. Without this, Redis NOPERM errors occur when an
+ ACL restricts DEL to the litellm:* pattern."""
+ monkeypatch.setenv("REDIS_HOST", "https://my-test-host")
+ redis_cache = RedisCache(namespace=namespace)
+ mock_redis_instance = AsyncMock()
+
+ with patch.object(
+ redis_cache, "init_async_client", return_value=mock_redis_instance
+ ):
+ await redis_cache.async_delete_cache(key="3997c4abcdef")
+
+ expected_key = "litellm:3997c4abcdef" if namespace else "3997c4abcdef"
+ mock_redis_instance.delete.assert_awaited_once_with(expected_key)
+
+
[email protected]("namespace", [None, "litellm"])
+def test_delete_cache_applies_namespace(namespace, monkeypatch, redis_no_ping):
+ """delete_cache must prefix keys with the namespace, matching every other
+ cache operation."""
+ monkeypatch.setenv("REDIS_HOST", "https://my-test-host")
+ redis_cache = RedisCache(namespace=namespace)
+ mock_redis_client = MagicMock()
+ redis_cache.redis_client = mock_redis_client
+
+ redis_cache.delete_cache(key="3997c4abcdef")
+
+ expected_key = "litellm:3997c4abcdef" if namespace else "3997c4abcdef"
+ mock_redis_client.delete.assert_called_once_with(expected_key)
+
+
@pytest.mark.asyncio
async def test_redis_client_init_with_socket_timeout(monkeypatch, redis_no_ping):
monkeypatch.setenv("REDIS_HOST", "my-fake-host")
diff --git a/tests/test_litellm/caching/test_redis_semantic_cache.py b/tests/test_litellm/caching/test_redis_semantic_cache.py
index 13f9d00136d..1d3129d6467 100644
--- a/tests/test_litellm/caching/test_redis_semantic_cache.py
+++ b/tests/test_litellm/caching/test_redis_semantic_cache.py
@@ -104,6 +104,7 @@ def test_redis_semantic_cache_get_cache(monkeypatch):
# Verify llmcache.check was called
redis_semantic_cache.llmcache.check.assert_called_once_with(
prompt="What is the capital of France?",
+ vector=[0.1, 0.2, 0.3],
filter_expression="cache-key-filter",
)
@@ -138,10 +139,16 @@ def test_redis_semantic_cache_rejects_unscoped_cache_hit(monkeypatch):
]
)
- with patch.object(
- redis_semantic_cache,
- "_get_cache_key_filter_expression",
- return_value="cache-key-filter",
+ with (
+ patch(
+ "litellm.embedding",
+ return_value={"data": [{"embedding": [0.1, 0.2, 0.3]}]},
+ ),
+ patch.object(
+ redis_semantic_cache,
+ "_get_cache_key_filter_expression",
+ return_value="cache-key-filter",
+ ),
):
metadata = {}
result = redis_semantic_cache.get_cache(
@@ -176,16 +183,21 @@ def test_redis_semantic_cache_set_cache_stores_cache_key_filter(monkeypatch):
redis_semantic_cache = RedisSemanticCache(similarity_threshold=0.8)
redis_semantic_cache.llmcache.store = MagicMock()
- redis_semantic_cache.set_cache(
- key="test_key",
- value={"content": "Paris"},
- messages=[{"content": "What is the capital of France?"}],
- ttl=60,
- )
+ with patch(
+ "litellm.embedding",
+ return_value={"data": [{"embedding": [0.1, 0.2, 0.3]}]},
+ ):
+ redis_semantic_cache.set_cache(
+ key="test_key",
+ value={"content": "Paris"},
+ messages=[{"content": "What is the capital of France?"}],
+ ttl=60,
+ )
redis_semantic_cache.llmcache.store.assert_called_once_with(
"What is the capital of France?",
"{'content': 'Paris'}",
+ vector=[0.1, 0.2, 0.3],
filters={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"},
ttl=60,
)
@@ -299,10 +311,11 @@ def test_redis_semantic_cache_reraises_unexpected_isolated_index_error(monkeypat
monkeypatch.setenv("REDIS_PASSWORD", "test_password")
with pytest.raises(ValueError, match="connection failed"):
- RedisSemanticCache(
+ cache = RedisSemanticCache(
similarity_threshold=0.8,
index_name="existing_index",
)
+ _ = cache.llmcache
def test_redis_semantic_cache_reraises_unexpected_index_error():
@@ -534,6 +547,7 @@ def test_redis_semantic_cache_set_cache_uses_responses_string_input():
return_value={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"}
)
redis_semantic_cache._get_ttl = MagicMock(return_value=None)
+ redis_semantic_cache._get_embedding = MagicMock(return_value=[0.1, 0.2, 0.3])
redis_semantic_cache.set_cache(
key="test_key",
@@ -544,6 +558,7 @@ def test_redis_semantic_cache_set_cache_uses_responses_string_input():
redis_semantic_cache.llmcache.store.assert_called_once_with(
"What is the capital of France?",
"{'content': 'Paris'}",
+ vector=[0.1, 0.2, 0.3],
filters={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"},
)
@@ -564,6 +579,7 @@ def test_redis_semantic_cache_get_cache_uses_responses_string_input():
}
]
)
+ redis_semantic_cache._get_embedding = MagicMock(return_value=[0.1, 0.2, 0.3])
with patch.object(
redis_semantic_cache,
@@ -581,6 +597,7 @@ def test_redis_semantic_cache_get_cache_uses_responses_string_input():
assert metadata["semantic-similarity"] == pytest.approx(0.9)
redis_semantic_cache.llmcache.check.assert_called_once_with(
prompt="What is the capital of France?",
+ vector=[0.1, 0.2, 0.3],
filter_expression="cache-key-filter",
)
@@ -594,6 +611,7 @@ def test_redis_semantic_cache_set_cache_flattens_structured_responses_input():
return_value={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"}
)
redis_semantic_cache._get_ttl = MagicMock(return_value=None)
+ redis_semantic_cache._get_embedding = MagicMock(return_value=[0.1, 0.2, 0.3])
redis_semantic_cache.set_cache(
key="test_key",
@@ -616,6 +634,7 @@ def test_redis_semantic_cache_set_cache_flattens_structured_responses_input():
redis_semantic_cache.llmcache.store.assert_called_once_with(
"What is the capital of France?\nAnswer briefly.",
"{'content': 'Paris'}",
+ vector=[0.1, 0.2, 0.3],
filters={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"},
)
@@ -740,6 +759,7 @@ def test_redis_semantic_cache_get_cache_sets_similarity_when_no_results():
redis_semantic_cache = RedisSemanticCache.__new__(RedisSemanticCache)
redis_semantic_cache.llmcache = MagicMock()
redis_semantic_cache.llmcache.check = MagicMock(return_value=[])
+ redis_semantic_cache._get_embedding = MagicMock(return_value=[0.1, 0.2, 0.3])
with patch.object(
redis_semantic_cache,
@@ -757,6 +777,7 @@ def test_redis_semantic_cache_get_cache_sets_similarity_when_no_results():
assert metadata["semantic-similarity"] == 0.0
redis_semantic_cache.llmcache.check.assert_called_once_with(
prompt="What is the capital of France?",
+ vector=[0.1, 0.2, 0.3],
filter_expression="cache-key-filter",
)
@@ -870,6 +891,63 @@ async def test_redis_semantic_cache_async_paths_set_similarity_on_misses():
)
+def test_redis_get_embedding_routes_through_router(monkeypatch):
+ import sys
+ import types
+
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ cache = RedisSemanticCache.__new__(RedisSemanticCache)
+ cache.embedding_model = "sem-embed"
+
+ router = MagicMock()
+ router.embedding = MagicMock(return_value={"data": [{"embedding": [0.5, 0.6]}]})
+ fake_proxy = types.ModuleType("litellm.proxy.proxy_server")
+ fake_proxy.llm_router = router
+ fake_proxy.llm_model_list = [{"model_name": "sem-embed"}]
+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy)
+
+ with patch("litellm.embedding") as direct_embed:
+ vec = cache._get_embedding("hello", metadata={"user_api_key": "sk-x"})
+
+ assert vec == [0.5, 0.6]
+ router.embedding.assert_called_once()
+ assert router.embedding.call_args.kwargs["model"] == "sem-embed"
+ assert router.embedding.call_args.kwargs["input"] == "hello"
+ assert router.embedding.call_args.kwargs["cache"] == {
+ "no-store": True,
+ "no-cache": True,
+ }
+ assert router.embedding.call_args.kwargs["metadata"] == {
+ "user_api_key": "sk-x",
+ "semantic-cache-embedding": True,
+ }
+ direct_embed.assert_not_called()
+
+
+def test_redis_get_embedding_falls_back_to_direct(monkeypatch):
+ import sys
+ import types
+
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ cache = RedisSemanticCache.__new__(RedisSemanticCache)
+ cache.embedding_model = "text-embedding-ada-002"
+
+ fake_proxy = types.ModuleType("litellm.proxy.proxy_server")
+ fake_proxy.llm_router = None
+ fake_proxy.llm_model_list = None
+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy)
+
+ with patch(
+ "litellm.embedding", return_value={"data": [{"embedding": [0.1, 0.2]}]}
+ ) as direct_embed:
+ vec = cache._get_embedding("hello")
+
+ assert vec == [0.1, 0.2]
+ direct_embed.assert_called_once()
+
+
def test_cache_get_cache_passes_responses_input_to_backend_cache():
from litellm.caching.caching import Cache
@@ -893,7 +971,7 @@ def test_cache_get_cache_passes_responses_input_to_backend_cache():
)
-def test_cache_get_cache_filters_sensitive_kwargs_from_backend_cache():
+def test_cache_get_cache_filters_non_lookup_kwargs_from_backend_cache():
from litellm.caching.caching import Cache
cache = Cache.__new__(Cache)
@@ -927,7 +1005,11 @@ def test_cache_get_cache_filters_sensitive_kwargs_from_backend_cache():
forwarded_kwargs = cache.cache.get_cache.call_args.kwargs
assert forwarded_kwargs == {
"input": "What is the capital of France?",
- "metadata": {"semantic-similarity": 0.7},
+ "metadata": {
+ "user_api_key": "sk-secret",
+ "trace_id": "trace-id",
+ "semantic-similarity": 0.7,
+ },
}
assert forwarded_kwargs["metadata"] is not metadata
cache._get_cache_logic.assert_called_once_with(
@@ -988,3 +1070,166 @@ def test_cache_get_cache_passes_responses_input_to_dynamic_cache():
cached_result={"content": "Paris"},
max_age=float("inf"),
)
+
+
+def test_redis_sync_set_cache_passes_precomputed_vector():
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ cache = RedisSemanticCache.__new__(RedisSemanticCache)
+ cache.llmcache = MagicMock()
+ cache._get_cache_filters = MagicMock(
+ return_value={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"}
+ )
+ cache._get_ttl = MagicMock(return_value=None)
+ cache._get_embedding = MagicMock(return_value=[0.1, 0.2, 0.3])
+
+ cache.set_cache(
+ key="test_key",
+ value={"content": "Paris"},
+ messages=[{"content": "What is the capital of France?"}],
+ )
+
+ cache._get_embedding.assert_called_once()
+ cache.llmcache.store.assert_called_once_with(
+ "What is the capital of France?",
+ "{'content': 'Paris'}",
+ vector=[0.1, 0.2, 0.3],
+ filters={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"},
+ )
+
+
+def test_redis_sync_get_cache_passes_precomputed_vector():
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ cache = RedisSemanticCache.__new__(RedisSemanticCache)
+ cache.similarity_threshold = 0.8
+ cache.llmcache = MagicMock()
+ cache.llmcache.check = MagicMock(
+ return_value=[
+ {
+ "prompt": "What is the capital of France?",
+ "response": '{"content": "Paris"}',
+ "vector_distance": 0.1,
+ RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key",
+ }
+ ]
+ )
+ cache._get_embedding = MagicMock(return_value=[0.1, 0.2, 0.3])
+
+ with patch.object(
+ cache, "_get_cache_key_filter_expression", return_value="cache-key-filter"
+ ):
+ result = cache.get_cache(
+ key="test_key",
+ messages=[{"content": "What is the capital of France?"}],
+ metadata={},
+ )
+
+ assert result == {"content": "Paris"}
+ cache._get_embedding.assert_called_once()
+ cache.llmcache.check.assert_called_once_with(
+ prompt="What is the capital of France?",
+ vector=[0.1, 0.2, 0.3],
+ filter_expression="cache-key-filter",
+ )
+
+
+async def test_redis_async_embedding_forwards_full_metadata(monkeypatch):
+ import sys
+ import types
+
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ cache = RedisSemanticCache.__new__(RedisSemanticCache)
+ cache.embedding_model = "sem-embed"
+
+ router = MagicMock()
+ router.aembedding = AsyncMock(return_value={"data": [{"embedding": [0.1, 0.2]}]})
+ fake_proxy = types.ModuleType("litellm.proxy.proxy_server")
+ fake_proxy.llm_router = router
+ fake_proxy.llm_model_list = [{"model_name": "sem-embed"}]
+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy)
+
+ await cache._get_async_embedding(
+ "hello",
+ metadata={"user_api_key": "sk-x", "user_api_key_team_id": "team-1"},
+ )
+
+ md = router.aembedding.call_args.kwargs["metadata"]
+ assert md["user_api_key"] == "sk-x"
+ assert md["user_api_key_team_id"] == "team-1" # FAILS today: team_id is dropped
+ assert md["semantic-cache-embedding"] is True
+
+
+def test_redis_init_defers_redisvl_construction(monkeypatch):
+ semantic_cache_mock = MagicMock()
+ custom_vectorizer_mock = MagicMock()
+
+ with patch.dict(
+ "sys.modules",
+ {
+ "redisvl.extensions.llmcache": MagicMock(SemanticCache=semantic_cache_mock),
+ "redisvl.utils.vectorize": MagicMock(
+ CustomTextVectorizer=custom_vectorizer_mock
+ ),
+ },
+ ):
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ monkeypatch.setenv("REDIS_HOST", "localhost")
+ monkeypatch.setenv("REDIS_PORT", "6379")
+ monkeypatch.setenv("REDIS_PASSWORD", "test_password")
+
+ cache = RedisSemanticCache(similarity_threshold=0.8)
+
+ semantic_cache_mock.assert_not_called()
+ custom_vectorizer_mock.assert_not_called()
+
+ first = cache.llmcache
+ semantic_cache_mock.assert_called_once()
+ custom_vectorizer_mock.assert_called_once()
+
+ second = cache.llmcache
+ assert first is second
+ semantic_cache_mock.assert_called_once()
+
+
+def test_redis_failed_llmcache_build_is_not_memoized(monkeypatch):
+ built_cache = MagicMock()
+ semantic_cache_mock = MagicMock(
+ side_effect=[ConnectionError("redis down"), built_cache]
+ )
+ custom_vectorizer_mock = MagicMock()
+
+ with patch.dict(
+ "sys.modules",
+ {
+ "redisvl.extensions.llmcache": MagicMock(SemanticCache=semantic_cache_mock),
+ "redisvl.utils.vectorize": MagicMock(
+ CustomTextVectorizer=custom_vectorizer_mock
+ ),
+ },
+ ):
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ monkeypatch.setenv("REDIS_HOST", "localhost")
+ monkeypatch.setenv("REDIS_PORT", "6379")
+ monkeypatch.setenv("REDIS_PASSWORD", "test_password")
+
+ cache = RedisSemanticCache(similarity_threshold=0.8)
+
+ with pytest.raises(ConnectionError, match="redis down"):
+ _ = cache.llmcache
+
+ assert cache.llmcache is built_cache
+ assert semantic_cache_mock.call_count == 2
+
+
+def test_redis_llmcache_setter_supported():
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ cache = RedisSemanticCache.__new__(RedisSemanticCache)
+ sentinel = MagicMock()
+ cache.llmcache = sentinel
+ assert cache.llmcache is sentinel
diff --git a/tests/test_litellm/google_genai/test_google_genai_main.py b/tests/test_litellm/google_genai/test_google_genai_main.py
index 5854e4b55af..8f56b4e4bc0 100644
--- a/tests/test_litellm/google_genai/test_google_genai_main.py
+++ b/tests/test_litellm/google_genai/test_google_genai_main.py
@@ -2,6 +2,7 @@
"""
Test to verify the Google GenAI generate_content adapter functionality
"""
+
import json
import os
import sys
@@ -42,4 +43,228 @@ async def test_agenerate_content_stream():
stream=True,
)
mock_post.assert_called_once()
- mock_post.call_args.kwargs["stream"] == True
+ assert mock_post.call_args.kwargs["stream"] is True
+
+
+def _mock_gemini_post_response():
+ """A minimal stand-in for a successful Gemini generateContent HTTP response."""
+ from unittest.mock import MagicMock
+
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.headers = {}
+ resp.json.return_value = {
+ "candidates": [
+ {
+ "content": {"parts": [{"text": "hi"}], "role": "model"},
+ "finishReason": "STOP",
+ }
+ ]
+ }
+ return resp
+
+
+NATIVE_TOP_LEVEL_FIELD_CASES = [
+ (
+ "safetySettings",
+ [{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}],
+ ),
+ ("toolConfig", {"functionCallingConfig": {"mode": "AUTO"}}),
+ ("cachedContent", "cachedContents/abc123"),
+ ("labels", {"team": "search"}),
+]
+
+
[email protected]("field_name, field_value", NATIVE_TOP_LEVEL_FIELD_CASES)
+def test_native_top_level_field_forwarded_to_request_body(field_name, field_value):
+ """
+ Regression for https://github.com/BerriAI/litellm/issues/12671
+
+ Google's native generateContent body carries fields like safetySettings at the
+ top level (siblings of generationConfig). The proxy spreads them as loose kwargs
+ into generate_content. They must reach Google's request body at the top level and
+ must NOT be silently dropped nor nested under generationConfig.
+ """
+ from unittest.mock import patch
+
+ from litellm.google_genai.main import generate_content
+ from litellm.llms.custom_httpx.http_handler import HTTPHandler
+
+ with patch.object(
+ HTTPHandler, "post", return_value=_mock_gemini_post_response()
+ ) as mock_post:
+ generate_content(
+ model="gemini/gemini-2.0-flash",
+ contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
+ custom_llm_provider="gemini",
+ api_key="test-key",
+ **{field_name: field_value},
+ )
+
+ assert mock_post.called, "expected the request to reach the HTTP client"
+ body = mock_post.call_args.kwargs["json"]
+ assert (
+ body[field_name] == field_value
+ ), f"{field_name} should be forwarded to Google at the top level"
+ assert field_name not in body.get("generationConfig", {}), (
+ f"{field_name} must be a top-level sibling of generationConfig, "
+ "not nested inside it"
+ )
+
+
+async def test_native_safety_settings_forwarded_async():
+ """The async path (used by the proxy's :generateContent route) must also forward
+ native top-level fields."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.google_genai.main import agenerate_content
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ safety_settings = [
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
+ ]
+
+ with patch.object(
+ AsyncHTTPHandler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=_mock_gemini_post_response(),
+ ) as mock_post:
+ await agenerate_content(
+ model="gemini/gemini-2.0-flash",
+ contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
+ custom_llm_provider="gemini",
+ api_key="test-key",
+ safetySettings=safety_settings,
+ )
+
+ assert mock_post.called
+ body = mock_post.call_args.kwargs["json"]
+ assert body["safetySettings"] == safety_settings
+ assert "safetySettings" not in body.get("generationConfig", {})
+
+
+def test_native_fields_coexist_with_generation_config():
+ """Forwarding native top-level fields must not regress the already-working
+ generationConfig path; both must land in their correct positions."""
+ from unittest.mock import patch
+
+ from litellm.google_genai.main import generate_content
+ from litellm.llms.custom_httpx.http_handler import HTTPHandler
+
+ safety_settings = [
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
+ ]
+
+ with patch.object(
+ HTTPHandler, "post", return_value=_mock_gemini_post_response()
+ ) as mock_post:
+ generate_content(
+ model="gemini/gemini-2.0-flash",
+ contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
+ custom_llm_provider="gemini",
+ api_key="test-key",
+ safetySettings=safety_settings,
+ generationConfig={"temperature": 0, "responseMimeType": "application/json"},
+ )
+
+ body = mock_post.call_args.kwargs["json"]
+ assert body["safetySettings"] == safety_settings
+ generation_config = body["generationConfig"]
+ assert generation_config["temperature"] == 0
+ assert generation_config["responseMimeType"] == "application/json"
+
+
+def test_explicit_extra_body_overrides_native_top_level_field():
+ """An explicit extra_body value takes precedence over the same top-level field."""
+ from unittest.mock import patch
+
+ from litellm.google_genai.main import generate_content
+ from litellm.llms.custom_httpx.http_handler import HTTPHandler
+
+ native = [{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}]
+ override = [
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"}
+ ]
+
+ with patch.object(
+ HTTPHandler, "post", return_value=_mock_gemini_post_response()
+ ) as mock_post:
+ generate_content(
+ model="gemini/gemini-2.0-flash",
+ contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
+ custom_llm_provider="gemini",
+ api_key="test-key",
+ safetySettings=native,
+ extra_body={"safetySettings": override},
+ )
+
+ body = mock_post.call_args.kwargs["json"]
+ assert body["safetySettings"] == override
+
+
+def test_native_fields_and_system_instruction_forwarded_on_sync_stream():
+ """The sync streaming path (generate_content_stream) must forward native top-level
+ fields AND systemInstruction. The PR changed the merge here and newly added the
+ systemInstruction kwarg; without coverage a regression on either ships green."""
+ from unittest.mock import patch
+
+ from litellm.google_genai.main import generate_content_stream
+ from litellm.llms.custom_httpx.http_handler import HTTPHandler
+
+ safety_settings = [
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
+ ]
+ system_instruction = {"parts": [{"text": "Be terse"}]}
+
+ with patch.object(
+ HTTPHandler, "post", return_value=_mock_gemini_post_response()
+ ) as mock_post:
+ generate_content_stream(
+ model="gemini/gemini-2.0-flash",
+ contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
+ custom_llm_provider="gemini",
+ api_key="test-key",
+ safetySettings=safety_settings,
+ systemInstruction=system_instruction,
+ )
+
+ assert mock_post.called
+ body = mock_post.call_args.kwargs["json"]
+ assert body["safetySettings"] == safety_settings
+ assert body["systemInstruction"] == system_instruction
+ assert "safetySettings" not in body.get("generationConfig", {})
+
+
+async def test_native_fields_forwarded_on_async_stream():
+ """The async streaming path (agenerate_content_stream) backs the proxy's
+ :streamGenerateContent route and must forward native top-level fields too."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.google_genai.main import agenerate_content_stream
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ safety_settings = [
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
+ ]
+
+ with patch.object(
+ AsyncHTTPHandler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=_mock_gemini_post_response(),
+ ) as mock_post:
+ await agenerate_content_stream(
+ model="gemini/gemini-2.0-flash",
+ contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
+ custom_llm_provider="gemini",
+ api_key="test-key",
+ safetySettings=safety_settings,
+ )
+
+ assert mock_post.called
+ body = mock_post.call_args.kwargs["json"]
+ assert body["safetySettings"] == safety_settings
+ assert "safetySettings" not in body.get("generationConfig", {})
diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_cursor.py b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_cursor.py
new file mode 100644
index 00000000000..453c7490d98
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_cursor.py
@@ -0,0 +1,321 @@
+"""
+Regression tests for the Anthropic message_start cursor=1 bug in
+ChunkProcessor._calculate_usage_per_chunk.
+
+Background
+----------
+Anthropic streams a `message_start` event that carries
+`usage.output_tokens=1` as a placeholder ("cursor"). The real cumulative
+output count only arrives in the final `message_delta` event. When a
+stream is cancelled before `message_delta` lands (very common for
+thinking models on long-tail prompts), the last-wins accumulator in
+ChunkProcessor leaves completion_tokens stuck at 1. Because 1 is
+truthy, the `completion_tokens or token_counter(text=...)` fallback in
+calculate_usage() never fires, and the request is billed for 1 output
+token even when several thousand tokens of text were actually streamed.
+
+These tests pin the post-fix behavior: completion_tokens should reset
+to 0 when the only update we saw was the cursor, allowing the
+text-based fallback to estimate from the real completion text.
+"""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+from litellm.litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor
+from litellm.types.utils import (
+ Delta,
+ ModelResponseStream,
+ StreamingChoices,
+ Usage,
+)
+
+
+def _make_chunk(
+ *,
+ content: str = "",
+ usage: Usage = None,
+ finish_reason: str = None,
+ custom_llm_provider: str = "anthropic",
+) -> ModelResponseStream:
+ chunk = ModelResponseStream(
+ id="msg_test",
+ created=1738900000,
+ model="claude-sonnet-4-6",
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ finish_reason=finish_reason,
+ index=0,
+ delta=Delta(content=content, role="assistant"),
+ )
+ ],
+ usage=usage,
+ )
+ # The cursor reset is now gated on provider; populate the same field the
+ # real streaming_handler sets (see litellm/litellm_core_utils/streaming_handler.py).
+ chunk._hidden_params = {"custom_llm_provider": custom_llm_provider}
+ return chunk
+
+
+class TestAnthropicCursorBug:
+ """The core regression: completion_tokens=1 cursor must not leak through."""
+
+ def test_only_message_start_cursor_resets_completion_to_zero(self):
+ """
+ Stream cancelled before message_delta — only the message_start cursor
+ (output_tokens=1) was seen. Per-chunk accumulator must reset to 0 so
+ token_counter fallback can estimate from completion text.
+ """
+ # Anthropic message_start: input_tokens accurate, output_tokens=1 cursor
+ message_start = _make_chunk(
+ usage=Usage(prompt_tokens=1024, completion_tokens=1, total_tokens=1025)
+ )
+ # Several content_block_delta chunks (no usage attached)
+ text_chunks = [
+ _make_chunk(content="Hello"),
+ _make_chunk(content=" world"),
+ _make_chunk(content=" this is partial."),
+ ]
+ chunks = [message_start, *text_chunks]
+
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+
+ assert result["prompt_tokens"] == 1024
+ # The cursor value of 1 must NOT leak through — should be reset to 0
+ # so the text-based fallback estimates the real completion length.
+ assert result["completion_tokens"] == 0, (
+ "completion_tokens=1 from message_start cursor leaked through. "
+ "Should reset to 0 when only cursor was seen, so token_counter "
+ "fallback in calculate_usage() can estimate from completion text."
+ )
+
+ def test_message_start_plus_message_delta_uses_delta_value(self):
+ """
+ Normal complete stream: message_start cursor=1, then message_delta=3847.
+ Last-wins must give 3847 (the real value).
+ """
+ message_start = _make_chunk(
+ usage=Usage(prompt_tokens=1024, completion_tokens=1, total_tokens=1025)
+ )
+ text_chunks = [_make_chunk(content=t) for t in ["Hello", " world", "!"]]
+ # message_delta with the real cumulative output_tokens
+ message_delta = _make_chunk(
+ usage=Usage(prompt_tokens=1024, completion_tokens=3847, total_tokens=4871),
+ finish_reason="stop",
+ )
+ chunks = [message_start, *text_chunks, message_delta]
+
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+
+ assert result["prompt_tokens"] == 1024
+ assert result["completion_tokens"] == 3847
+
+ def test_calculate_usage_falls_back_to_token_counter_for_cursor_only(self):
+ """
+ End-to-end via calculate_usage(): cursor-only stream + real completion
+ text should produce a token-counter estimate, NOT 1.
+ """
+ message_start = _make_chunk(
+ usage=Usage(prompt_tokens=1024, completion_tokens=1, total_tokens=1025)
+ )
+ # ~50 visible chars ≈ ~12 tokens (anthropic-style tokenizer ballpark)
+ text_chunks = [
+ _make_chunk(content="Based on your question, I think the answer is "),
+ _make_chunk(content="forty-two. Here is my reasoning: "),
+ ]
+ chunks = [message_start, *text_chunks]
+ completion_output = (
+ "Based on your question, I think the answer is forty-two. "
+ "Here is my reasoning: "
+ )
+
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ usage = processor.calculate_usage(
+ chunks=chunks,
+ model="claude-sonnet-4-6",
+ completion_output=completion_output,
+ messages=[],
+ )
+
+ # Should be a token_counter estimate of the text, not the cursor 1
+ assert usage.completion_tokens > 1, (
+ f"Expected token_counter estimate of completion text, got "
+ f"completion_tokens={usage.completion_tokens} (likely stuck at cursor)"
+ )
+
+ def test_cache_fields_preserved_from_message_start(self):
+ """cache_read / cache_creation come from message_start and must survive."""
+ message_start_usage = Usage(
+ prompt_tokens=1024, completion_tokens=1, total_tokens=1025
+ )
+ # Anthropic puts these in message_start
+ message_start_usage.cache_read_input_tokens = 512
+ message_start_usage.cache_creation_input_tokens = 128
+ message_start = _make_chunk(usage=message_start_usage)
+
+ chunks = [message_start, _make_chunk(content="hi")]
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+
+ assert result["cache_read_input_tokens"] == 512
+ assert result["cache_creation_input_tokens"] == 128
+
+ def test_openai_streaming_unaffected(self):
+ """
+ OpenAI's only usage chunk is the penultimate one (with
+ stream_options.include_usage=true), and it carries the real value
+ directly. Our cursor fix must not break this path — output > 1
+ means saw_non_cursor_completion=True so no reset happens.
+ """
+ # Simulate OpenAI: content chunks first, then ONE usage chunk at the end
+ text_chunks = [_make_chunk(content=t) for t in ["The", " answer", " is 42"]]
+ usage_chunk = _make_chunk(
+ usage=Usage(prompt_tokens=42, completion_tokens=15, total_tokens=57),
+ finish_reason="stop",
+ )
+ chunks = [*text_chunks, usage_chunk]
+
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+
+ assert result["prompt_tokens"] == 42
+ assert result["completion_tokens"] == 15
+
+ def test_single_token_completion_legitimate_case(self):
+ """
+ Edge case: a stream that legitimately completes with output_tokens=1
+ (e.g., model returns just "Yes."). Without saw_non_cursor_completion
+ we'd reset to 0 and fall through to token_counter — but token_counter
+ on a 1-token string also gives ~1, so billing is still approximately
+ correct. This test pins that the result is sane (1 or 0).
+ """
+ message_start = _make_chunk(
+ usage=Usage(prompt_tokens=20, completion_tokens=1, total_tokens=21)
+ )
+ text_chunk = _make_chunk(content="Yes.")
+ # Anthropic's message_delta also gives output_tokens=1 in this case
+ message_delta = _make_chunk(
+ usage=Usage(prompt_tokens=20, completion_tokens=1, total_tokens=21),
+ finish_reason="stop",
+ )
+ chunks = [message_start, text_chunk, message_delta]
+
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ usage = processor.calculate_usage(
+ chunks=chunks,
+ model="claude-sonnet-4-6",
+ completion_output="Yes.",
+ messages=[],
+ )
+
+ # Two completion-bearing usage events (message_start AND message_delta
+ # both with output_tokens=1) is positive evidence that message_delta
+ # arrived — saw_non_cursor_completion goes True via the count >= 2
+ # branch and the reset is suppressed. Result: completion_tokens stays
+ # at the legitimate value of 1.
+ assert usage.completion_tokens == 1, (
+ f"Legitimate single-token completion should bill exactly 1 token "
+ f"(message_start + message_delta both saw output_tokens=1, "
+ f"confirming message_delta arrived), got {usage.completion_tokens}"
+ )
+
+ def test_anthropic_cache_only_chunks_after_message_start_still_resets(self):
+ """
+ Cache-only chunks (cache_read_input_tokens > 0 but completion_tokens=0)
+ following message_start should not be mistaken for completion progress.
+ The cursor=1 from message_start stays the only completion update; reset
+ must fire so token_counter estimates from completion text instead of
+ billing the placeholder.
+ """
+ message_start_usage = Usage(
+ prompt_tokens=1024, completion_tokens=1, total_tokens=1025
+ )
+ message_start_usage.cache_read_input_tokens = 4096
+ message_start = _make_chunk(usage=message_start_usage)
+ # Subsequent chunks with cache fields but no completion_tokens
+ cache_chunk_usage = Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0)
+ cache_chunk_usage.cache_read_input_tokens = 4096
+ cache_chunk = _make_chunk(content="partial", usage=cache_chunk_usage)
+ # No message_delta — stream was cancelled
+ chunks = [message_start, cache_chunk]
+
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+
+ assert result["cache_read_input_tokens"] == 4096
+ assert result["completion_tokens"] == 0, (
+ "cache chunks alone don't count as completion progress — only "
+ "completion_tokens > 0 in a usage event proves real output happened. "
+ "Reset to 0 forces token_counter fallback."
+ )
+
+
+class TestProviderGuard:
+ """Class A: the cursor-reset heuristic must NOT silently affect non-Anthropic
+ providers, even if they happen to report completion_tokens=1."""
+
+ def test_non_anthropic_provider_completion_tokens_one_not_reset(self):
+ """
+ Some non-Anthropic provider legitimately reports completion_tokens=1
+ in its single usage chunk. Without the provider guard the cursor
+ heuristic would silently reset it to 0 and bill via token_counter,
+ producing a different (often inflated) number than what the provider
+ actually charged.
+ """
+ chunks = [
+ _make_chunk(
+ usage=Usage(prompt_tokens=10, completion_tokens=1, total_tokens=11),
+ finish_reason="stop",
+ custom_llm_provider="openai",
+ ),
+ ]
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+ assert result["completion_tokens"] == 1, (
+ "Non-Anthropic providers must not be subject to the message_start "
+ "cursor reset — their completion_tokens=1 is the real value."
+ )
+
+ def test_unknown_provider_completion_tokens_one_not_reset(self):
+ """No custom_llm_provider on hidden_params (older path or custom
+ plugin) — heuristic must not fire."""
+ chunk = _make_chunk(
+ usage=Usage(prompt_tokens=10, completion_tokens=1, total_tokens=11),
+ )
+ # Explicitly clear hidden_params to simulate the unknown-provider case
+ chunk._hidden_params = {}
+ processor = ChunkProcessor(chunks=[chunk], messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=[chunk])
+ assert result["completion_tokens"] == 1
+
+
+class TestNonAnthropicStreamingIntact:
+ """Make sure providers without cursor pattern still work."""
+
+ def test_completion_tokens_above_one_never_resets(self):
+ """Any chunk reporting completion_tokens > 1 sets saw_non_cursor
+ and prevents the reset."""
+ chunks = [
+ _make_chunk(
+ usage=Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15)
+ ),
+ ]
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+ assert result["completion_tokens"] == 5
+
+ def test_no_usage_chunks_leaves_zero(self):
+ """Stream with zero usage info → completion_tokens stays 0
+ (token_counter fallback will handle it)."""
+ chunks = [_make_chunk(content="hi"), _make_chunk(content=" there")]
+ processor = ChunkProcessor(chunks=chunks, messages=[])
+ result = processor._calculate_usage_per_chunk(chunks=chunks)
+ assert result["prompt_tokens"] == 0
+ assert result["completion_tokens"] == 0
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
index f93f2404fa4..45820b9833f 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py
@@ -2175,6 +2175,283 @@ def test_translate_openai_response_to_anthropic_cache_tokens_from_prompt_tokens_
assert anthropic_response["usage"]["cache_read_input_tokens"] == 30
+def test_translate_openai_usage_to_anthropic_cache_tokens_from_dict_details_with_integral_floats():
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ )
+ usage.prompt_tokens_details = {
+ "cached_tokens": 30.0,
+ "cache_write_tokens": 20.0,
+ }
+
+ anthropic_usage = LiteLLMAnthropicMessagesAdapter._translate_openai_usage_to_anthropic_usage_delta(
+ usage
+ )
+
+ assert anthropic_usage["input_tokens"] == 70
+ assert anthropic_usage["output_tokens"] == 50
+ assert anthropic_usage["cache_read_input_tokens"] == 30
+ assert anthropic_usage["cache_creation_input_tokens"] == 20
+
+
+def test_translate_openai_usage_to_anthropic_ignores_fractional_cache_tokens():
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ )
+ usage.prompt_tokens_details = {
+ "cached_tokens": 30.5,
+ "cache_creation_tokens": 20.25,
+ }
+
+ anthropic_usage = LiteLLMAnthropicMessagesAdapter._translate_openai_usage_to_anthropic_usage_delta(
+ usage
+ )
+
+ assert anthropic_usage["input_tokens"] == 120
+ assert anthropic_usage["output_tokens"] == 50
+ assert "cache_read_input_tokens" not in anthropic_usage
+ assert "cache_creation_input_tokens" not in anthropic_usage
+
+
+def test_translate_openai_usage_to_anthropic_ignores_bool_cache_tokens():
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ )
+ usage.cache_read_input_tokens = True
+ usage.cache_creation_input_tokens = True
+
+ anthropic_usage = LiteLLMAnthropicMessagesAdapter._translate_openai_usage_to_anthropic_usage_delta(
+ usage
+ )
+
+ assert anthropic_usage["input_tokens"] == 120
+ assert anthropic_usage["output_tokens"] == 50
+ assert "cache_read_input_tokens" not in anthropic_usage
+ assert "cache_creation_input_tokens" not in anthropic_usage
+
+
+def test_translate_openai_response_to_anthropic_cache_creation_from_prompt_tokens_details():
+ from litellm.types.utils import PromptTokensDetailsWrapper
+
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=30,
+ cache_creation_tokens=20,
+ ),
+ )
+
+ response = ModelResponse(
+ id="test-id",
+ choices=[
+ Choices(
+ index=0,
+ finish_reason="stop",
+ message=Message(
+ role="assistant",
+ content="Test response",
+ ),
+ )
+ ],
+ model="gpt-4o-2024-08-06",
+ usage=usage,
+ )
+
+ adapter = LiteLLMAnthropicMessagesAdapter()
+ anthropic_response = adapter.translate_openai_response_to_anthropic(
+ response=response,
+ tool_name_mapping=None,
+ )
+
+ assert anthropic_response["usage"]["input_tokens"] == 70
+ assert anthropic_response["usage"]["output_tokens"] == 50
+ assert anthropic_response["usage"]["cache_read_input_tokens"] == 30
+ assert anthropic_response["usage"]["cache_creation_input_tokens"] == 20
+
+
+def test_translate_openai_response_to_anthropic_cache_tokens_from_usage_fields():
+ usage = Usage(prompt_tokens=120, completion_tokens=50, total_tokens=170)
+ usage.cache_read_input_tokens = 30
+ usage.cache_creation_input_tokens = 20
+
+ response = ModelResponse(
+ id="test-id",
+ choices=[
+ Choices(
+ index=0,
+ finish_reason="stop",
+ message=Message(
+ role="assistant",
+ content="Test response",
+ ),
+ )
+ ],
+ model="claude-3-sonnet-20240229",
+ usage=usage,
+ )
+
+ adapter = LiteLLMAnthropicMessagesAdapter()
+ anthropic_response = adapter.translate_openai_response_to_anthropic(
+ response=response,
+ tool_name_mapping=None,
+ )
+
+ assert anthropic_response["usage"]["input_tokens"] == 70
+ assert anthropic_response["usage"]["output_tokens"] == 50
+ assert anthropic_response["usage"]["cache_read_input_tokens"] == 30
+ assert anthropic_response["usage"]["cache_creation_input_tokens"] == 20
+
+
+def test_translate_openai_response_to_anthropic_cache_tokens_from_private_usage_fields():
+ usage = Usage(prompt_tokens=120, completion_tokens=50, total_tokens=170)
+
+ response = ModelResponse(
+ id="test-id",
+ choices=[
+ Choices(
+ index=0,
+ finish_reason="stop",
+ message=Message(
+ role="assistant",
+ content="Test response",
+ ),
+ )
+ ],
+ model="claude-3-sonnet-20240229",
+ usage=usage,
+ )
+ response.usage._cache_read_input_tokens = 30
+ response.usage._cache_creation_input_tokens = 20
+
+ adapter = LiteLLMAnthropicMessagesAdapter()
+ anthropic_response = adapter.translate_openai_response_to_anthropic(
+ response=response,
+ tool_name_mapping=None,
+ )
+
+ assert anthropic_response["usage"]["input_tokens"] == 70
+ assert anthropic_response["usage"]["output_tokens"] == 50
+ assert anthropic_response["usage"]["cache_read_input_tokens"] == 30
+ assert anthropic_response["usage"]["cache_creation_input_tokens"] == 20
+
+
+def test_translate_streaming_openai_response_to_anthropic_cache_tokens_from_prompt_tokens_details():
+ from litellm.types.utils import PromptTokensDetailsWrapper
+
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=30,
+ cache_creation_tokens=20,
+ ),
+ )
+ response = ModelResponseStream(
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(),
+ finish_reason="stop",
+ )
+ ],
+ usage=usage,
+ )
+
+ adapter = LiteLLMAnthropicMessagesAdapter()
+ message_delta = adapter.translate_streaming_openai_response_to_anthropic(
+ response=response,
+ current_content_block_index=0,
+ )
+
+ assert message_delta["usage"]["input_tokens"] == 70
+ assert message_delta["usage"]["output_tokens"] == 50
+ assert message_delta["usage"]["cache_read_input_tokens"] == 30
+ assert message_delta["usage"]["cache_creation_input_tokens"] == 20
+
+
+def test_translate_streaming_openai_response_to_anthropic_cache_tokens_from_hidden_params_usage():
+ from litellm.types.utils import PromptTokensDetailsWrapper
+
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=30,
+ cache_creation_tokens=20,
+ ),
+ )
+ response = ModelResponseStream(
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(),
+ finish_reason="stop",
+ )
+ ],
+ )
+ response._hidden_params = {"usage": usage}
+
+ adapter = LiteLLMAnthropicMessagesAdapter()
+ message_delta = adapter.translate_streaming_openai_response_to_anthropic(
+ response=response,
+ current_content_block_index=0,
+ )
+
+ assert message_delta["usage"]["input_tokens"] == 70
+ assert message_delta["usage"]["output_tokens"] == 50
+ assert message_delta["usage"]["cache_read_input_tokens"] == 30
+ assert message_delta["usage"]["cache_creation_input_tokens"] == 20
+
+
+def test_translate_streaming_openai_response_to_anthropic_cache_tokens_with_applied_edits():
+ from litellm.types.utils import PromptTokensDetailsWrapper
+
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=30,
+ cache_creation_tokens=20,
+ ),
+ )
+ response = ModelResponseStream(
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(),
+ finish_reason="stop",
+ )
+ ],
+ usage=usage,
+ )
+
+ adapter = LiteLLMAnthropicMessagesAdapter()
+ message_delta = adapter.translate_streaming_openai_response_to_anthropic(
+ response=response,
+ current_content_block_index=0,
+ applied_edits=[{"type": "compact_20260112"}],
+ )
+
+ assert message_delta["usage"]["input_tokens"] == 70
+ assert message_delta["usage"]["output_tokens"] == 50
+ assert message_delta["usage"]["cache_read_input_tokens"] == 30
+ assert message_delta["usage"]["cache_creation_input_tokens"] == 20
+ assert message_delta["context_management"]["applied_edits"][0]["type"] == (
+ "compact_20260112"
+ )
+
+
# =====================================================================
# Web Search Tool Transformation Tests
# =====================================================================
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_combined_chunk.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_combined_chunk.py
index f74c5b61300..d67de0dcaf8 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_combined_chunk.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_combined_chunk.py
@@ -24,6 +24,7 @@ from litellm.types.utils import (
Message,
ModelResponse,
ModelResponseStream,
+ PromptTokensDetailsWrapper,
StreamingChoices,
Usage,
)
@@ -88,6 +89,59 @@ def test_fake_stream_usage_preserved():
assert message_delta["usage"]["input_tokens"] == 10
+def test_delayed_usage_chunk_preserves_cache_tokens():
+ usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=5,
+ total_tokens=125,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=30,
+ cache_creation_tokens=20,
+ ),
+ )
+ chunks = [
+ ModelResponseStream(
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content="Two."),
+ finish_reason=None,
+ )
+ ],
+ ),
+ ModelResponseStream(
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(),
+ finish_reason="stop",
+ )
+ ],
+ ),
+ ModelResponseStream(
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(),
+ finish_reason=None,
+ )
+ ],
+ usage=usage,
+ ),
+ ]
+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="gpt-4o")
+ events = list(wrapper)
+
+ message_delta = next(
+ event for event in events if event.get("type") == "message_delta"
+ )
+
+ assert message_delta["usage"]["input_tokens"] == 70
+ assert message_delta["usage"]["output_tokens"] == 5
+ assert message_delta["usage"]["cache_read_input_tokens"] == 30
+ assert message_delta["usage"]["cache_creation_input_tokens"] == 20
+
+
def test_splitter_passes_through_non_combined_chunks():
"""A chunk with content but no finish_reason is not split."""
chunk = ModelResponseStream(
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py
index 8bc39a6d85e..d9d9474d6f3 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py
@@ -30,7 +30,9 @@ from litellm.types.utils import (
ChatCompletionDeltaToolCall,
Delta,
Function,
+ PromptTokensDetailsWrapper,
StreamingChoices,
+ Usage,
)
@@ -107,6 +109,34 @@ def _input_json_deltas(events: List[dict]) -> List[str]:
]
+def test_held_stop_reason_usage_merge_preserves_openai_cache_token_details():
+ """OpenAI-compatible usage chunks carry cache reads in prompt_tokens_details."""
+ wrapper = AnthropicStreamWrapper(completion_stream=iter([]), model="claude-x")
+ wrapper.holding_stop_reason_chunk = {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn"},
+ "usage": {"input_tokens": 0, "output_tokens": 0},
+ }
+
+ usage_chunk = MagicMock()
+ usage_chunk.usage = Usage(
+ prompt_tokens=120,
+ completion_tokens=50,
+ total_tokens=170,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=30,
+ cache_creation_tokens=20,
+ ),
+ )
+
+ merged_chunk = wrapper._merge_usage_into_held_stop_reason_chunk(usage_chunk)
+
+ assert merged_chunk["usage"]["input_tokens"] == 70
+ assert merged_chunk["usage"]["output_tokens"] == 50
+ assert merged_chunk["usage"]["cache_read_input_tokens"] == 30
+ assert merged_chunk["usage"]["cache_creation_input_tokens"] == 20
+
+
def test_first_text_delta_after_tool_use_is_not_dropped_sync():
"""A tool_use -> text transition (text resuming after a tool call) carries
the resumed text's first token in the trigger chunk. Without the fix it was
diff --git a/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py b/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
index 03b72c504b8..b6c055f4390 100644
--- a/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
+++ b/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
@@ -159,6 +159,59 @@ class TestGetAnthropicHeaders:
assert "authorization" not in headers
assert "anthropic-dangerous-direct-browser-access" not in headers
+ def test_custom_api_base_uses_bearer_header(self):
+ """Custom api_base and non-standard API key should produce Authorization: Bearer header when opted in."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ config = AnthropicModelInfo()
+ headers = config.get_anthropic_headers(
+ api_key="my-custom-ollama-token",
+ computer_tool_used=False,
+ prompt_caching_set=False,
+ pdf_used=False,
+ is_vertex_request=False,
+ api_base="https://ollama.com/",
+ use_bearer_for_custom_base=True,
+ )
+
+ assert headers["authorization"] == "Bearer my-custom-ollama-token"
+ assert "x-api-key" not in headers
+
+ def test_custom_api_base_uses_bearer_header_already_starts_with_bearer(self):
+ """If the key already starts with Bearer and Bearer opt-in is enabled, use it directly."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ config = AnthropicModelInfo()
+ headers = config.get_anthropic_headers(
+ api_key="Bearer my-custom-ollama-token",
+ computer_tool_used=False,
+ prompt_caching_set=False,
+ pdf_used=False,
+ is_vertex_request=False,
+ api_base="https://ollama.com/",
+ use_bearer_for_custom_base=True,
+ )
+
+ assert headers["authorization"] == "Bearer my-custom-ollama-token"
+ assert "x-api-key" not in headers
+
+ def test_custom_api_base_uses_x_api_key_when_standard_key(self):
+ """If the key is standard sk-ant- key, use x-api-key even with custom api_base."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ config = AnthropicModelInfo()
+ headers = config.get_anthropic_headers(
+ api_key=FAKE_REGULAR_KEY,
+ computer_tool_used=False,
+ prompt_caching_set=False,
+ pdf_used=False,
+ is_vertex_request=False,
+ api_base="https://ollama.com/",
+ )
+
+ assert headers["x-api-key"] == FAKE_REGULAR_KEY
+ assert "authorization" not in headers
+
def test_oauth_includes_standard_headers(self):
"""OAuth path should still include standard Anthropic headers."""
from litellm.llms.anthropic.common_utils import AnthropicModelInfo
@@ -242,6 +295,46 @@ class TestValidateEnvironmentOAuth:
assert updated_headers["x-api-key"] == FAKE_REGULAR_KEY
assert "authorization" not in updated_headers
+
+ def test_custom_api_base_via_param(self):
+ """validate_environment uses Bearer when use_bearer_for_custom_base is set in litellm_params."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ config = AnthropicModelInfo()
+ headers = {}
+
+ updated_headers = config.validate_environment(
+ headers=headers,
+ model="claude-sonnet-4-5-20250929",
+ messages=[{"role": "user", "content": "Hello"}],
+ optional_params={},
+ litellm_params={"use_bearer_for_custom_base": True},
+ api_key="custom-api-key",
+ api_base="https://custom-gateway.com",
+ )
+
+ assert updated_headers["authorization"] == "Bearer custom-api-key"
+ assert "x-api-key" not in updated_headers
+
+ def test_custom_api_base_via_litellm_params(self):
+ """validate_environment uses Bearer when api_base and use_bearer_for_custom_base are in litellm_params."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ config = AnthropicModelInfo()
+ headers = {}
+
+ updated_headers = config.validate_environment(
+ headers=headers,
+ model="claude-sonnet-4-5-20250929",
+ messages=[{"role": "user", "content": "Hello"}],
+ optional_params={},
+ litellm_params={"api_base": "https://custom-gateway.com", "use_bearer_for_custom_base": True},
+ api_key="custom-api-key",
+ api_base=None,
+ )
+
+ assert updated_headers["authorization"] == "Bearer custom-api-key"
+ assert "x-api-key" not in updated_headers
assert "anthropic-dangerous-direct-browser-access" not in updated_headers
@@ -1004,6 +1097,20 @@ class TestGetAuthHeader:
result = AnthropicModelInfo.get_auth_header()
assert result == {"authorization": f"Bearer {FAKE_OAUTH_TOKEN}"}
+ def test_custom_api_base_get_auth_header_uses_bearer(self):
+ """Non-standard API key and custom api_base returns Bearer when use_bearer_for_custom_base=True."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ result = AnthropicModelInfo.get_auth_header(api_key="my-custom-key", api_base="https://custom-gateway.com", use_bearer_for_custom_base=True)
+ assert result == {"authorization": "Bearer my-custom-key"}
+
+ def test_custom_api_base_get_auth_header_uses_x_api_key_when_standard(self):
+ """Standard sk-ant- key with custom api_base should still return x-api-key."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ result = AnthropicModelInfo.get_auth_header(api_key=FAKE_REGULAR_KEY, api_base="https://custom-gateway.com")
+ assert result == {"x-api-key": FAKE_REGULAR_KEY}
+
class TestGetApiBaseFallbackChain:
"""Tests for AnthropicModelInfo.get_api_base() fallback to ANTHROPIC_BASE_URL."""
diff --git a/tests/test_litellm/llms/bedrock/test_bedrock_common_utils.py b/tests/test_litellm/llms/bedrock/test_bedrock_common_utils.py
index 6298eeb25e9..6b869076044 100644
--- a/tests/test_litellm/llms/bedrock/test_bedrock_common_utils.py
+++ b/tests/test_litellm/llms/bedrock/test_bedrock_common_utils.py
@@ -263,3 +263,123 @@ def test_bundled_bedrock_opus_model_info_declares_output_config_effort_ceiling(
model_info = GetModelCostMap.load_local_model_cost_map()[model]
assert model_info["bedrock_output_config_effort_ceiling"] == expected_ceiling
+
+
+def test_route_prefix_matched_as_path_segment_not_substring():
+ """Route tokens like ``mantle/`` must match only at a path-segment boundary.
+
+ The ``bedrock_mantle/`` provider prefix contains the substring ``mantle/``;
+ a substring match misroutes ``bedrock_mantle/openai.gpt-5.5`` to the Claude
+ Mythos mantle config, whose request transform strips ``mantle/`` and mangles
+ the body model into ``bedrock_openai.gpt-5.5``. These assertions fail under
+ the old substring matching and pass once matching is anchored to ``startswith``
+ or a ``/`` boundary.
+ """
+ # The bedrock_mantle/ provider prefix must NOT be read as the mantle/ route.
+ assert (
+ BedrockModelInfo.get_bedrock_route("bedrock_mantle/openai.gpt-5.5") != "mantle"
+ )
+ assert (
+ BedrockModelInfo.get_bedrock_route("bedrock_mantle/openai.gpt-5.4") == "invoke"
+ )
+ assert (
+ BedrockModelInfo._explicit_mantle_route("bedrock_mantle/openai.gpt-5.5")
+ is False
+ )
+
+ # A genuine mantle route still resolves, via the startswith branch...
+ assert (
+ BedrockModelInfo.get_bedrock_route("mantle/anthropic.claude-mythos-preview")
+ == "mantle"
+ )
+ # ...and via the mid-path "/mantle/" branch (after the bedrock/ provider prefix).
+ assert (
+ BedrockModelInfo.get_bedrock_route(
+ "bedrock/mantle/anthropic.claude-mythos-preview"
+ )
+ == "mantle"
+ )
+
+
+def test_model_has_route_prefix_exercises_both_branches():
+ """``_model_has_route_prefix`` matches on ``startswith`` or a ``/`` boundary only."""
+ # startswith branch
+ assert (
+ BedrockModelInfo._model_has_route_prefix(
+ "mantle/anthropic.claude-mythos-preview", "mantle/"
+ )
+ is True
+ )
+ # f"/{prefix}" boundary branch
+ assert (
+ BedrockModelInfo._model_has_route_prefix(
+ "bedrock/mantle/anthropic.claude-mythos-preview", "mantle/"
+ )
+ is True
+ )
+ # neither branch: the token only appears glued to another segment
+ assert (
+ BedrockModelInfo._model_has_route_prefix(
+ "bedrock_mantle/openai.gpt-5.5", "mantle/"
+ )
+ is False
+ )
+
+
+ "route_method, token",
+ [
+ (BedrockModelInfo._explicit_converse_route, "converse"),
+ (BedrockModelInfo._explicit_converse_like_route, "converse_like"),
+ (BedrockModelInfo._explicit_invoke_route, "invoke"),
+ (BedrockModelInfo._explicit_async_invoke_route, "async_invoke"),
+ (BedrockModelInfo._explicit_agent_route, "agent"),
+ (BedrockModelInfo._explicit_agentcore_route, "agentcore"),
+ (BedrockModelInfo._explicit_claude_platform_route, "claude_platform"),
+ (BedrockModelInfo._explicit_openai_route, "openai"),
+ ],
+ ids=[
+ "converse",
+ "converse_like",
+ "invoke",
+ "async_invoke",
+ "agent",
+ "agentcore",
+ "claude_platform",
+ "openai",
+ ],
+)
+def test_explicit_route_helpers_match_token_only_as_path_segment(route_method, token):
+ """Each migrated ``_explicit_*_route`` matches its token only as a path segment.
+
+ A leading segment (start of the id or right after a ``/``) matches; the token
+ glued onto a preceding segment does not. Reverting any method to the old
+ ``"<token>/" in model`` substring check makes the non-segment case return True
+ and fails this test.
+ """
+ # leading-segment forms match
+ assert route_method(f"{token}/some-model") is True
+ assert route_method(f"bedrock/{token}/some-model") is True
+ # the token only as a non-segment substring must not match
+ assert route_method(f"x{token}/y") is False
+
+
+def test_explicit_invoke_route_does_not_match_async_invoke():
+ """``invoke/`` must not substring-match ``async_invoke/`` models.
+
+ This is the concrete improvement of the segment-boundary migration: the old
+ ``"invoke/" in model`` check wrongly classified async-invoke models as the
+ invoke route.
+ """
+ async_invoke_model = "async_invoke/twelvelabs.marengo-embed-2-7-v1:0"
+ assert BedrockModelInfo._explicit_invoke_route(async_invoke_model) is False
+ assert (
+ BedrockModelInfo._explicit_invoke_route(f"bedrock/{async_invoke_model}")
+ is False
+ )
+ # ...while async_invoke/ is still detected as its own route.
+ assert BedrockModelInfo._explicit_async_invoke_route(async_invoke_model) is True
+ assert (
+ BedrockModelInfo._explicit_async_invoke_route(f"bedrock/{async_invoke_model}")
+ is True
+ )
diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_context_circulation.py b/tests/test_litellm/llms/vertex_ai/gemini/test_context_circulation.py
index 6d913ad5d1d..1422531edbf 100644
--- a/tests/test_litellm/llms/vertex_ai/gemini/test_context_circulation.py
+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_context_circulation.py
@@ -22,7 +22,6 @@ from litellm.llms.vertex_ai.gemini.transformation import (
)
from litellm.types.llms.vertex_ai import HttpxPartType
-
# --- Response extraction tests ---
@@ -63,6 +62,7 @@ class TestExtractServerSideToolInvocations:
assert result[0]["args"] == {"queries": ["weather Buenos Aires"]}
assert result[0]["response"] == {"weather": "Sunny, 20°C"}
assert result[0]["thought_signature"] == "sig_call_1"
+ assert result[0]["response_thought_signature"] == "sig_resp_1"
def test_returns_none_when_no_server_side_tools(self):
"""No toolCall/toolResponse parts → returns None."""
@@ -145,6 +145,59 @@ class TestExtractServerSideToolInvocations:
assert result[0]["id"] == "exec1"
assert "response" not in result[0]
+ def test_extracts_tool_call_and_response_with_different_signatures(self):
+ """Case where toolCall and toolResponse have different signatures."""
+ parts: List[HttpxPartType] = [
+ {
+ "thoughtSignature": "sig_call_1",
+ "toolCall": {
+ "toolType": "GOOGLE_SEARCH_WEB",
+ "id": "abc123",
+ "args": {"queries": ["weather Buenos Aires"]},
+ },
+ },
+ {
+ "thoughtSignature": "sig_resp_1",
+ "toolResponse": {
+ "toolType": "GOOGLE_SEARCH_WEB",
+ "id": "abc123",
+ "response": {"weather": "Sunny, 20°C"},
+ },
+ },
+ ]
+
+ result = VertexGeminiConfig._extract_server_side_tool_invocations(parts)
+
+ assert result is not None
+ assert len(result) == 1
+ assert result[0]["tool_type"] == "GOOGLE_SEARCH_WEB"
+ assert result[0]["id"] == "abc123"
+ assert result[0]["args"] == {"queries": ["weather Buenos Aires"]}
+ assert result[0]["response"] == {"weather": "Sunny, 20°C"}
+ assert result[0]["thought_signature"] == "sig_call_1"
+ assert result[0]["response_thought_signature"] == "sig_resp_1"
+
+ def test_orphan_response_signature_extraction(self):
+ """Orphan toolResponse is captured and has response_thought_signature set."""
+ parts: List[HttpxPartType] = [
+ {
+ "thoughtSignature": "sig_resp_1",
+ "toolResponse": {
+ "toolType": "GOOGLE_SEARCH_WEB",
+ "id": "orphan123",
+ "response": {"result": "some response"},
+ },
+ },
+ ]
+
+ result = VertexGeminiConfig._extract_server_side_tool_invocations(parts)
+
+ assert result is not None
+ assert len(result) == 1
+ assert result[0]["id"] == "orphan123"
+ assert result[0]["response"] == {"result": "some response"}
+ assert result[0]["response_thought_signature"] == "sig_resp_1"
+
# --- Input re-injection tests ---
@@ -200,6 +253,76 @@ class TestReInjectServerSideToolInvocations:
"weather": "Sunny, 20°C"
}
+ def test_roundtrip_single_invocation_with_different_signatures(self):
+ """Server-side invocations with different signatures for call and response."""
+ messages = [
+ {"role": "user", "content": "What's the weather?"},
+ {
+ "role": "assistant",
+ "content": "It's sunny in Buenos Aires.",
+ "provider_specific_fields": {
+ "server_side_tool_invocations": [
+ {
+ "tool_type": "GOOGLE_SEARCH_WEB",
+ "id": "abc123",
+ "args": {"queries": ["weather Buenos Aires"]},
+ "response": {"weather": "Sunny, 20°C"},
+ "thought_signature": "sig_call",
+ "response_thought_signature": "sig_resp",
+ }
+ ]
+ },
+ },
+ {"role": "user", "content": "Thanks!"},
+ ]
+
+ contents = _gemini_convert_messages_with_history(messages)
+
+ model_turn = [c for c in contents if c["role"] == "model"]
+ assert len(model_turn) == 1
+
+ parts = model_turn[0]["parts"]
+ tool_call_parts = [p for p in parts if "toolCall" in p]
+ tool_response_parts = [p for p in parts if "toolResponse" in p]
+
+ assert len(tool_call_parts) == 1
+ assert tool_call_parts[0]["thoughtSignature"] == "sig_call"
+
+ assert len(tool_response_parts) == 1
+ assert tool_response_parts[0]["thoughtSignature"] == "sig_resp"
+
+ def test_roundtrip_orphan_response_signature(self):
+ """Orphan response signature is preserved and re-injected into toolResponse part."""
+ messages = [
+ {"role": "user", "content": "What's the weather?"},
+ {
+ "role": "assistant",
+ "content": "It's sunny in Buenos Aires.",
+ "provider_specific_fields": {
+ "server_side_tool_invocations": [
+ {
+ "tool_type": "GOOGLE_SEARCH_WEB",
+ "id": "orphan123",
+ "response": {"result": "some response"},
+ "response_thought_signature": "sig_orphan_resp",
+ }
+ ]
+ },
+ },
+ {"role": "user", "content": "Thanks!"},
+ ]
+
+ contents = _gemini_convert_messages_with_history(messages)
+
+ model_turn = [c for c in contents if c["role"] == "model"]
+ assert len(model_turn) == 1
+
+ parts = model_turn[0]["parts"]
+ tool_response_parts = [p for p in parts if "toolResponse" in p]
+
+ assert len(tool_response_parts) == 1
+ assert tool_response_parts[0]["thoughtSignature"] == "sig_orphan_resp"
+
def test_no_invocations_no_extra_parts(self):
"""Without server_side_tool_invocations, no extra parts are added."""
messages = [
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
index 47c9396f121..27f9a311250 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
@@ -1800,3 +1800,71 @@ class TestConnectionErrorMessage:
message = rest_endpoints._connection_error_message(RuntimeError("weird"))
assert "weird" not in message
assert "proxy logs" in message.lower()
+
+
+class TestToolResponseMcpInfoEnrichment:
+ """The REST tools/list response must expose the user-facing alias and the
+ server_id alongside the internal server_name so clients (agent builder UIs)
+ can map the internal config key to a friendly name without needing the
+ mcp_routes-gated server listing.
+ """
+
+ def test_enriches_mcp_info_with_alias_and_server_id(self):
+ from mcp.types import Tool as MCPTool
+
+ from litellm.proxy._experimental.mcp_server.server import MCPServer
+ from litellm.types.mcp import MCPTransport
+
+ server = MCPServer(
+ server_id="a1b2c3d4",
+ name="mcpAtlassian",
+ alias="atlassian",
+ server_name="mcpAtlassian",
+ transport=MCPTransport.http,
+ mcp_info={"server_name": "mcpAtlassian"},
+ )
+ tools = [
+ MCPTool(
+ name="get_issue",
+ description="Fetch a Jira issue",
+ inputSchema={"type": "object"},
+ )
+ ]
+
+ result = rest_endpoints._create_tool_response_objects(tools, server)
+
+ assert result[0].mcp_info == {
+ "server_name": "mcpAtlassian",
+ "server_id": "a1b2c3d4",
+ "alias": "atlassian",
+ }
+
+ def test_alias_none_is_explicit_in_mcp_info(self):
+ from mcp.types import Tool as MCPTool
+
+ from litellm.proxy._experimental.mcp_server.server import MCPServer
+ from litellm.types.mcp import MCPTransport
+
+ server = MCPServer(
+ server_id="server-uuid",
+ name="no_alias_server",
+ alias=None,
+ server_name="no_alias_server",
+ transport=MCPTransport.http,
+ mcp_info={"server_name": "no_alias_server"},
+ )
+ tools = [
+ MCPTool(
+ name="ping",
+ description="Ping",
+ inputSchema={"type": "object"},
+ )
+ ]
+
+ result = rest_endpoints._create_tool_response_objects(tools, server)
+
+ assert result[0].mcp_info == {
+ "server_name": "no_alias_server",
+ "server_id": "server-uuid",
+ "alias": None,
+ }
diff --git a/tests/test_litellm/proxy/management_endpoints/test_common_utils.py b/tests/test_litellm/proxy/management_endpoints/test_common_utils.py
index 7a8d04507dc..dd9cbcf5232 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_common_utils.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_common_utils.py
@@ -570,3 +570,41 @@ class TestRequireCallerUserIdForNonAdmin:
assert exc_info.value.status_code == 403
assert "Service-account keys" in str(exc_info.value.detail)
+
+
+class TestValidateFiniteSpend:
+ """`validate_finite_spend` rejects NaN/±inf so a non-finite spend cannot
+ bypass `spend >= max_budget` enforcement (NaN/-inf compare false)."""
+
+ def test_none_is_allowed(self):
+ from litellm.proxy.management_endpoints.common_utils import (
+ validate_finite_spend,
+ )
+
+ assert validate_finite_spend(None) is None
+
+ def test_finite_value_is_allowed(self):
+ from litellm.proxy.management_endpoints.common_utils import (
+ validate_finite_spend,
+ )
+
+ assert validate_finite_spend(0.0) is None
+ assert validate_finite_spend(12.5) is None
+ # Negative spend is intentionally allowed. Admins may set a negative
+ # spend counter to grant an entity extra allowance for the current
+ # budget period only (e.g. a large one-time spend grant), effectively
+ # raising their headroom without raising the recurring budget ceiling.
+ # Future changes should continue to allow negative spend counters.
+ assert validate_finite_spend(-50.0) is None
+
+ @pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")])
+ def test_non_finite_is_rejected(self, bad):
+ from fastapi import HTTPException
+
+ from litellm.proxy.management_endpoints.common_utils import (
+ validate_finite_spend,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ validate_finite_spend(bad)
+ assert exc_info.value.status_code == 400
diff --git a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
index b4602e0ad8b..27e82df90c1 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
@@ -3102,6 +3102,86 @@ async def test_ghsa_wvg4_proxy_admin_can_update_user_budget(mocker):
assert result is not None
+async def test_admin_user_update_spend_invalidates_counter(mocker):
+ """A direct /user/update spend change must invalidate the cross-pod
+ spend counter so enforcement re-reads the new DB value."""
+ from litellm.proxy.management_endpoints.internal_user_endpoints import (
+ _update_single_user_helper,
+ )
+
+ mock_prisma_client = mocker.MagicMock()
+ existing_user = mocker.MagicMock()
+ existing_user.model_dump.return_value = {"user_id": "target-user", "spend": 50.0}
+ existing_user.user_id = "target-user"
+ mock_prisma_client.db.litellm_usertable.find_first = mocker.AsyncMock(
+ return_value=existing_user
+ )
+ mock_prisma_client.update_data = mocker.AsyncMock(
+ return_value={"user_id": "target-user", "spend": -25.0}
+ )
+ mock_prisma_client.jsonify_object = mocker.MagicMock(side_effect=lambda x: x)
+ mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ mocker.patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+ mock_invalidate = mocker.patch(
+ "litellm.proxy.proxy_server._invalidate_spend_counter",
+ new=mocker.AsyncMock(),
+ )
+
+ # Use a negative spend: this also implicitly validates that negative spend
+ # is allowed, which is desirable. Admins may grant an entity extra
+ # allowance for the current budget period only (a one-time spend grant)
+ # without raising the recurring budget ceiling. Future changes should
+ # continue allowing negative spend counters.
+ user_request = UpdateUserRequest(user_id="target-user", spend=-25)
+ admin_caller = UserAPIKeyAuth(
+ user_id="admin-1", user_role=LitellmUserRoles.PROXY_ADMIN
+ )
+
+ await _update_single_user_helper(
+ user_request=user_request, user_api_key_dict=admin_caller
+ )
+ mock_invalidate.assert_awaited_once_with(counter_key="spend:user:target-user")
+
+
+async def test_user_update_rejects_non_finite_spend(mocker):
+ """NaN/inf spend is rejected before any DB write or counter invalidation."""
+ from fastapi import HTTPException
+
+ from litellm.proxy.management_endpoints.internal_user_endpoints import (
+ _update_single_user_helper,
+ )
+
+ mock_prisma_client = mocker.MagicMock()
+ existing_user = mocker.MagicMock()
+ existing_user.model_dump.return_value = {"user_id": "target-user", "spend": 50.0}
+ existing_user.user_id = "target-user"
+ mock_prisma_client.db.litellm_usertable.find_first = mocker.AsyncMock(
+ return_value=existing_user
+ )
+ mock_prisma_client.update_data = mocker.AsyncMock()
+ mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ mocker.patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
+ mock_invalidate = mocker.patch(
+ "litellm.proxy.proxy_server._invalidate_spend_counter",
+ new=mocker.AsyncMock(),
+ )
+
+ user_request = UpdateUserRequest(user_id="target-user", spend=float("nan"))
+ admin_caller = UserAPIKeyAuth(
+ user_id="admin-1", user_role=LitellmUserRoles.PROXY_ADMIN
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await _update_single_user_helper(
+ user_request=user_request, user_api_key_dict=admin_caller
+ )
+ assert exc.value.status_code == 400
+ mock_prisma_client.update_data.assert_not_called()
+ mock_invalidate.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_resolve_user_email_metadata_maps_page_user_ids_to_email(mocker):
"""Regression for LIT-3889.
diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
index b8ec8a8a388..97397fb06be 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
@@ -6639,9 +6639,9 @@ async def test_reset_key_spend_success(monkeypatch):
@pytest.mark.asyncio
-async def test_update_key_spend_invalidates_counter(monkeypatch):
+async def test_update_key_spend_updates_counter(monkeypatch):
"""
- Test that updating a key's spend via update_key_fn immediately invalidates the spend counter.
+ Test that updating a key's spend via update_key_fn immediately updates the spend counter.
"""
from litellm.proxy.management_endpoints.key_management_endpoints import (
update_key_fn,
@@ -6676,15 +6676,17 @@ async def test_update_key_spend_invalidates_counter(monkeypatch):
monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
monkeypatch.setattr("litellm.store_audit_logs", False)
+ mock_spend_counter_cache = MagicMock()
+ mock_spend_counter_cache.redis_cache = MagicMock()
+ mock_spend_counter_cache.redis_cache.async_set_cache = AsyncMock()
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.spend_counter_cache",
+ mock_spend_counter_cache,
+ )
- with (
- patch(
- "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object"
- ) as mock_delete_cache,
- patch(
- "litellm.proxy.proxy_server._invalidate_spend_counter"
- ) as mock_invalidate,
- ):
+ with patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object"
+ ) as mock_delete_cache:
mock_delete_cache.return_value = None
user_api_key_dict = UserAPIKeyAuth(
@@ -6704,7 +6706,12 @@ async def test_update_key_spend_invalidates_counter(monkeypatch):
)
mock_delete_cache.assert_awaited_once()
- mock_invalidate.assert_awaited_once_with(counter_key=f"spend:key:{hashed_key}")
+ mock_spend_counter_cache.in_memory_cache.set_cache.assert_called_once_with(
+ key=f"spend:key:{hashed_key}", value=0.0, ttl=60
+ )
+ mock_spend_counter_cache.redis_cache.async_set_cache.assert_awaited_once_with(
+ key=f"spend:key:{hashed_key}", value=0.0, ttl=60
+ )
@pytest.mark.asyncio
@@ -9718,6 +9725,39 @@ class TestKeyOwnerPrivilegeEscalation:
assert exc_info.value.status_code == 403
mock_check.assert_called_once()
+ @pytest.mark.asyncio
+ async def test_creator_cannot_reset_own_spend_to_stale_value(self):
+ """Submitting `spend` equal to the stale DB value must still require
+ admin. The DB spend lags the live cross-pod counter, so an
+ "unchanged" spend on the non-admin path would let the creator
+ overwrite the live counter below real usage. Any explicit `spend`
+ is a budget change, regardless of value match."""
+ existing = self._make_existing_key(created_by="creator-123")
+ existing.spend = 0.0
+ # spend equals the stale DB value (0.0) — the old `!=` gate skipped
+ # the admin check here.
+ data = UpdateKeyRequest(key="sk-test", spend=0.0)
+ auth = self._make_auth(user_id="creator-123")
+
+ mock_check = AsyncMock(
+ side_effect=HTTPException(status_code=403, detail="Not authorized")
+ )
+ with patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
+ mock_check,
+ ):
+ with pytest.raises(HTTPException):
+ await _validate_update_key_data(
+ data=data,
+ existing_key_row=existing,
+ user_api_key_dict=auth,
+ llm_router=None,
+ premium_user=False,
+ prisma_client=AsyncMock(),
+ user_api_key_cache=MagicMock(),
+ )
+ mock_check.assert_called_once()
+
@pytest.mark.asyncio
async def test_assigned_user_blocked_from_model_escalation(self):
data = UpdateKeyRequest(key="sk-test", models=["gpt-4", "claude-opus"])
diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
index 592232f45f5..196ff045208 100644
--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
@@ -10,8 +10,8 @@ from __future__ import annotations
import os
from types import SimpleNamespace
-from typing import Any, Dict, List, Optional
-from unittest.mock import AsyncMock, MagicMock, patch
+from typing import Any, Dict
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -887,6 +887,84 @@ def test_ProxyConfig__add_deployment_invalid_litellm_params_skips(monkeypatch):
assert pc._add_deployment(db_models=[bad]) == 0
+def test_ProxyConfig__add_deployment_resolves_env_refs_after_db_decrypt(monkeypatch):
+ monkeypatch.setenv("LITELLM_DB_MODEL_API_KEY", "resolved-secret")
+ monkeypatch.setenv("LITELLM_MASTER_KEY", "master-secret")
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.decrypt_value_helper",
+ lambda value, key, return_original_value: value,
+ )
+ fake_router = MagicMock()
+ fake_router.upsert_deployment = MagicMock(return_value=True)
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", fake_router)
+ pc = ProxyConfig()
+ db_model = SimpleNamespace(
+ model_id="model-1",
+ model_name="env-model",
+ model_info={"id": "model-1"},
+ litellm_params={
+ "model": "openai/gpt-4o-mini",
+ "api_key": "os.environ/LITELLM_DB_MODEL_API_KEY",
+ "api_base": "os.environ/LITELLM_MASTER_KEY",
+ },
+ blocked=False,
+ )
+
+ added = pc._add_deployment(db_models=[db_model])
+ deployment = fake_router.upsert_deployment.call_args.kwargs["deployment"]
+
+ assert added == 1
+ assert deployment.litellm_params.api_key == "resolved-secret"
+ assert deployment.litellm_params.api_base == "os.environ/LITELLM_MASTER_KEY"
+
+
+def test_ProxyConfig__add_deployment_keeps_team_env_refs_literal(monkeypatch):
+ def fail_on_call(secret_name, *args, **kwargs):
+ raise AssertionError("team DB models should not resolve env refs")
+
+ monkeypatch.setenv("LITELLM_MASTER_KEY", "master-secret")
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.decrypt_value_helper",
+ lambda value, key, return_original_value: value,
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.get_secret", fail_on_call)
+ fake_router = MagicMock()
+ fake_router.upsert_deployment = MagicMock(return_value=True)
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", fake_router)
+ pc = ProxyConfig()
+ db_model = SimpleNamespace(
+ model_id="model-1",
+ model_name="model_name_team-1_abc",
+ model_info={"id": "model-1", "team_id": "team-1"},
+ litellm_params={
+ "model": "openai/gpt-4o-mini",
+ "api_key": "os.environ/LITELLM_MASTER_KEY",
+ "api_base": "https://attacker.example",
+ },
+ blocked=False,
+ )
+
+ added = pc._add_deployment(db_models=[db_model])
+ deployment = fake_router.upsert_deployment.call_args.kwargs["deployment"]
+
+ assert added == 1
+ assert deployment.litellm_params.api_key == "os.environ/LITELLM_MASTER_KEY"
+ assert deployment.litellm_params.api_base == "https://attacker.example"
+
+
+def test_ProxyConfig__resolve_db_litellm_param_skips_non_string_values(monkeypatch):
+ def fail_on_call(value, key, return_original_value):
+ raise AssertionError("decrypt_value_helper should only receive strings")
+
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.decrypt_value_helper",
+ fail_on_call,
+ )
+ pc = ProxyConfig()
+
+ assert pc._resolve_db_litellm_param(key="tpm", value=100) == 100
+
+
# ---------------------------------------------------------------------------
# ProxyConfig.decrypt_model_list_from_db
# ---------------------------------------------------------------------------
@@ -919,6 +997,71 @@ def test_ProxyConfig_decrypt_model_list_from_db_returns_decrypted(monkeypatch):
}
+def test_ProxyConfig_decrypt_model_list_from_db_resolves_env_refs_after_db_decrypt(
+ monkeypatch,
+):
+ monkeypatch.setenv("LITELLM_DB_MODEL_API_KEY", "resolved-secret")
+ monkeypatch.setenv("LITELLM_MASTER_KEY", "master-secret")
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.decrypt_value_helper",
+ lambda value, key, return_original_value: (
+ "os.environ/LITELLM_DB_MODEL_API_KEY"
+ if key == "api_key"
+ else "os.environ/LITELLM_MASTER_KEY" if key == "api_base" else value
+ ),
+ )
+ pc = ProxyConfig()
+ m = SimpleNamespace(
+ model_id="model-1",
+ model_name="env-model",
+ model_info={"id": "model-1"},
+ litellm_params={
+ "api_key": "encrypted-env-ref",
+ "api_base": "encrypted-api-base-env-ref",
+ "model": "openai/gpt-4o-mini",
+ },
+ blocked=False,
+ )
+
+ out = pc.decrypt_model_list_from_db(new_models=[m])
+
+ assert out[0]["litellm_params"]["api_key"] == "resolved-secret"
+ assert out[0]["litellm_params"]["api_base"] == "os.environ/LITELLM_MASTER_KEY"
+
+
+def test_ProxyConfig_decrypt_model_list_from_db_keeps_team_env_refs_literal_after_db_decrypt(
+ monkeypatch,
+):
+ def fail_on_call(secret_name, *args, **kwargs):
+ raise AssertionError("team DB models should not resolve env refs")
+
+ monkeypatch.setenv("LITELLM_MASTER_KEY", "master-secret")
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.decrypt_value_helper",
+ lambda value, key, return_original_value: (
+ "os.environ/LITELLM_MASTER_KEY" if key == "api_key" else value
+ ),
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.get_secret", fail_on_call)
+ pc = ProxyConfig()
+ m = SimpleNamespace(
+ model_id="model-1",
+ model_name="model_name_team-1_abc",
+ model_info={"id": "model-1", "team_id": "team-1"},
+ litellm_params={
+ "api_key": "encrypted-env-ref",
+ "api_base": "https://attacker.example",
+ "model": "openai/gpt-4o-mini",
+ },
+ blocked=False,
+ )
+
+ out = pc.decrypt_model_list_from_db(new_models=[m])
+
+ assert out[0]["litellm_params"]["api_key"] == "os.environ/LITELLM_MASTER_KEY"
+ assert out[0]["litellm_params"]["api_base"] == "https://attacker.example"
+
+
def test_ProxyConfig_decrypt_model_list_from_db_invalid_params_skips():
pc = ProxyConfig()
bad = SimpleNamespace(
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py b/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py
new file mode 100644
index 00000000000..04db7192364
--- /dev/null
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py
@@ -0,0 +1,73 @@
+"""Regression tests for the responses -> completion fallback bridge guard.
+
+When the Responses API falls back to chat completions (no native responses
+config), it must tag the forwarded ``litellm.completion`` / ``litellm.acompletion``
+call with ``_skip_responses_api_bridge=True`` so ``completion()`` does not bridge
+the request straight back to the Responses API and mutually recurse forever.
+
+Both fallback paths are covered: the sync ``response_api_handler`` (``_is_async``
+False) and the async ``async_response_api_handler`` (``_is_async`` True). The
+module-level ``litellm.completion`` / ``litellm.acompletion`` are patched to
+capture the forwarded kwargs; if the flag-setting line is removed the captured
+kwargs lack the flag and these tests fail.
+"""
+
+import os
+import sys
+from unittest.mock import patch
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../../.."))
+
+from litellm.responses.litellm_completion_transformation.handler import (
+ LiteLLMCompletionTransformationHandler,
+)
+
+
+class _StopForwarding(Exception):
+ """Raised by the mocked (a)completion once the forwarded kwargs are captured."""
+
+
+def test_sync_fallback_tags_skip_responses_api_bridge():
+ handler = LiteLLMCompletionTransformationHandler()
+ captured: dict = {}
+
+ def fake_completion(**kwargs):
+ captured.update(kwargs)
+ raise _StopForwarding()
+
+ with patch("litellm.completion", fake_completion):
+ with pytest.raises(_StopForwarding):
+ handler.response_api_handler(
+ model="gpt-4o",
+ input="hello",
+ responses_api_request={},
+ custom_llm_provider="openai",
+ _is_async=False,
+ )
+
+ assert captured.get("_skip_responses_api_bridge") is True
+
+
+async def test_async_fallback_tags_skip_responses_api_bridge():
+ handler = LiteLLMCompletionTransformationHandler()
+ captured: dict = {}
+
+ async def fake_acompletion(**kwargs):
+ captured.update(kwargs)
+ raise _StopForwarding()
+
+ with patch("litellm.acompletion", fake_acompletion):
+ coro = handler.response_api_handler(
+ model="gpt-4o",
+ input="hello",
+ responses_api_request={},
+ custom_llm_provider="openai",
+ _is_async=True,
+ )
+ with pytest.raises(_StopForwarding):
+ await coro
+
+ assert captured.get("_skip_responses_api_bridge") is True
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index ee3d4e835ba..b53acf930f2 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -21125,10 +21125,9 @@ export interface components {
};
/**
* Mode
- * @description The mode to test the model with
- * @default chat
+ * @description The mode to test the model with. If not provided, auto-detected from model capabilities.
*/
- mode: ("chat" | "completion" | "embedding" | "audio_speech" | "audio_transcription" | "image_generation" | "video_generation" | "batch" | "rerank" | "realtime" | "responses" | "ocr") | null;
+ mode?: ("chat" | "completion" | "embedding" | "audio_speech" | "audio_transcription" | "image_generation" | "video_generation" | "batch" | "rerank" | "realtime" | "responses" | "ocr") | null;
/**
* Model Info
* @description Model info for the health check