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]

Litellm oss staging (#29492)

Sameer Kankuteb84f7f82f731
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 56d516536e8..bae15f0362c 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -240,6 +240,7 @@ api_key: Optional[str] = None
openai_key: Optional[str] = None
groq_key: Optional[str] = None
gigachat_key: Optional[str] = None
+xai_key: Optional[str] = None
databricks_key: Optional[str] = None
openai_like_key: Optional[str] = None
azure_key: Optional[str] = None
diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
index 5fd42fe0d36..2547fd4d8c6 100644
--- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
+++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
@@ -144,6 +144,19 @@ async def convert_to_streaming_response_async(response_object: Optional[dict] =
choice_list: List[StreamingChoices] = []
+ if not response_object.get("choices"):
+ from litellm.exceptions import APIError
+
+ raise APIError(
+ status_code=500,
+ message=(
+ "LiteLLM: provider returned a response with no 'choices'. "
+ f"Raw keys: {list(response_object.keys())}"
+ ),
+ llm_provider="",
+ model="",
+ )
+
for idx, choice in enumerate(response_object["choices"]):
if (
choice["message"].get("tool_calls", None) is not None
@@ -213,6 +226,20 @@ def convert_to_streaming_response(response_object: Optional[dict] = None):
model_response_object = ModelResponseStream()
choice_list: List[StreamingChoices] = []
+
+ if not response_object.get("choices"):
+ from litellm.exceptions import APIError
+
+ raise APIError(
+ status_code=500,
+ message=(
+ "LiteLLM: provider returned a response with no 'choices'. "
+ f"Raw keys: {list(response_object.keys())}"
+ ),
+ llm_provider="",
+ model="",
+ )
+
for idx, choice in enumerate(response_object["choices"]):
delta = Delta(**choice["message"])
finish_reason = choice.get("finish_reason", None)
@@ -536,9 +563,20 @@ def convert_to_model_response_object( # noqa: PLR0915
return convert_to_streaming_response(response_object=response_object)
choice_list: List[Choices] = []
- assert response_object["choices"] is not None and isinstance(
+ if not response_object.get("choices") or not isinstance(
response_object["choices"], Iterable
- )
+ ):
+ from litellm.exceptions import APIError
+
+ raise APIError(
+ status_code=500,
+ message=(
+ "LiteLLM: provider returned a response with no 'choices'. "
+ f"Raw keys: {list(response_object.keys())}"
+ ),
+ llm_provider="",
+ model="",
+ )
for idx, choice in enumerate(response_object["choices"]):
## HANDLE JSON MODE - anthropic returns single function call]
@@ -816,7 +854,12 @@ def convert_to_model_response_object( # noqa: PLR0915
model_response_object.results = response_object["results"]
return model_response_object
- except Exception:
+ except Exception as e:
+ from litellm.exceptions import APIError
+
+ if isinstance(e, APIError):
+ raise
+
received_args = dict(
response_object=response_object,
model_response_object=model_response_object,
diff --git a/litellm/litellm_core_utils/secret_redaction.py b/litellm/litellm_core_utils/secret_redaction.py
index 5c4e3e3dacf..b526068589d 100644
--- a/litellm/litellm_core_utils/secret_redaction.py
+++ b/litellm/litellm_core_utils/secret_redaction.py
@@ -50,13 +50,15 @@ def _build_secret_patterns() -> "re.Pattern[str]":
r"(?<=://)[^\s'\"]*:[^\s'\"@]+(?=@)",
# Databricks personal access tokens
r"dapi[0-9a-f]{32}",
+ # Module-level provider keys logged as litellm.<provider>_key=<value>
+ r"litellm\.[A-Za-z0-9_]*_key['\"]?\s*[:=]\s*['\"]?[^\s,'\"})\]{}>]+",
# ── Key-name-based redaction ──
# Catches secrets inside dicts/config dumps by matching on the KEY name
# regardless of what the value looks like.
# e.g. 'master_key': 'any-value-here', "database_url": "postgres://..."
# private_key with PEM-aware value capture
r"""private_key['\"]?\s*[:=]\s*['\"]?(?:-----BEGIN[A-Z \-]*PRIVATE KEY-----[\s\S]*?-----END[A-Z \-]*PRIVATE KEY-----|[^\s,'\"})\]{}>]+)""",
- r"(?:master_key|database_url|db_url|connection_string|"
+ r"(?:master_key|xai_key|database_url|db_url|connection_string|"
r"signing_key|encryption_key|"
r"auth_token|access_token|refresh_token|"
r"slack_webhook_url|webhook_url|"
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
index 62eced8e6f0..a3ac465c463 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
@@ -229,9 +229,20 @@ async def anthropic_messages(
**kwargs,
)
- # Extract modified parameters
+ # Extract modified parameters. Pop every named param of `anthropic_messages`
+ # that we may forward explicitly downstream, so we (a) honor pre-request hook
+ # overrides and (b) avoid duplicate-keyword conflicts when splatting `kwargs`
+ # into call sites that already pass these as named arguments.
tools = request_kwargs.pop("tools", tools)
stream = request_kwargs.pop("stream", stream)
+ metadata = request_kwargs.pop("metadata", metadata)
+ stop_sequences = request_kwargs.pop("stop_sequences", stop_sequences)
+ system = request_kwargs.pop("system", system)
+ temperature = request_kwargs.pop("temperature", temperature)
+ thinking = request_kwargs.pop("thinking", thinking)
+ tool_choice = request_kwargs.pop("tool_choice", tool_choice)
+ top_k = request_kwargs.pop("top_k", top_k)
+ top_p = request_kwargs.pop("top_p", top_p)
# Propagate the provider derived inside pre-request hooks, if not already set.
# The litellm_params dict may have been overwritten by **kwargs in
# _execute_pre_request_hooks, so fall back to get_llm_provider() if needed.
@@ -265,8 +276,8 @@ async def anthropic_messages(
return short_circuit_response
# Run registered MessagesInterceptors (e.g. advisor orchestration loop).
- # api_key and api_base are explicit params (not in **kwargs) so pass them
- # explicitly so interceptor sub-calls can route to the same backend.
+ # Named params on `anthropic_messages` are bound to locals, not `**kwargs`,
+ # so forward them explicitly — otherwise interceptor sub-calls drop them.
for interceptor in get_messages_interceptors():
if interceptor.can_handle(tools, custom_llm_provider):
return await interceptor.handle(
@@ -278,6 +289,14 @@ async def anthropic_messages(
custom_llm_provider=custom_llm_provider,
api_key=api_key,
api_base=api_base,
+ metadata=metadata,
+ stop_sequences=stop_sequences,
+ system=system,
+ temperature=temperature,
+ thinking=thinking,
+ tool_choice=tool_choice,
+ top_k=top_k,
+ top_p=top_p,
**kwargs,
)
diff --git a/litellm/llms/apiserpent/__init__.py b/litellm/llms/apiserpent/__init__.py
new file mode 100644
index 00000000000..2edf992adc2
--- /dev/null
+++ b/litellm/llms/apiserpent/__init__.py
@@ -0,0 +1 @@
+"""APISerpent integration for LiteLLM."""
diff --git a/litellm/llms/apiserpent/search/__init__.py b/litellm/llms/apiserpent/search/__init__.py
new file mode 100644
index 00000000000..4e9f88a2f1d
--- /dev/null
+++ b/litellm/llms/apiserpent/search/__init__.py
@@ -0,0 +1,8 @@
+"""
+APISerpent Search API module.
+"""
+
+from litellm.llms.apiserpent.search.defaults import APISerpentSearchParams
+from litellm.llms.apiserpent.search.transformation import APISerpentSearchConfig
+
+__all__ = ["APISerpentSearchConfig", "APISerpentSearchParams"]
diff --git a/litellm/llms/apiserpent/search/defaults.py b/litellm/llms/apiserpent/search/defaults.py
new file mode 100644
index 00000000000..219178587d6
--- /dev/null
+++ b/litellm/llms/apiserpent/search/defaults.py
@@ -0,0 +1,70 @@
+"""
+Default parameter values and shared constants for APISerpent search.
+
+Single source of truth for the supported request parameters and their
+package-level defaults. See https://apiserpent.com/docs.
+"""
+
+from dataclasses import asdict, dataclass
+from typing import Dict, Literal, Optional
+
+SearchEngine = Literal["google", "bing", "yahoo", "ddg"]
+SafeSearch = Literal["off", "moderate", "strict"]
+Freshness = Literal["h", "1h", "d", "1d", "7d", "w", "m", "1m", "y", "1y"]
+ResponseFormat = Literal["full", "simple"]
+
+NUM_MIN = 1
+NUM_MIN_DEEP = 10
+NUM_MAX = 100
+PAGES_MIN = 1
+PAGES_MAX = 10
+
+
+@dataclass(frozen=True)
+class APISerpentSearchParams:
+ """
+ Supported APISerpent search parameters with package defaults.
+
+ Fields defaulting to ``None`` are only sent when the caller provides them;
+ the rest are always sent so behavior is deterministic regardless of any
+ server-side defaults.
+ """
+
+ engine: SearchEngine = "google"
+ country: str = "us"
+ num: int = 10
+ format: ResponseFormat = "full"
+ pages: Optional[int] = None
+ freshness: Optional[Freshness] = None
+ safe: Optional[SafeSearch] = None
+ language: Optional[str] = None
+ pixel_position: Optional[bool] = None
+
+ def __post_init__(self) -> None:
+ # num's deep-search floor (NUM_MIN_DEEP) is endpoint-specific and enforced
+ # in the transform layer; here we only bound the absolute range.
+ if not NUM_MIN <= self.num <= NUM_MAX:
+ raise ValueError(
+ f"num must be between {NUM_MIN} and {NUM_MAX}, got {self.num}"
+ )
+ if self.pages is not None and not PAGES_MIN <= self.pages <= PAGES_MAX:
+ raise ValueError(
+ f"pages must be between {PAGES_MIN} and {PAGES_MAX}, got {self.pages}"
+ )
+
+ def to_request_params(self) -> Dict:
+ """Return non-None fields as request params, booleans lowercased."""
+ params: Dict = {}
+ for key, value in asdict(self).items():
+ if value is None:
+ continue
+ params[key] = str(value).lower() if isinstance(value, bool) else value
+ return params
+
+ @classmethod
+ def field_names(cls) -> set:
+ return set(cls.__dataclass_fields__.keys())
+
+
+QUICK_SEARCH_PATH = "/api/search/quick"
+DEEP_SEARCH_PATH = "/api/search"
diff --git a/litellm/llms/apiserpent/search/transformation.py b/litellm/llms/apiserpent/search/transformation.py
new file mode 100644
index 00000000000..1eb7d34c875
--- /dev/null
+++ b/litellm/llms/apiserpent/search/transformation.py
@@ -0,0 +1,182 @@
+"""
+Calls APISerpent's search endpoints to search Google, Bing, Yahoo, or DuckDuckGo.
+
+Two endpoints under one provider, selected via the ``deep`` boolean param:
+- ``deep=False`` (default) -> quick search (/api/search/quick)
+- ``deep=True`` -> deep search (/api/search)
+
+APISerpent API Reference: https://apiserpent.com/docs
+"""
+
+from typing import Dict, List, Literal, Optional, Union, cast
+from urllib.parse import urlencode
+
+import httpx
+
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.llms.apiserpent.search.defaults import (
+ DEEP_SEARCH_PATH,
+ NUM_MAX,
+ NUM_MIN,
+ NUM_MIN_DEEP,
+ QUICK_SEARCH_PATH,
+ APISerpentSearchParams,
+)
+from litellm.llms.base_llm.search.transformation import (
+ BaseSearchConfig,
+ SearchResponse,
+ SearchResult,
+)
+from litellm.secret_managers.main import get_secret_str
+
+DEEP_SEARCH_PARAM = "deep"
+APISERPENT_BASE = "https://apiserpent.com"
+APISERPENT_PARAMS_KEY = "_apiserpent_params"
+
+
+class APISerpentSearchConfig(BaseSearchConfig):
+ @staticmethod
+ def ui_friendly_name() -> str:
+ return "APISerpent"
+
+ def get_http_method(self) -> Literal["GET", "POST"]:
+ return "GET"
+
+ @staticmethod
+ def _is_deep_search(optional_params: dict) -> bool:
+ return bool(optional_params.get(DEEP_SEARCH_PARAM))
+
+ def validate_environment(
+ self,
+ headers: Dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ **kwargs,
+ ) -> Dict:
+ api_key = api_key or get_secret_str("APISERPENT_API_KEY")
+ if not api_key:
+ raise ValueError(
+ "APISERPENT_API_KEY is not set. Set `APISERPENT_API_KEY` environment variable."
+ )
+ headers["X-API-Key"] = api_key
+ headers["Content-Type"] = "application/json"
+ return headers
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ optional_params: dict,
+ data: Optional[Union[Dict, List[Dict]]] = None,
+ **kwargs,
+ ) -> str:
+ """
+ Build the search URL. APISerpent uses GET, so the transformed request is
+ serialized into the query string. The endpoint path (quick vs deep) is
+ always applied; an ``api_base`` / ``APISERPENT_API_BASE`` override only
+ changes the host. The ``endswith`` guard keeps this idempotent, since the
+ handler re-invokes this method with the already-resolved URL as api_base.
+ """
+ base = (
+ api_base or get_secret_str("APISERPENT_API_BASE") or APISERPENT_BASE
+ ).rstrip("/")
+ path = (
+ DEEP_SEARCH_PATH
+ if self._is_deep_search(optional_params)
+ else QUICK_SEARCH_PATH
+ )
+ if not base.endswith(path):
+ base = f"{base}{path}"
+
+ if data and isinstance(data, dict) and APISERPENT_PARAMS_KEY in data:
+ query_string = urlencode(data[APISERPENT_PARAMS_KEY], doseq=True)
+ return f"{base}?{query_string}"
+
+ return base
+
+ def transform_search_request(
+ self,
+ query: Union[str, List[str]],
+ optional_params: dict,
+ **kwargs,
+ ) -> Dict:
+ """
+ Transform a unified search request into APISerpent query params.
+
+ Unified spec mappings:
+ - query -> q
+ - max_results -> num (clamped to the endpoint's valid range)
+ - country -> country (lowercased)
+ - search_domain_filter -> site: clauses appended to q
+
+ All other APISerpent params (engine, language, freshness, safe, pages,
+ format, pixel_position) pass through, defaulting via APISerpentSearchParams.
+ """
+ if isinstance(query, list):
+ query = " ".join(query)
+
+ is_deep = self._is_deep_search(optional_params)
+
+ overrides: Dict = {}
+ if "max_results" in optional_params:
+ num_min = NUM_MIN_DEEP if is_deep else NUM_MIN
+ overrides["num"] = max(
+ num_min, min(optional_params["max_results"], NUM_MAX)
+ )
+ if "country" in optional_params:
+ overrides["country"] = cast(str, optional_params["country"]).lower()
+
+ for param, value in optional_params.items():
+ if param in APISerpentSearchParams.field_names() and param not in overrides:
+ overrides[param] = value
+
+ params = {**APISerpentSearchParams(**overrides).to_request_params(), "q": query}
+
+ if "search_domain_filter" in optional_params:
+ domains = optional_params["search_domain_filter"]
+ if isinstance(domains, list) and len(domains) > 0:
+ params["q"] = self._append_domain_filters(str(params["q"]), domains)
+
+ return {APISERPENT_PARAMS_KEY: params}
+
+ @staticmethod
+ def _append_domain_filters(query: str, domains: List[str]) -> str:
+ domain_clauses = " OR ".join(f"site:{domain}" for domain in domains)
+ return f"({query}) ({domain_clauses})"
+
+ def transform_search_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: Optional[LiteLLMLoggingObj],
+ **kwargs,
+ ) -> SearchResponse:
+ """
+ Transform APISerpent response to the unified SearchResponse format.
+
+ Full format nests results under ``results.organic[]``; simple format
+ returns a flat ``results[]`` array. Both expose title/url/snippet.
+ """
+ response_json = raw_response.json()
+
+ raw_results = response_json.get("results") or {}
+ organic = (
+ raw_results.get("organic", [])
+ if isinstance(raw_results, dict)
+ else raw_results
+ )
+
+ results: List[SearchResult] = []
+ for result in organic:
+ results.append(
+ SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=result.get("snippet", ""),
+ date=result.get("date"),
+ last_updated=None,
+ )
+ )
+
+ return SearchResponse(
+ results=results,
+ object="search",
+ )
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 941fe59e825..8b3add5398b 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -2026,6 +2026,7 @@ class BaseLLMHTTPHandler:
litellm_params={
"preset_cache_key": None,
"stream_response": {},
+ "model_info": kwargs.get("model_info"),
**anthropic_messages_optional_request_params,
},
custom_llm_provider=custom_llm_provider,
diff --git a/litellm/llms/github_copilot/chat/transformation.py b/litellm/llms/github_copilot/chat/transformation.py
index 6651a3c60b7..72dacb59f8a 100644
--- a/litellm/llms/github_copilot/chat/transformation.py
+++ b/litellm/llms/github_copilot/chat/transformation.py
@@ -1,10 +1,15 @@
-from typing import List, Optional, Tuple
+import json
+from typing import Any, List, Optional, Tuple
import os
+import httpx
+
from litellm.exceptions import AuthenticationError
+from litellm.llms.anthropic.chat.transformation import AnthropicConfig
from litellm.llms.openai.openai import OpenAIConfig
-from litellm.types.llms.openai import AllMessageValues
+from litellm.types.llms.openai import AllMessageValues, ChatCompletionToolCallChunk
+from litellm.types.utils import ModelResponse
from ..authenticator import Authenticator
from ..common_utils import (
@@ -164,3 +169,147 @@ class GithubCopilotConfig(OpenAIConfig):
if content_type == "image_url":
return True
return False
+
+ @staticmethod
+ def _parse_anthropic_native_content(
+ content_blocks: List[Any],
+ ) -> Tuple[str, List[ChatCompletionToolCallChunk], Optional[List[Any]]]:
+ """
+ Parse Anthropic-native content blocks into OpenAI-compatible fields.
+
+ Concatenates all text blocks, extracts tool_use blocks as tool_calls, and
+ preserves thinking blocks when present.
+ """
+ (
+ text_content,
+ _citations,
+ thinking_blocks,
+ _reasoning_content,
+ tool_calls,
+ _web_search_results,
+ _tool_results,
+ _compaction_blocks,
+ ) = AnthropicConfig().extract_response_content(
+ completion_response={"content": content_blocks}
+ )
+ return text_content, tool_calls, thinking_blocks
+
+ def transform_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: "ModelResponse",
+ logging_obj: Any,
+ request_data: dict,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ encoding: Any,
+ api_key: Optional[str] = None,
+ json_mode: Optional[bool] = None,
+ ) -> "ModelResponse":
+ """
+ Handle newer Copilot models (e.g. claude-opus-4.7, claude-opus-4.8) that
+ return Anthropic-native format responses without a `choices` array.
+
+ Synthesizes the missing `choices` from Anthropic-native fields, then
+ delegates to the parent so all standard post-processing applies.
+
+ See: https://github.com/BerriAI/litellm/issues/29391
+ """
+ try:
+ response_json = raw_response.json()
+ except Exception:
+ return super().transform_response(
+ model=model,
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=logging_obj,
+ request_data=request_data,
+ messages=messages,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ encoding=encoding,
+ api_key=api_key,
+ json_mode=json_mode,
+ )
+
+ if not response_json.get("choices"):
+ content = ""
+ tool_calls: List[ChatCompletionToolCallChunk] = []
+ thinking_blocks: Optional[List[Any]] = None
+ if "content" in response_json and isinstance(
+ response_json["content"], list
+ ):
+ content, tool_calls, thinking_blocks = (
+ self._parse_anthropic_native_content(response_json["content"])
+ )
+ elif isinstance(response_json.get("content"), str):
+ content = response_json["content"]
+
+ stop_reason = response_json.get("stop_reason")
+ finish_reason_map = {
+ "end_turn": "stop",
+ "max_tokens": "length",
+ "stop_sequence": "stop",
+ "tool_use": "tool_calls",
+ }
+ # Prefer tool_calls when blocks were extracted; otherwise map stop_reason.
+ if tool_calls:
+ finish_reason = "tool_calls"
+ elif stop_reason in finish_reason_map:
+ finish_reason = finish_reason_map[stop_reason]
+ elif content:
+ finish_reason = "stop"
+ else:
+ finish_reason = "length"
+
+ message: dict = {
+ "role": "assistant",
+ "content": content if content or not tool_calls else None,
+ }
+ if tool_calls:
+ message["tool_calls"] = tool_calls
+ if thinking_blocks:
+ message["thinking_blocks"] = thinking_blocks
+
+ response_json["choices"] = [
+ {
+ "index": 0,
+ "message": message,
+ "finish_reason": finish_reason,
+ }
+ ]
+
+ if "usage" in response_json:
+ usage = response_json["usage"]
+ if "input_tokens" in usage and "prompt_tokens" not in usage:
+ usage["prompt_tokens"] = usage["input_tokens"]
+ if "output_tokens" in usage and "completion_tokens" not in usage:
+ usage["completion_tokens"] = usage["output_tokens"]
+ if "total_tokens" not in usage:
+ usage["total_tokens"] = usage.get("prompt_tokens", 0) + usage.get(
+ "completion_tokens", 0
+ )
+
+ # Build a patched response so super() sees valid JSON with choices
+ patched = httpx.Response(
+ status_code=raw_response.status_code,
+ headers=raw_response.headers,
+ content=json.dumps(response_json).encode(),
+ )
+ raw_response = patched
+
+ return super().transform_response(
+ model=model,
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=logging_obj,
+ request_data=request_data,
+ messages=messages,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ encoding=encoding,
+ api_key=api_key,
+ json_mode=json_mode,
+ )
diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py
index 7325c0596a6..c06928516ef 100644
--- a/litellm/llms/xai/chat/transformation.py
+++ b/litellm/llms/xai/chat/transformation.py
@@ -9,6 +9,7 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import (
filter_value_from_dict,
strip_name_from_messages,
)
+from litellm.llms.xai.common_utils import XAIModelInfo
from litellm.secret_managers.main import get_secret_str
from litellm.types.llms.openai import AllMessageValues
from litellm.types.utils import (
@@ -35,7 +36,7 @@ class XAIChatConfig(OpenAIGPTConfig):
self, api_base: Optional[str], api_key: Optional[str]
) -> Tuple[Optional[str], Optional[str]]:
api_base = api_base or get_secret_str("XAI_API_BASE") or XAI_API_BASE # type: ignore
- dynamic_api_key = api_key or get_secret_str("XAI_API_KEY")
+ dynamic_api_key = XAIModelInfo.get_api_key(api_key)
return api_base, dynamic_api_key
def get_supported_openai_params(self, model: str) -> list:
diff --git a/litellm/llms/xai/common_utils.py b/litellm/llms/xai/common_utils.py
index df324cf3ee2..adc857894c5 100644
--- a/litellm/llms/xai/common_utils.py
+++ b/litellm/llms/xai/common_utils.py
@@ -45,8 +45,28 @@ class XAIModelInfo(BaseLLMModelInfo):
return api_base or get_secret_str("XAI_API_BASE") or "https://api.x.ai"
@staticmethod
- def get_api_key(api_key: Optional[str] = None) -> Optional[str]:
- return api_key or get_secret_str("XAI_API_KEY")
+ def get_api_key(
+ api_key: Optional[str] = None,
+ legacy_generic_before_env: bool = False,
+ ) -> Optional[str]:
+ """
+ Resolve xAI API keys while preserving endpoint-specific legacy order.
+
+ Chat uses xai_key before XAI_API_KEY without adding a generic
+ litellm.api_key fallback. Responses and realtime historically
+ preferred litellm.api_key over XAI_API_KEY, so those paths opt into
+ the legacy order with legacy_generic_before_env=True. In both modes,
+ the provider-specific litellm.xai_key takes precedence over fallbacks.
+ """
+ if legacy_generic_before_env:
+ return (
+ api_key
+ or litellm.xai_key
+ or litellm.api_key
+ or get_secret_str("XAI_API_KEY")
+ )
+
+ return api_key or litellm.xai_key or get_secret_str("XAI_API_KEY")
@staticmethod
def get_base_model(model: str) -> Optional[str]:
@@ -59,7 +79,7 @@ class XAIModelInfo(BaseLLMModelInfo):
api_key = self.get_api_key(api_key)
if api_base is None or api_key is None:
raise ValueError(
- "XAI_API_BASE or XAI_API_KEY is not set. Please set the environment variable, to query XAI's `/models` endpoint."
+ "XAI API base or key is not set. Set XAI_API_BASE and provide an xAI API key via api_key, litellm.xai_key, or XAI_API_KEY."
)
response = litellm.module_level_client.get(
url=f"{api_base}/v1/models",
diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py
index 23aee3a1202..55805ddaede 100644
--- a/litellm/llms/xai/responses/transformation.py
+++ b/litellm/llms/xai/responses/transformation.py
@@ -4,6 +4,7 @@ import litellm
from litellm._logging import verbose_logger
from litellm.constants import XAI_API_BASE
from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig
+from litellm.llms.xai.common_utils import XAIModelInfo
from litellm.secret_managers.main import get_secret_str
from litellm.types.llms.openai import ResponsesAPIOptionalRequestParams
from litellm.types.llms.xai import XAIWebSearchTool, XAIXSearchTool
@@ -212,16 +213,17 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
"""
Validate environment and set up headers for XAI API.
- Uses XAI_API_KEY from environment or litellm_params.
+ Uses the shared xAI key resolver with Responses API legacy precedence.
"""
litellm_params = litellm_params or GenericLiteLLMParams()
- api_key = (
- litellm_params.api_key or litellm.api_key or get_secret_str("XAI_API_KEY")
+ api_key = XAIModelInfo.get_api_key(
+ litellm_params.api_key, legacy_generic_before_env=True
)
if not api_key:
raise ValueError(
- "XAI API key is required. Set XAI_API_KEY environment variable or pass api_key parameter."
+ "XAI API key is required. Set api_key, litellm.xai_key, "
+ "litellm.api_key, or XAI_API_KEY."
)
headers.update(
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index 0ddfec5f63c..a604aafa540 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -13387,6 +13387,22 @@
"notes": "Serper Google Search API. Pricing: $1.00/1k queries (Starter), $0.75/1k (Standard), $0.50/1k (Scale), $0.30/1k (Ultimate)."
}
},
+ "apiserpent/search": {
+ "input_cost_per_query": 0.0006,
+ "litellm_provider": "apiserpent",
+ "mode": "search",
+ "metadata": {
+ "notes": "APISerpent quick search (/api/search/quick), multi-engine (Google, Bing, Yahoo, DuckDuckGo). Pricing: $0.60/1k searches."
+ }
+ },
+ "apiserpent/deep_search": {
+ "input_cost_per_query": 0.0006,
+ "litellm_provider": "apiserpent",
+ "mode": "search",
+ "metadata": {
+ "notes": "APISerpent deep search (/api/search), multi-engine (Google, Bing, Yahoo, DuckDuckGo). Pricing: $0.60/1k searches."
+ }
+ },
"elevenlabs/scribe_v1": {
"input_cost_per_second": 6.11e-05,
"litellm_provider": "elevenlabs",
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 38976f79aa3..917239e0358 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -491,6 +491,20 @@ async def check_tools_allowlist(
)
+# Read-only discovery routes that incur no spend. Kept narrower than info_routes so an exhausted
+# budget cannot reach side-effectful routes like /health/services (Slack/email/webhook). See #27923.
+MODEL_DISCOVERY_ROUTES = frozenset(
+ {
+ "/v1/models",
+ "/models",
+ "/model/info",
+ "/v1/model/info",
+ "/v2/model/info",
+ "/model_group/info",
+ }
+)
+
+
async def common_checks( # noqa: PLR0915
request_body: dict,
team_object: Optional[LiteLLM_TeamTable],
@@ -534,6 +548,9 @@ async def common_checks( # noqa: PLR0915
request_query_params=_safe_get_request_query_params(request=request),
)
+ if route in MODEL_DISCOVERY_ROUTES:
+ skip_budget_checks = True
+
# 1. If team is blocked
if team_object is not None and team_object.blocked is True:
raise Exception(
diff --git a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
index 37be832d350..27fa685eaac 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
@@ -799,6 +799,11 @@ class ToolPermissionGuardrail(CustomGuardrail):
verbose_proxy_logger.debug(
"Tool Permission Guardrail: No tool uses found"
)
+ mock_response = MockResponseIterator(
+ model_response=assembled_model_response
+ )
+ async for chunk in mock_response:
+ yield chunk
return
verbose_proxy_logger.debug(
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.py
index 6c57fd95b34..ca5e0473659 100644
--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py
+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py
@@ -1780,6 +1780,9 @@ async def ui_view_spend_logs( # noqa: PLR0915
default=None,
description="Filter logs by model ID (litellm model deployment id)",
),
+ model_group: Optional[str] = fastapi.Query(
+ default=None, description="Filter logs by model group"
+ ),
key_alias: Optional[str] = fastapi.Query(
default=None, description="Filter logs by key alias"
),
@@ -1914,6 +1917,9 @@ async def ui_view_spend_logs( # noqa: PLR0915
if model_id is not None:
where_conditions["model_id"] = model_id
+ if model_group is not None:
+ where_conditions["model_group"] = model_group
+
# Build metadata filters
metadata_filters = []
if key_alias is not None:
@@ -2037,6 +2043,7 @@ async def ui_view_spend_logs( # noqa: PLR0915
("request_id", "request_id"),
("model", "model"),
("model_id", "model_id"),
+ ("model_group", "model_group"),
("end_user", "end_user"),
]:
val = where_conditions.get(wc_key)
diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.py
index 842e5ea4859..95d6f7c3e03 100644
--- a/litellm/realtime_api/main.py
+++ b/litellm/realtime_api/main.py
@@ -8,6 +8,7 @@ from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, request
from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider
from litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfig
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
+from litellm.llms.xai.common_utils import XAIModelInfo
from litellm.secret_managers.main import get_secret_str
from litellm.types.realtime import (
RealtimeClientSecretRequest,
@@ -383,7 +384,9 @@ async def _arealtime( # noqa: PLR0915
or "https://api.x.ai/v1"
)
# set API KEY
- api_key = dynamic_api_key or litellm.api_key or get_secret_str("XAI_API_KEY")
+ api_key = XAIModelInfo.get_api_key(
+ dynamic_api_key, legacy_generic_before_env=True
+ )
await xai_realtime.async_realtime(
model=model,
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index a0d8f78b3b3..d208eb29ac1 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -3406,6 +3406,7 @@ class SearchProviders(str, Enum):
DUCKDUCKGO = "duckduckgo"
SEARCHAPI = "searchapi"
SERPER = "serper"
+ APISERPENT = "apiserpent"
# Create a set of all search provider values for quick lookup
diff --git a/litellm/utils.py b/litellm/utils.py
index 0a2bf532281..68982ea2b35 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -3374,12 +3374,17 @@ def get_optional_params_embeddings( # noqa: PLR0915
and "dimensions" in non_default_params.keys()
and "dimensions" not in (allowed_openai_params or [])
):
- raise UnsupportedParamsError(
- status_code=500,
- message="Setting dimensions is not supported for OpenAI `text-embedding-3` and later models. To drop it from the call, set `litellm.drop_params = True`.",
- )
- else:
- optional_params = non_default_params
+ # Honor drop_params (per-call) and litellm.drop_params (global) the same
+ # way `_check_valid_arg` does above. The raised error message itself
+ # tells users to set `drop_params=True`, so respect it here.
+ if litellm.drop_params is True or drop_params is True:
+ non_default_params.pop("dimensions", None)
+ else:
+ raise UnsupportedParamsError(
+ status_code=500,
+ message="Setting dimensions is not supported for OpenAI `text-embedding-3` and later models. To drop it from the call, set `litellm.drop_params = True`.",
+ )
+ optional_params = non_default_params
elif custom_llm_provider == "triton":
supported_params = get_supported_openai_params(
model=model,
@@ -9444,6 +9449,9 @@ class ProviderConfigManager:
"""
Get Search configuration for a given provider.
"""
+ from litellm.llms.apiserpent.search.transformation import (
+ APISerpentSearchConfig,
+ )
from litellm.llms.brave.search.transformation import BraveSearchConfig
from litellm.llms.dataforseo.search.transformation import DataForSEOSearchConfig
from litellm.llms.duckduckgo.search.transformation import DuckDuckGoSearchConfig
@@ -9474,6 +9482,7 @@ class ProviderConfigManager:
SearchProviders.DUCKDUCKGO: DuckDuckGoSearchConfig,
SearchProviders.SEARCHAPI: SearchAPIConfig,
SearchProviders.SERPER: SerperSearchConfig,
+ SearchProviders.APISERPENT: APISerpentSearchConfig,
}
config_class = PROVIDER_TO_CONFIG_MAP.get(provider, None)
if config_class is None:
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index b2698ab3a82..b253235ec2a 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -13387,6 +13387,22 @@
"notes": "Serper Google Search API. Pricing: $1.00/1k queries (Starter), $0.75/1k (Standard), $0.50/1k (Scale), $0.30/1k (Ultimate)."
}
},
+ "apiserpent/search": {
+ "input_cost_per_query": 0.0006,
+ "litellm_provider": "apiserpent",
+ "mode": "search",
+ "metadata": {
+ "notes": "APISerpent quick search (/api/search/quick), multi-engine (Google, Bing, Yahoo, DuckDuckGo). Pricing: $0.60/1k searches."
+ }
+ },
+ "apiserpent/deep_search": {
+ "input_cost_per_query": 0.0006,
+ "litellm_provider": "apiserpent",
+ "mode": "search",
+ "metadata": {
+ "notes": "APISerpent deep search (/api/search), multi-engine (Google, Bing, Yahoo, DuckDuckGo). Pricing: $0.60/1k searches."
+ }
+ },
"elevenlabs/scribe_v1": {
"input_cost_per_second": 6.11e-05,
"litellm_provider": "elevenlabs",
diff --git a/provider_endpoints_support.json b/provider_endpoints_support.json
index abd03e1c957..1e8357a8137 100644
--- a/provider_endpoints_support.json
+++ b/provider_endpoints_support.json
@@ -2172,6 +2172,13 @@
"search": true
}
},
+ "apiserpent": {
+ "display_name": "APISerpent (`apiserpent`)",
+ "url": "https://docs.litellm.ai/docs/search/apiserpent",
+ "endpoints": {
+ "search": true
+ }
+ },
"triton": {
"display_name": "Triton (`triton`)",
"url": "https://docs.litellm.ai/docs/providers/triton-inference-server",
diff --git a/tests/code_coverage_tests/enforce_llms_folder_style.py b/tests/code_coverage_tests/enforce_llms_folder_style.py
index 370ff13e029..43ab81b6c60 100644
--- a/tests/code_coverage_tests/enforce_llms_folder_style.py
+++ b/tests/code_coverage_tests/enforce_llms_folder_style.py
@@ -19,6 +19,7 @@ SEARCH_PROVIDERS = [
"duckduckgo",
"searchapi",
"serper",
+ "apiserpent",
]
ALLOWED_FILES_IN_LLMS_FOLDER = [
diff --git a/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py b/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py
index 66a1a4d74af..01bcb1a247a 100644
--- a/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py
+++ b/tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py
@@ -1414,10 +1414,11 @@ def test_error_message_includes_function_args():
Test that when an exception occurs, the error message includes
the function arguments for debugging (deferred locals() - Opt 2).
"""
- # Pass a response_object that will cause an error inside the try block
- # (e.g. choices is not iterable)
+ # Pass a response_object whose choices survive the missing-choices guard
+ # but raise inside the conversion loop (the choice lacks a "message" key),
+ # so the generic debugging handler builds the received_args message.
response_object = {
- "choices": None, # will fail the assert
+ "choices": [{"index": 0}],
}
with pytest.raises(Exception) as exc_info:
@@ -1597,3 +1598,843 @@ def test_convert_to_model_response_object_with_null_top_logprobs():
for token_logprob in choice.logprobs.content:
assert token_logprob.top_logprobs == []
assert isinstance(token_logprob.top_logprobs, list)
+
+
+class TestMissingChoicesGuard:
+ """
+ Tests for the defense-in-depth guard that raises APIError when a provider
+ returns a response with no 'choices' field.
+
+ See: https://github.com/BerriAI/litellm/issues/29391
+ """
+
+ def test_convert_to_model_response_object_no_choices_raises_api_error(self):
+ """Missing choices in non-streaming path raises APIError, not IndexError."""
+ from litellm.exceptions import APIError
+
+ response_object = {
+ "id": "msg_123",
+ "model": "some-model",
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ }
+
+ with pytest.raises(APIError) as exc_info:
+ convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ )
+
+ assert "no 'choices'" in exc_info.value.message
+
+ def test_convert_to_model_response_object_empty_choices_raises_api_error(self):
+ """Empty choices list raises APIError."""
+ from litellm.exceptions import APIError
+
+ response_object = {
+ "id": "msg_123",
+ "model": "some-model",
+ "choices": [],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ }
+
+ with pytest.raises(APIError) as exc_info:
+ convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ )
+
+ assert "no 'choices'" in exc_info.value.message
+
+ def test_convert_to_model_response_object_null_choices_raises_api_error(self):
+ """choices=None raises APIError."""
+ from litellm.exceptions import APIError
+
+ response_object = {
+ "id": "msg_123",
+ "model": "some-model",
+ "choices": None,
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ }
+
+ with pytest.raises(APIError) as exc_info:
+ convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ )
+
+ assert "no 'choices'" in exc_info.value.message
+
+ def test_convert_to_streaming_response_no_choices_raises_api_error(self):
+ """Missing choices in streaming cache-hit path raises APIError."""
+ from litellm.exceptions import APIError
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response,
+ )
+
+ response_object = {
+ "id": "msg_123",
+ "model": "some-model",
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ }
+
+ with pytest.raises(APIError) as exc_info:
+ # convert_to_streaming_response is a generator, must consume it
+ list(convert_to_streaming_response(response_object=response_object))
+
+ assert "no 'choices'" in exc_info.value.message
+
+ def test_convert_to_model_response_object_stream_true_no_choices_raises_api_error(self):
+ """Missing choices via stream=True path raises APIError when generator is consumed."""
+ from litellm.exceptions import APIError
+
+ response_object = {
+ "id": "msg_123",
+ "model": "some-model",
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ }
+
+ with pytest.raises(APIError) as exc_info:
+ list(
+ convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ stream=True,
+ )
+ )
+
+ assert "no 'choices'" in exc_info.value.message
+
+ def test_convert_to_streaming_response_async_no_choices_raises_api_error(self):
+ """Missing choices in async streaming path raises APIError."""
+ import asyncio
+
+ from litellm.exceptions import APIError
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response_async,
+ )
+
+ response_object = {
+ "id": "msg_123",
+ "model": "some-model",
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ }
+
+ async def consume():
+ chunks = []
+ async for chunk in convert_to_streaming_response_async(
+ response_object=response_object
+ ):
+ chunks.append(chunk)
+ return chunks
+
+ with pytest.raises(APIError) as exc_info:
+ asyncio.run(consume())
+
+ assert "no 'choices'" in exc_info.value.message
+
+ def test_error_message_includes_response_keys(self):
+ """The error message should include the keys present in the response for debugging."""
+ from litellm.exceptions import APIError
+
+ response_object = {
+ "id": "msg_123",
+ "model": "some-model",
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ "copilot_usage": {"total_nano_aiu": 9500000},
+ }
+
+ with pytest.raises(APIError) as exc_info:
+ convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ )
+
+ assert "copilot_usage" in exc_info.value.message
+
+
+class TestNormalizeImagesForMessage:
+ def test_none_returns_none(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _normalize_images_for_message,
+ )
+
+ assert _normalize_images_for_message(None) is None
+
+ def test_empty_list_returns_empty(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _normalize_images_for_message,
+ )
+
+ assert _normalize_images_for_message([]) == []
+
+ def test_adds_index_when_missing(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _normalize_images_for_message,
+ )
+
+ images = [{"url": "http://a.png"}, {"url": "http://b.png"}]
+ result = _normalize_images_for_message(images)
+ assert result[0]["index"] == 0
+ assert result[1]["index"] == 1
+ assert result[0]["url"] == "http://a.png"
+
+ def test_preserves_existing_index(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _normalize_images_for_message,
+ )
+
+ images = [{"url": "http://a.png", "index": 5}]
+ result = _normalize_images_for_message(images)
+ assert result[0]["index"] == 5
+
+
+class TestSafeConvertCreatedField:
+ def test_none_returns_current_time(self):
+ import time
+
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _safe_convert_created_field,
+ )
+
+ result = _safe_convert_created_field(None)
+ assert abs(result - int(time.time())) <= 1
+
+ def test_int_passthrough(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _safe_convert_created_field,
+ )
+
+ assert _safe_convert_created_field(1700000000) == 1700000000
+
+ def test_float_truncated(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _safe_convert_created_field,
+ )
+
+ assert _safe_convert_created_field(1700000000.999) == 1700000000
+
+ def test_string_converted(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _safe_convert_created_field,
+ )
+
+ assert _safe_convert_created_field("1700000000.5") == 1700000000
+
+ def test_invalid_string_returns_current_time(self):
+ import time
+
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _safe_convert_created_field,
+ )
+
+ result = _safe_convert_created_field("not-a-number")
+ assert abs(result - int(time.time())) <= 1
+
+
+class TestConvertToStreamingResponse:
+ def test_none_raises(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response,
+ )
+
+ with pytest.raises(Exception, match="Error in response object format"):
+ list(convert_to_streaming_response(response_object=None))
+
+ def test_happy_path_basic(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response,
+ )
+
+ response_object = {
+ "id": "chatcmpl-123",
+ "model": "gpt-4",
+ "created": 1700000000,
+ "system_fingerprint": "fp_abc",
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {"content": "Hello!", "role": "assistant"},
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 5,
+ "completion_tokens": 2,
+ "total_tokens": 7,
+ },
+ }
+
+ chunks = list(convert_to_streaming_response(response_object=response_object))
+ assert len(chunks) == 1
+ chunk = chunks[0]
+ assert chunk.id == "chatcmpl-123"
+ assert chunk.model == "gpt-4"
+ assert chunk.created == 1700000000
+ assert chunk.system_fingerprint == "fp_abc"
+ assert chunk.choices[0].delta.content == "Hello!"
+ assert chunk.choices[0].delta.role == "assistant"
+ assert chunk.choices[0].finish_reason == "stop"
+ assert chunk.usage.prompt_tokens == 5
+ assert chunk.usage.completion_tokens == 2
+
+ def test_finish_details_fallback(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response,
+ )
+
+ response_object = {
+ "choices": [
+ {
+ "finish_reason": None,
+ "finish_details": "length",
+ "message": {"content": "Hi", "role": "assistant"},
+ }
+ ],
+ }
+
+ chunks = list(convert_to_streaming_response(response_object=response_object))
+ assert chunks[0].choices[0].finish_reason == "length"
+
+ def test_tool_calls_in_streaming(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response_async,
+ )
+ import asyncio
+
+ response_object = {
+ "choices": [
+ {
+ "finish_reason": "tool_calls",
+ "index": 0,
+ "message": {
+ "content": None,
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "arguments": '{"city": "NYC"}',
+ },
+ }
+ ],
+ },
+ }
+ ],
+ }
+
+ async def run():
+ chunks = []
+ async for chunk in convert_to_streaming_response_async(
+ response_object=response_object
+ ):
+ chunks.append(chunk)
+ return chunks
+
+ chunks = asyncio.run(run())
+ assert len(chunks) == 1
+ assert chunks[0].choices[0].delta.tool_calls[0].id == "call_1"
+ assert chunks[0].choices[0].delta.tool_calls[0].function.name == "get_weather"
+
+
+class TestConvertToStreamingResponseAsync:
+ def test_none_raises(self):
+ import asyncio
+
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response_async,
+ )
+
+ async def run():
+ async for _ in convert_to_streaming_response_async(response_object=None):
+ pass
+
+ with pytest.raises(Exception, match="Error in response object format"):
+ asyncio.run(run())
+
+ def test_happy_path(self):
+ import asyncio
+
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_to_streaming_response_async,
+ )
+
+ response_object = {
+ "id": "msg_async_1",
+ "model": "claude-3",
+ "created": 1700000000,
+ "system_fingerprint": "fp_xyz",
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {"content": "Hi there", "role": "assistant"},
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 3,
+ "completion_tokens": 2,
+ "total_tokens": 5,
+ },
+ }
+
+ async def run():
+ chunks = []
+ async for chunk in convert_to_streaming_response_async(
+ response_object=response_object
+ ):
+ chunks.append(chunk)
+ return chunks
+
+ chunks = asyncio.run(run())
+ assert len(chunks) == 1
+ assert chunks[0].id == "msg_async_1"
+ assert chunks[0].model == "claude-3"
+ assert chunks[0].choices[0].delta.content == "Hi there"
+ assert chunks[0].usage.prompt_tokens == 3
+
+
+class TestHandleInvalidParallelToolCalls:
+ def test_none_input(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _handle_invalid_parallel_tool_calls,
+ )
+
+ assert _handle_invalid_parallel_tool_calls(None) is None
+
+ def test_normal_tool_calls_unchanged(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _handle_invalid_parallel_tool_calls,
+ )
+ from litellm.types.utils import ChatCompletionMessageToolCall, Function
+
+ tool_calls = [
+ ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(name="get_weather", arguments='{"city": "NYC"}'),
+ )
+ ]
+ result = _handle_invalid_parallel_tool_calls(tool_calls)
+ assert len(result) == 1
+ assert result[0].function.name == "get_weather"
+
+ def test_multi_tool_use_parallel_expanded(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _handle_invalid_parallel_tool_calls,
+ )
+ from litellm.types.utils import ChatCompletionMessageToolCall, Function
+
+ tool_calls = [
+ ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(
+ name="multi_tool_use.parallel",
+ arguments=json.dumps(
+ {
+ "tool_uses": [
+ {
+ "recipient_name": "functions.get_weather",
+ "parameters": {"city": "NYC"},
+ },
+ {
+ "recipient_name": "functions.get_time",
+ "parameters": {"tz": "EST"},
+ },
+ ]
+ }
+ ),
+ ),
+ )
+ ]
+ result = _handle_invalid_parallel_tool_calls(tool_calls)
+ assert len(result) == 2
+ assert result[0].function.name == "get_weather"
+ assert result[0].id == "call_1_0"
+ assert json.loads(result[0].function.arguments) == {"city": "NYC"}
+ assert result[1].function.name == "get_time"
+ assert result[1].id == "call_1_1"
+
+ def test_invalid_json_returns_original(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _handle_invalid_parallel_tool_calls,
+ )
+ from litellm.types.utils import ChatCompletionMessageToolCall, Function
+
+ tool_calls = [
+ ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(name="some_func", arguments="not valid json{{{"),
+ )
+ ]
+ result = _handle_invalid_parallel_tool_calls(tool_calls)
+ assert len(result) == 1
+ assert result[0].id == "call_1"
+
+
+class TestShouldConvertToolCallToJsonMode:
+ def test_returns_true_when_conditions_met(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _should_convert_tool_call_to_json_mode,
+ )
+ from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+
+ tool_calls = [{"function": {"name": RESPONSE_FORMAT_TOOL_NAME}}]
+ assert (
+ _should_convert_tool_call_to_json_mode(
+ tool_calls=tool_calls, convert_tool_call_to_json_mode=True
+ )
+ is True
+ )
+
+ def test_returns_false_when_flag_off(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _should_convert_tool_call_to_json_mode,
+ )
+ from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+
+ tool_calls = [{"function": {"name": RESPONSE_FORMAT_TOOL_NAME}}]
+ assert (
+ _should_convert_tool_call_to_json_mode(
+ tool_calls=tool_calls, convert_tool_call_to_json_mode=False
+ )
+ is False
+ )
+
+ def test_returns_false_when_wrong_tool_name(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _should_convert_tool_call_to_json_mode,
+ )
+
+ tool_calls = [{"function": {"name": "some_other_tool"}}]
+ assert (
+ _should_convert_tool_call_to_json_mode(
+ tool_calls=tool_calls, convert_tool_call_to_json_mode=True
+ )
+ is False
+ )
+
+ def test_returns_false_when_multiple_tool_calls(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _should_convert_tool_call_to_json_mode,
+ )
+ from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+
+ tool_calls = [
+ {"function": {"name": RESPONSE_FORMAT_TOOL_NAME}},
+ {"function": {"name": "other"}},
+ ]
+ assert (
+ _should_convert_tool_call_to_json_mode(
+ tool_calls=tool_calls, convert_tool_call_to_json_mode=True
+ )
+ is False
+ )
+
+ def test_returns_false_when_none(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _should_convert_tool_call_to_json_mode,
+ )
+
+ assert (
+ _should_convert_tool_call_to_json_mode(
+ tool_calls=None, convert_tool_call_to_json_mode=True
+ )
+ is False
+ )
+
+
+class TestConvertToolCallToJsonMode:
+ def test_converts_when_should(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_tool_call_to_json_mode as convert_fn,
+ )
+ from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+ from litellm.types.utils import ChatCompletionMessageToolCall, Function
+
+ tool_calls = [
+ ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(
+ name=RESPONSE_FORMAT_TOOL_NAME,
+ arguments='{"key": "value"}',
+ ),
+ )
+ ]
+ message, finish_reason = convert_fn(
+ tool_calls=tool_calls, convert_tool_call_to_json_mode=True
+ )
+ assert message is not None
+ assert message.content == '{"key": "value"}'
+ assert finish_reason == "stop"
+
+ def test_no_conversion_when_flag_false(self):
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ convert_tool_call_to_json_mode as convert_fn,
+ )
+ from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+ from litellm.types.utils import ChatCompletionMessageToolCall, Function
+
+ tool_calls = [
+ ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(
+ name=RESPONSE_FORMAT_TOOL_NAME,
+ arguments='{"key": "value"}',
+ ),
+ )
+ ]
+ message, finish_reason = convert_fn(
+ tool_calls=tool_calls, convert_tool_call_to_json_mode=False
+ )
+ assert message is None
+ assert finish_reason is None
+
+
+class TestConvertToModelResponseObjectEmbedding:
+ def test_basic_embedding_response(self):
+ from litellm.types.utils import EmbeddingResponse
+
+ response_object = {
+ "model": "text-embedding-ada-002",
+ "object": "list",
+ "data": [{"embedding": [0.1, 0.2, 0.3], "index": 0}],
+ "usage": {
+ "prompt_tokens": 5,
+ "completion_tokens": 0,
+ "total_tokens": 5,
+ },
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=EmbeddingResponse(),
+ response_type="embedding",
+ )
+ assert result.model == "text-embedding-ada-002"
+ assert result.object == "list"
+ assert result.data == [{"embedding": [0.1, 0.2, 0.3], "index": 0}]
+ assert result.usage.prompt_tokens == 5
+
+
+class TestConvertToModelResponseObjectAudioTranscription:
+ def test_basic_transcription(self):
+ from litellm.types.utils import TranscriptionResponse
+
+ response_object = {
+ "text": "Hello world",
+ "language": "en",
+ "duration": 1.5,
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=TranscriptionResponse(),
+ response_type="audio_transcription",
+ )
+ assert result.text == "Hello world"
+ assert result.language == "en"
+ assert result.duration == 1.5
+
+ def test_transcription_with_duration_usage(self):
+ from litellm.types.utils import TranscriptionResponse
+
+ response_object = {
+ "text": "Hello",
+ "usage": {"type": "duration", "seconds": 3.0},
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=TranscriptionResponse(),
+ response_type="audio_transcription",
+ )
+ assert result.text == "Hello"
+ assert result.usage.seconds == 3.0
+
+ def test_transcription_with_token_usage(self):
+ from litellm.types.utils import TranscriptionResponse
+
+ response_object = {
+ "text": "Hi",
+ "usage": {
+ "type": "tokens",
+ "input_tokens": 10,
+ "output_tokens": 5,
+ "total_tokens": 15,
+ "input_token_details": {"audio_tokens": 4, "text_tokens": 6},
+ },
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=TranscriptionResponse(),
+ response_type="audio_transcription",
+ )
+ assert result.text == "Hi"
+ assert result.usage.input_tokens == 10
+ assert result.usage.output_tokens == 5
+ assert result.usage.input_token_details.audio_tokens == 4
+
+
+class TestConvertToModelResponseObjectRerank:
+ def test_basic_rerank(self):
+ from litellm.types.utils import RerankResponse
+
+ response_object = {
+ "id": "rerank-123",
+ "meta": {"model": "rerank-v1"},
+ "results": [{"index": 0, "relevance_score": 0.9}],
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=None,
+ response_type="rerank",
+ )
+ assert result.id == "rerank-123"
+ assert result.results[0]["relevance_score"] == 0.9
+
+
+class TestConvertToModelResponseObjectCompletion:
+ def test_tool_calls_finish_reason_override(self):
+ response_object = {
+ "id": "chatcmpl-1",
+ "model": "gpt-4",
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {
+ "content": None,
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "arguments": '{"city": "NYC"}',
+ },
+ }
+ ],
+ },
+ }
+ ],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15},
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ )
+ assert result.choices[0].finish_reason == "tool_calls"
+
+ def test_multiple_choices(self):
+ response_object = {
+ "id": "chatcmpl-2",
+ "model": "gpt-4",
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {"content": "Answer A", "role": "assistant"},
+ },
+ {
+ "finish_reason": "stop",
+ "index": 1,
+ "message": {"content": "Answer B", "role": "assistant"},
+ },
+ ],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15},
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ )
+ assert len(result.choices) == 2
+ assert result.choices[0].message.content == "Answer A"
+ assert result.choices[1].message.content == "Answer B"
+ assert result.choices[1].index == 1
+
+ def test_json_mode_conversion(self):
+ from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+
+ response_object = {
+ "id": "chatcmpl-3",
+ "model": "gpt-3.5-turbo",
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {
+ "content": None,
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": RESPONSE_FORMAT_TOOL_NAME,
+ "arguments": '{"result": 42}',
+ },
+ }
+ ],
+ },
+ }
+ ],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15},
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ convert_tool_call_to_json_mode=True,
+ )
+ assert result.choices[0].message.content == '{"result": 42}'
+ assert result.choices[0].finish_reason == "stop"
+
+ def test_reasoning_content_extracted(self):
+ response_object = {
+ "id": "chatcmpl-4",
+ "model": "o1",
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {
+ "content": "The answer is 4.",
+ "role": "assistant",
+ "reasoning_content": "2+2=4",
+ },
+ }
+ ],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15},
+ }
+
+ result = convert_to_model_response_object(
+ response_object=response_object,
+ model_response_object=ModelResponse(),
+ )
+ assert result.choices[0].message.content == "The answer is 4."
+ assert result.choices[0].message.reasoning_content == "2+2=4"
+
+ def test_response_none_raises(self):
+ with pytest.raises(Exception):
+ convert_to_model_response_object(
+ response_object=None,
+ model_response_object=ModelResponse(),
+ )
+
+ def test_model_response_none_raises(self):
+ with pytest.raises(Exception):
+ convert_to_model_response_object(
+ response_object={"choices": [{"message": {"content": "hi", "role": "assistant"}, "finish_reason": "stop"}]},
+ model_response_object=None,
+ )
diff --git a/tests/local_testing/test_get_optional_params_embeddings.py b/tests/local_testing/test_get_optional_params_embeddings.py
index 8a94c8f4682..667207de789 100644
--- a/tests/local_testing/test_get_optional_params_embeddings.py
+++ b/tests/local_testing/test_get_optional_params_embeddings.py
@@ -97,12 +97,69 @@ def test_openai_non_text_embedding_3_without_allowed_openai_params_raises():
"""
from litellm.exceptions import UnsupportedParamsError
- model, custom_llm_provider, _, _ = get_llm_provider(
- model="openai/nvidia/llama-3.2-nv-embedqa-1b-v2"
- )
- with pytest.raises(UnsupportedParamsError):
- get_optional_params_embeddings(
+ # ensure global drop_params is off (other tests in this file flip it on)
+ prev_drop_params = litellm.drop_params
+ litellm.drop_params = False
+ try:
+ model, custom_llm_provider, _, _ = get_llm_provider(
+ model="openai/nvidia/llama-3.2-nv-embedqa-1b-v2"
+ )
+ with pytest.raises(UnsupportedParamsError):
+ get_optional_params_embeddings(
+ model=model,
+ dimensions=1024,
+ custom_llm_provider=custom_llm_provider,
+ )
+ finally:
+ litellm.drop_params = prev_drop_params
+
+
+def test_openai_non_text_embedding_3_drop_params_per_call():
+ """
+ Regression for https://github.com/BerriAI/litellm/issues/26787
+
+ When drop_params=True is passed per-call, `dimensions` should be silently
+ stripped for a non-`text-embedding-3` OpenAI-provider model instead of
+ raising UnsupportedParamsError.
+ """
+ prev_drop_params = litellm.drop_params
+ litellm.drop_params = False # ensure only per-call flag is in effect
+ try:
+ model, custom_llm_provider, _, _ = get_llm_provider(
+ model="openai/Qwen/Qwen3-Embedding-0.6B"
+ )
+ optional_params = get_optional_params_embeddings(
+ model=model,
+ dimensions=1024,
+ custom_llm_provider=custom_llm_provider,
+ drop_params=True,
+ )
+ print(f"received optional_params: {optional_params}")
+ assert "dimensions" not in optional_params
+ finally:
+ litellm.drop_params = prev_drop_params
+
+
+def test_openai_non_text_embedding_3_drop_params_global():
+ """
+ Regression for https://github.com/BerriAI/litellm/issues/26787
+
+ When `litellm.drop_params = True` is set globally, `dimensions` should be
+ silently stripped for a non-`text-embedding-3` OpenAI-provider model
+ instead of raising UnsupportedParamsError.
+ """
+ prev_drop_params = litellm.drop_params
+ litellm.drop_params = True
+ try:
+ model, custom_llm_provider, _, _ = get_llm_provider(
+ model="openai/Qwen/Qwen3-Embedding-0.6B"
+ )
+ optional_params = get_optional_params_embeddings(
model=model,
dimensions=1024,
custom_llm_provider=custom_llm_provider,
)
+ print(f"received optional_params: {optional_params}")
+ assert "dimensions" not in optional_params
+ finally:
+ litellm.drop_params = prev_drop_params
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_advisor_integration.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_advisor_integration.py
index 74c54232ce5..414ba8f0f5c 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_advisor_integration.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_advisor_integration.py
@@ -194,3 +194,173 @@ async def test_anthropic_provider_bypasses_interceptor():
content = result.get("content", []) if isinstance(result, dict) else []
text_blocks = [b for b in content if b.get("type") == "text"]
assert any("Native anthropic" in b.get("text", "") for b in text_blocks)
+
+
+# ---------------------------------------------------------------------------
+# 4. Regression: top-level named params must be forwarded into executor sub-call
+# ---------------------------------------------------------------------------
+
+
+async def test_named_params_forwarded_into_advisor_executor_subcall():
+ """
+ Regression test: ``thinking``, ``metadata``, ``system``, ``temperature``,
+ ``stop_sequences``, ``tool_choice``, ``top_k``, ``top_p`` are bound as named
+ parameters on ``anthropic_messages``. They must be forwarded to the
+ interceptor handler so the advisor executor sub-call carries them through
+ to the underlying provider.
+
+ Without this forwarding, ``thinking={"type": "adaptive"}`` (and others)
+ are silently dropped, causing 400s on providers whose validation depends on
+ them, e.g. Vertex AI rejecting ``clear_thinking_20251015`` context_management
+ edits with: ``strategy requires thinking to be enabled or adaptive``.
+ """
+ from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
+ anthropic_messages,
+ )
+
+ captured_executor_kwargs: Dict = {}
+
+ async def mock_handler(
+ model, messages, tools, stream, max_tokens, custom_llm_provider, **kwargs
+ ):
+ # First call is the executor sub-call (returns advisor tool_use).
+ # Capture its kwargs so we can assert the forwarded params.
+ if not captured_executor_kwargs:
+ captured_executor_kwargs.update(
+ {
+ "thinking": kwargs.get("thinking"),
+ "metadata": kwargs.get("metadata"),
+ "system": kwargs.get("system"),
+ "temperature": kwargs.get("temperature"),
+ "stop_sequences": kwargs.get("stop_sequences"),
+ "tool_choice": kwargs.get("tool_choice"),
+ "top_k": kwargs.get("top_k"),
+ "top_p": kwargs.get("top_p"),
+ }
+ )
+ return _advisor_call_resp()
+ # Subsequent calls — terminate the loop.
+ if tools is None:
+ return _text_resp("Some advice.", model="claude-opus-4-6")
+ return _text_resp("Final answer.")
+
+ with patch(
+ "litellm.llms.anthropic.experimental_pass_through.messages.interceptors.advisor._call_messages_handler",
+ side_effect=mock_handler,
+ ):
+ await anthropic_messages(
+ model="openai/gpt-4o-mini",
+ messages=MESSAGES,
+ tools=[ADVISOR_TOOL],
+ stream=False,
+ max_tokens=512,
+ custom_llm_provider="openai",
+ thinking={"type": "adaptive"},
+ metadata={"caller_field": "preserve_me"},
+ system="You are a helpful assistant.",
+ temperature=0.7,
+ stop_sequences=["STOP"],
+ tool_choice={"type": "auto"},
+ top_k=40,
+ top_p=0.9,
+ )
+
+ assert captured_executor_kwargs["thinking"] == {"type": "adaptive"}, (
+ "thinking must be forwarded into executor sub-call — see "
+ "anthropic_messages.handler interceptor invocation."
+ )
+ # The advisor enriches metadata with `advisor_sub_call` / `parent_request_id`,
+ # but the original caller fields must survive into the executor sub-call.
+ assert isinstance(captured_executor_kwargs["metadata"], dict)
+ assert captured_executor_kwargs["metadata"].get("caller_field") == "preserve_me"
+ assert captured_executor_kwargs["system"] == "You are a helpful assistant."
+ assert captured_executor_kwargs["temperature"] == 0.7
+ assert captured_executor_kwargs["stop_sequences"] == ["STOP"]
+ assert captured_executor_kwargs["tool_choice"] == {"type": "auto"}
+ assert captured_executor_kwargs["top_k"] == 40
+ assert captured_executor_kwargs["top_p"] == 0.9
+
+
+# ---------------------------------------------------------------------------
+# 5. Regression: pre-request hook returning a named param must not cause
+# "got multiple values for keyword argument" at the interceptor dispatch.
+# ---------------------------------------------------------------------------
+
+
+async def test_pre_request_hook_override_does_not_collide_with_explicit_kwargs():
+ """
+ ``_execute_pre_request_hooks`` may return any subset of params. After
+ extraction those values are also propagated as named kwargs into the
+ interceptor, so the same key must not also appear in ``**kwargs`` (or the
+ splat raises ``TypeError: got multiple values for keyword argument``).
+
+ Regression for Greptile P2 on PR #27810.
+ """
+ from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
+ anthropic_messages,
+ )
+
+ captured: Dict = {}
+
+ async def mock_handler(
+ model, messages, tools, stream, max_tokens, custom_llm_provider, **kwargs
+ ):
+ if not captured:
+ captured.update(
+ {
+ "thinking": kwargs.get("thinking"),
+ "system": kwargs.get("system"),
+ "temperature": kwargs.get("temperature"),
+ }
+ )
+ return _advisor_call_resp()
+ if tools is None:
+ return _text_resp("Some advice.", model="claude-opus-4-6")
+ return _text_resp("Final answer.")
+
+ async def fake_pre_request_hooks(
+ model, messages, tools, stream, custom_llm_provider, **hook_kwargs
+ ):
+ # Simulate a CustomLogger.async_pre_request_hook that overrides several
+ # named params on its way through. Without the request_kwargs.pop()
+ # extraction in handler.py, these would collide with the explicit
+ # kwargs passed to interceptor.handle() (TypeError: got multiple
+ # values for keyword argument).
+ return {
+ "tools": tools,
+ "stream": stream,
+ "litellm_params": {"custom_llm_provider": custom_llm_provider},
+ "thinking": {"type": "enabled", "budget_tokens": 2048},
+ "system": "Hook overrode the system prompt.",
+ "temperature": 0.1,
+ }
+
+ with (
+ patch(
+ "litellm.llms.anthropic.experimental_pass_through.messages.handler._execute_pre_request_hooks",
+ side_effect=fake_pre_request_hooks,
+ ),
+ patch(
+ "litellm.llms.anthropic.experimental_pass_through.messages.interceptors.advisor._call_messages_handler",
+ side_effect=mock_handler,
+ ),
+ ):
+ # Should not raise TypeError.
+ await anthropic_messages(
+ model="openai/gpt-4o-mini",
+ messages=MESSAGES,
+ tools=[ADVISOR_TOOL],
+ stream=False,
+ max_tokens=512,
+ custom_llm_provider="openai",
+ thinking={"type": "adaptive"},
+ system="Original system prompt.",
+ temperature=0.9,
+ )
+
+ # Hook overrides win and reach the executor sub-call.
+ assert captured["thinking"] == {"type": "enabled", "budget_tokens": 2048}
+ assert captured["system"] == "Hook overrode the system prompt."
+ assert captured["temperature"] == 0.1
diff --git a/tests/test_litellm/llms/apiserpent/test_apiserpent_search.py b/tests/test_litellm/llms/apiserpent/test_apiserpent_search.py
new file mode 100644
index 00000000000..32838701949
--- /dev/null
+++ b/tests/test_litellm/llms/apiserpent/test_apiserpent_search.py
@@ -0,0 +1,293 @@
+"""
+Tests for APISerpent search API integration (quick + deep search).
+"""
+
+import os
+from unittest.mock import AsyncMock, MagicMock, patch
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+
+import litellm
+from litellm.llms.apiserpent.search.defaults import APISerpentSearchParams
+from litellm.llms.apiserpent.search.transformation import APISerpentSearchConfig
+from litellm.llms.base_llm.search.transformation import SearchResponse
+
+
+def _params(config, query, optional_params):
+ return config.transform_search_request(
+ query=query, optional_params=optional_params
+ )["_apiserpent_params"]
+
+
+class TestAPISerpentDefaults:
+ def test_defaults_applied(self):
+ params = APISerpentSearchParams().to_request_params()
+ assert params["engine"] == "google"
+ assert params["country"] == "us"
+ assert params["num"] == 10
+ assert params["format"] == "full"
+ assert "freshness" not in params
+ assert "pixel_position" not in params
+
+ def test_bool_lowercased(self):
+ params = APISerpentSearchParams(pixel_position=True).to_request_params()
+ assert params["pixel_position"] == "true"
+
+ @pytest.mark.parametrize("num", [0, 101, 500])
+ def test_num_out_of_range_raises(self, num):
+ with pytest.raises(ValueError, match="num must be between 1 and 100"):
+ APISerpentSearchParams(num=num)
+
+ @pytest.mark.parametrize("pages", [0, 11, 50])
+ def test_pages_out_of_range_raises(self, pages):
+ with pytest.raises(ValueError, match="pages must be between 1 and 10"):
+ APISerpentSearchParams(pages=pages)
+
+ def test_valid_bounds_accepted(self):
+ params = APISerpentSearchParams(num=100, pages=10).to_request_params()
+ assert params["num"] == 100
+ assert params["pages"] == 10
+
+
+class TestAPISerpentConfig:
+ def test_ui_friendly_name(self):
+ assert APISerpentSearchConfig().ui_friendly_name() == "APISerpent"
+
+ def test_get_http_method(self):
+ assert APISerpentSearchConfig().get_http_method() == "GET"
+
+ @patch("litellm.llms.apiserpent.search.transformation.get_secret_str")
+ def test_validate_environment_with_api_key(self, mock_get_secret):
+ mock_get_secret.return_value = None
+ headers = APISerpentSearchConfig().validate_environment(
+ {}, api_key="test-api-key"
+ )
+ assert headers["X-API-Key"] == "test-api-key"
+ assert headers["Content-Type"] == "application/json"
+
+ @patch("litellm.llms.apiserpent.search.transformation.get_secret_str")
+ def test_validate_environment_without_api_key(self, mock_get_secret):
+ mock_get_secret.return_value = None
+ with pytest.raises(ValueError, match="APISERPENT_API_KEY is not set"):
+ APISerpentSearchConfig().validate_environment({})
+
+ def test_transform_request_basic_applies_defaults(self):
+ params = _params(APISerpentSearchConfig(), "test query", {})
+ assert params["q"] == "test query"
+ assert params["engine"] == "google"
+ assert params["num"] == 10
+
+ def test_transform_request_list_query_joined(self):
+ assert _params(APISerpentSearchConfig(), ["foo", "bar"], {})["q"] == "foo bar"
+
+ def test_quick_num_clamped(self):
+ config = APISerpentSearchConfig()
+ assert _params(config, "q", {"max_results": 250})["num"] == 100
+ assert _params(config, "q", {"max_results": 0})["num"] == 1
+
+ def test_deep_num_floor_is_10(self):
+ config = APISerpentSearchConfig()
+ params = _params(config, "q", {"deep": True, "max_results": 5})
+ assert params["num"] == 10
+
+ def test_country_lowercased(self):
+ assert (
+ _params(APISerpentSearchConfig(), "q", {"country": "US"})["country"] == "us"
+ )
+
+ def test_engine_and_optional_passthrough(self):
+ params = _params(
+ APISerpentSearchConfig(),
+ "q",
+ {"engine": "bing", "language": "es", "freshness": "d", "safe": "strict"},
+ )
+ assert params["engine"] == "bing"
+ assert params["language"] == "es"
+ assert params["freshness"] == "d"
+ assert params["safe"] == "strict"
+
+ def test_pixel_position_passthrough_lowercased(self):
+ params = _params(APISerpentSearchConfig(), "q", {"pixel_position": True})
+ assert params["pixel_position"] == "true"
+
+ def test_domain_filter(self):
+ params = _params(
+ APISerpentSearchConfig(),
+ "machine learning",
+ {"search_domain_filter": ["arxiv.org", "nature.com"]},
+ )
+ assert "site:arxiv.org" in params["q"]
+ assert "site:nature.com" in params["q"]
+ assert "machine learning" in params["q"]
+
+ def test_get_complete_url_quick_path(self):
+ config = APISerpentSearchConfig()
+ data = {"_apiserpent_params": {"q": "test", "num": 5}}
+ url = config.get_complete_url(api_base=None, optional_params={}, data=data)
+ parsed = urlparse(url)
+ assert (
+ f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
+ == "https://apiserpent.com/api/search/quick"
+ )
+ assert parse_qs(parsed.query)["q"] == ["test"]
+
+ def test_get_complete_url_deep_path(self):
+ config = APISerpentSearchConfig()
+ data = {"_apiserpent_params": {"q": "test"}}
+ url = config.get_complete_url(
+ api_base=None, optional_params={"deep": True}, data=data
+ )
+ parsed = urlparse(url)
+ assert (
+ f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
+ == "https://apiserpent.com/api/search"
+ )
+
+ def test_explicit_api_base_swaps_host_and_keeps_routing(self):
+ config = APISerpentSearchConfig()
+ url = config.get_complete_url(
+ api_base="https://staging.apiserpent.com",
+ optional_params={"deep": True},
+ data={"_apiserpent_params": {"q": "x"}},
+ )
+ parsed = urlparse(url)
+ assert (
+ f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
+ == "https://staging.apiserpent.com/api/search"
+ )
+
+ def test_get_complete_url_is_idempotent(self):
+ """The handler re-invokes get_complete_url with the resolved URL as api_base."""
+ config = APISerpentSearchConfig()
+ resolved = config.get_complete_url(
+ api_base=None, optional_params={"deep": True}, data=None
+ )
+ again = config.get_complete_url(
+ api_base=resolved,
+ optional_params={"deep": True},
+ data={"_apiserpent_params": {"q": "x"}},
+ )
+ assert again == "https://apiserpent.com/api/search?q=x"
+ assert "/api/search/api/search" not in again
+
+ def test_transform_response_full_format(self):
+ raw_response = MagicMock()
+ raw_response.json.return_value = {
+ "success": True,
+ "results": {
+ "organic": [
+ {"title": "R1", "url": "https://example.com/1", "snippet": "S1"},
+ {"title": "R2", "url": "https://example.com/2", "snippet": "S2"},
+ ]
+ },
+ }
+ response = APISerpentSearchConfig().transform_search_response(
+ raw_response=raw_response, logging_obj=None
+ )
+ assert isinstance(response, SearchResponse)
+ assert len(response.results) == 2
+ assert response.results[0].title == "R1"
+ assert response.results[0].url == "https://example.com/1"
+
+ def test_transform_response_simple_format(self):
+ raw_response = MagicMock()
+ raw_response.json.return_value = {
+ "success": True,
+ "results": [{"position": 1, "title": "R1", "url": "https://example.com/1"}],
+ }
+ response = APISerpentSearchConfig().transform_search_response(
+ raw_response=raw_response, logging_obj=None
+ )
+ assert len(response.results) == 1
+ assert response.results[0].title == "R1"
+
+ def test_transform_response_empty(self):
+ raw_response = MagicMock()
+ raw_response.json.return_value = {"success": True, "results": {}}
+ response = APISerpentSearchConfig().transform_search_response(
+ raw_response=raw_response, logging_obj=None
+ )
+ assert len(response.results) == 0
+
+ def test_transform_response_null_results(self):
+ """An error response with `results: null` must not raise."""
+ raw_response = MagicMock()
+ raw_response.json.return_value = {"success": False, "results": None}
+ response = APISerpentSearchConfig().transform_search_response(
+ raw_response=raw_response, logging_obj=None
+ )
+ assert response.results == []
+
+
+class TestAPISerpentSearchIntegration:
+ @staticmethod
+ def _mock_response():
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "success": True,
+ "results": {
+ "organic": [
+ {
+ "title": "Test Result",
+ "url": "https://example.com",
+ "snippet": "A snippet",
+ }
+ ]
+ },
+ }
+ return mock_response
+
+ @pytest.mark.asyncio
+ async def test_asearch_quick_default(self):
+ os.environ["APISERPENT_API_KEY"] = "test-api-key"
+ with patch(
+ "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get",
+ new_callable=AsyncMock,
+ ) as mock_get:
+ mock_get.return_value = self._mock_response()
+
+ response = await litellm.asearch(
+ query="latest developments in AI",
+ search_provider="apiserpent",
+ max_results=5,
+ country="US",
+ )
+
+ parsed = urlparse(mock_get.call_args.kwargs["url"])
+ assert (
+ f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
+ == "https://apiserpent.com/api/search/quick"
+ )
+ qs = parse_qs(parsed.query)
+ assert qs["q"] == ["latest developments in AI"]
+ assert qs["num"] == ["5"]
+ assert qs["country"] == ["us"]
+ assert mock_get.call_args.kwargs["headers"]["X-API-Key"] == "test-api-key"
+
+ assert response.object == "search"
+ assert response.results[0].title == "Test Result"
+
+ @pytest.mark.asyncio
+ async def test_asearch_deep(self):
+ os.environ["APISERPENT_API_KEY"] = "test-api-key"
+ with patch(
+ "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get",
+ new_callable=AsyncMock,
+ ) as mock_get:
+ mock_get.return_value = self._mock_response()
+
+ await litellm.asearch(
+ query="climate research",
+ search_provider="apiserpent",
+ deep=True,
+ max_results=40,
+ )
+
+ parsed = urlparse(mock_get.call_args.kwargs["url"])
+ assert (
+ f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
+ == "https://apiserpent.com/api/search"
+ )
+ assert parse_qs(parsed.query)["num"] == ["40"]
diff --git a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
index 07a61c9c104..083f4a97ab6 100644
--- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
+++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
@@ -334,6 +334,79 @@ async def test_async_anthropic_messages_handler_passes_litellm_metadata():
assert kwargs_arg["litellm_metadata"]["model_info"] == custom_model_info
+async def test_async_anthropic_messages_handler_forwards_router_model_info():
+ """Ensure router deployment model_info is forwarded into litellm_params.
+
+ The Router stamps kwargs['model_info'] on every deployment dispatch via
+ _update_kwargs_with_deployment. Downstream cooldown / success callbacks
+ (router.deployment_callback_on_failure, deployment_callback_on_success)
+ look up the deployment id via kwargs['litellm_params']['model_info']['id'].
+ If async_anthropic_messages_handler builds its own litellm_params dict
+ without forwarding model_info, the id is missing and cooldown is silently
+ skipped for /v1/messages requests under the Router.
+ """
+ handler = BaseLLMHTTPHandler()
+
+ mock_config = Mock()
+ mock_config.validate_anthropic_messages_environment = Mock(
+ return_value=({"x-api-key": "test-key"}, "https://api.anthropic.com")
+ )
+ mock_config.transform_anthropic_messages_request = Mock(
+ return_value={"model": "claude-sonnet-4-20250514", "messages": []}
+ )
+
+ mock_client = AsyncMock()
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "id": "msg_123",
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "text", "text": "Hello!"}],
+ "model": "claude-sonnet-4-20250514",
+ "stop_reason": "end_turn",
+ }
+ mock_client.post = AsyncMock(return_value=mock_response)
+
+ mock_logging_obj = Mock()
+ mock_logging_obj.update_from_kwargs = Mock()
+ mock_logging_obj.model_call_details = {}
+ mock_logging_obj.stream = False
+
+ deployment_model_info = {
+ "id": "deployment-123",
+ "db_model": False,
+ }
+
+ try:
+ await handler.async_anthropic_messages_handler(
+ model="claude-sonnet-4-20250514",
+ messages=[{"role": "user", "content": "Hello"}],
+ anthropic_messages_provider_config=mock_config,
+ anthropic_messages_optional_request_params={},
+ custom_llm_provider="anthropic",
+ litellm_params=GenericLiteLLMParams(),
+ logging_obj=mock_logging_obj,
+ client=mock_client,
+ kwargs={"model_info": deployment_model_info},
+ )
+ except Exception:
+ pass
+
+ mock_logging_obj.update_from_kwargs.assert_called_once()
+ call_kwargs = mock_logging_obj.update_from_kwargs.call_args
+ litellm_params_arg = (
+ call_kwargs.kwargs.get(
+ "litellm_params", call_kwargs[1].get("litellm_params", {})
+ )
+ if call_kwargs.kwargs
+ else call_kwargs[1].get("litellm_params", {})
+ )
+
+ assert litellm_params_arg.get("model_info") == deployment_model_info
+
+
@pytest.mark.asyncio
async def test_async_anthropic_messages_handler_header_priority():
"""
diff --git a/tests/test_litellm/llms/github_copilot/test_github_copilot_transformation.py b/tests/test_litellm/llms/github_copilot/test_github_copilot_transformation.py
index 45ce5d58405..5673ad81551 100644
--- a/tests/test_litellm/llms/github_copilot/test_github_copilot_transformation.py
+++ b/tests/test_litellm/llms/github_copilot/test_github_copilot_transformation.py
@@ -530,3 +530,351 @@ def test_copilot_vision_request_header_with_type_image_url():
assert headers["Copilot-Vision-Request"] == "true"
assert headers["X-Initiator"] == "user"
+
+
+class TestGithubCopilotTransformResponse:
+ """
+ Tests for GithubCopilotConfig.transform_response handling of Anthropic-native
+ responses from newer Copilot models (e.g. claude-opus-4.7, claude-opus-4.8).
+
+ See: https://github.com/BerriAI/litellm/issues/29391
+ """
+
+ def _make_mock_response(self, json_data: dict, status_code: int = 200):
+ """Create a mock httpx.Response with the given JSON body."""
+ response = httpx.Response(
+ status_code=status_code,
+ json=json_data,
+ headers={"content-type": "application/json"},
+ )
+ return response
+
+ def _make_logging_obj(self):
+ """Create a mock logging object."""
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {}
+ return logging_obj
+
+ def test_transform_response_with_standard_choices(self):
+ """Standard OpenAI-format response with choices should work normally."""
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ response_json = {
+ "id": "chatcmpl-123",
+ "object": "chat.completion",
+ "created": 1700000000,
+ "model": "github_copilot/claude-opus-4.5",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "Hello!"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ },
+ }
+
+ raw_response = self._make_mock_response(response_json)
+ model_response = ModelResponse()
+
+ result = config.transform_response(
+ model="github_copilot/claude-opus-4.5",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "Hi"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result.choices[0].message.content == "Hello!"
+ assert result.choices[0].finish_reason == "stop"
+
+ def test_transform_response_no_choices_anthropic_native(self):
+ """
+ Newer Copilot models (opus-4.7, 4.8) may return Anthropic-native format
+ without choices. This must not crash with IndexError.
+ """
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ response_json = {
+ "id": "msg_vrtx_01ABC",
+ "type": "message",
+ "role": "assistant",
+ "model": "github_copilot/claude-opus-4.7",
+ "content": [{"type": "text", "text": "H"}],
+ "stop_reason": "max_tokens",
+ "usage": {
+ "input_tokens": 14,
+ "output_tokens": 1,
+ "total_tokens": 15,
+ },
+ }
+
+ raw_response = self._make_mock_response(response_json)
+ model_response = ModelResponse()
+
+ result = config.transform_response(
+ model="github_copilot/claude-opus-4.7",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "Hi"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result.choices[0].message.content == "H"
+ assert result.choices[0].finish_reason == "length"
+
+ def test_transform_response_empty_choices(self):
+ """Response with choices=[] should not crash."""
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ response_json = {
+ "id": "msg_vrtx_01ABC",
+ "model": "github_copilot/claude-opus-4.7",
+ "choices": [],
+ "usage": {
+ "input_tokens": 14,
+ "output_tokens": 1,
+ "total_tokens": 15,
+ },
+ }
+
+ raw_response = self._make_mock_response(response_json)
+ model_response = ModelResponse()
+
+ result = config.transform_response(
+ model="github_copilot/claude-opus-4.7",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "Hi"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert len(result.choices) >= 1
+ assert result.choices[0].finish_reason == "length"
+
+ def test_transform_response_no_choices_no_content(self):
+ """
+ Response with neither choices nor content (usage-only) should not crash.
+ This is the exact case triggered by max_tokens=1 on newer models.
+ """
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ response_json = {
+ "id": "msg_vrtx_01ABC",
+ "model": "github_copilot/claude-opus-4.8",
+ "usage": {
+ "input_tokens": 14,
+ "output_tokens": 1,
+ "total_tokens": 15,
+ },
+ "copilot_usage": {
+ "token_details": [],
+ "total_nano_aiu": 9500000,
+ },
+ }
+
+ raw_response = self._make_mock_response(response_json)
+ model_response = ModelResponse()
+
+ result = config.transform_response(
+ model="github_copilot/claude-opus-4.8",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "Hi"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert len(result.choices) >= 1
+ assert result.choices[0].message.content == ""
+ assert result.choices[0].finish_reason == "length"
+
+ def test_transform_response_anthropic_native_tool_use(self):
+ """tool_use blocks must be converted to OpenAI tool_calls on the message."""
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ response_json = {
+ "id": "msg_vrtx_tool",
+ "type": "message",
+ "role": "assistant",
+ "model": "github_copilot/claude-opus-4.8",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_01ABC",
+ "name": "get_weather",
+ "input": {"location": "Boston, MA"},
+ }
+ ],
+ "stop_reason": "tool_use",
+ "usage": {
+ "input_tokens": 10,
+ "output_tokens": 20,
+ "total_tokens": 30,
+ },
+ }
+
+ raw_response = self._make_mock_response(response_json)
+ model_response = ModelResponse()
+
+ result = config.transform_response(
+ model="github_copilot/claude-opus-4.8",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "What's the weather?"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result.choices[0].finish_reason == "tool_calls"
+ assert result.choices[0].message.tool_calls is not None
+ assert len(result.choices[0].message.tool_calls) == 1
+ assert result.choices[0].message.tool_calls[0]["id"] == "toolu_01ABC"
+ assert (
+ result.choices[0].message.tool_calls[0]["function"]["name"] == "get_weather"
+ )
+ assert (
+ '"Boston, MA"'
+ in result.choices[0].message.tool_calls[0]["function"]["arguments"]
+ )
+
+ def test_transform_response_anthropic_native_multiple_text_blocks(self):
+ """All text blocks must be concatenated, not only the first."""
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ response_json = {
+ "id": "msg_vrtx_multi_text",
+ "type": "message",
+ "role": "assistant",
+ "model": "github_copilot/claude-opus-4.7",
+ "content": [
+ {"type": "text", "text": "Hello "},
+ {"type": "text", "text": "world!"},
+ ],
+ "stop_reason": "end_turn",
+ "usage": {
+ "input_tokens": 5,
+ "output_tokens": 3,
+ "total_tokens": 8,
+ },
+ }
+
+ raw_response = self._make_mock_response(response_json)
+ model_response = ModelResponse()
+
+ result = config.transform_response(
+ model="github_copilot/claude-opus-4.7",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "Hi"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result.choices[0].message.content == "Hello world!"
+ assert result.choices[0].finish_reason == "stop"
+
+ def test_transform_response_anthropic_native_thinking_then_text(self):
+ """Thinking blocks are preserved; following text is still extracted."""
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ response_json = {
+ "id": "msg_vrtx_thinking",
+ "type": "message",
+ "role": "assistant",
+ "model": "github_copilot/claude-opus-4.8",
+ "content": [
+ {
+ "type": "thinking",
+ "thinking": "Let me reason about this.",
+ "signature": "sig123",
+ },
+ {"type": "text", "text": "The answer is 42."},
+ ],
+ "stop_reason": "end_turn",
+ "usage": {
+ "input_tokens": 20,
+ "output_tokens": 10,
+ "total_tokens": 30,
+ },
+ }
+
+ raw_response = self._make_mock_response(response_json)
+ model_response = ModelResponse()
+
+ result = config.transform_response(
+ model="github_copilot/claude-opus-4.8",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "What is the answer?"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result.choices[0].message.content == "The answer is 42."
+ assert result.choices[0].message.thinking_blocks is not None
+ assert len(result.choices[0].message.thinking_blocks) == 1
+ assert result.choices[0].finish_reason == "stop"
+
+ def test_transform_response_invalid_json_falls_through_to_super(self):
+ """
+ When raw_response.json() raises an exception (e.g. non-JSON body),
+ transform_response should delegate to super() without crashing.
+ """
+ config = GithubCopilotConfig()
+ config.authenticator = MagicMock()
+
+ raw_response = httpx.Response(
+ status_code=200,
+ content=b"not valid json at all",
+ headers={"content-type": "text/plain"},
+ )
+ model_response = ModelResponse()
+
+ with pytest.raises(Exception):
+ config.transform_response(
+ model="github_copilot/claude-opus-4.7",
+ raw_response=raw_response,
+ model_response=model_response,
+ logging_obj=self._make_logging_obj(),
+ request_data={},
+ messages=[{"role": "user", "content": "Hi"}],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
diff --git a/tests/test_litellm/llms/xai/test_xai_key_fallback.py b/tests/test_litellm/llms/xai/test_xai_key_fallback.py
new file mode 100644
index 00000000000..4c769c572ac
--- /dev/null
+++ b/tests/test_litellm/llms/xai/test_xai_key_fallback.py
@@ -0,0 +1,296 @@
+import asyncio
+import os
+import sys
+
+sys.path.insert(
+ 0, os.path.abspath("../../../..")
+) # Adds the parent directory to the system path
+
+import pytest
+
+import litellm
+from litellm.llms.xai.chat.transformation import XAIChatConfig
+from litellm.llms.xai.common_utils import XAIModelInfo
+from litellm.llms.xai.responses.transformation import XAIResponsesAPIConfig
+from litellm.realtime_api import main as realtime_main
+from litellm.types.router import GenericLiteLLMParams
+
+
+class FakeLogging:
+ def update_from_kwargs(self, **kwargs):
+ pass
+
+
+def test_get_api_key_prefers_xai_key_over_environment_and_generic_key(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ assert XAIModelInfo.get_api_key(None) == "xai_key_value"
+
+
+def test_get_api_key_prefers_explicit_key_for_both_orderings(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ assert XAIModelInfo.get_api_key("param_api_key") == "param_api_key"
+ assert (
+ XAIModelInfo.get_api_key("param_api_key", legacy_generic_before_env=True)
+ == "param_api_key"
+ )
+
+
+def test_get_api_key_prefers_environment_over_generic_key_by_default(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ assert XAIModelInfo.get_api_key(None) == "env_api_key"
+
+
+def test_get_api_key_does_not_use_generic_key_by_default(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.delenv("XAI_API_KEY", raising=False)
+
+ assert XAIModelInfo.get_api_key(None) is None
+
+
+def test_get_api_key_legacy_order_prefers_generic_key_over_env(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ assert (
+ XAIModelInfo.get_api_key(None, legacy_generic_before_env=True)
+ == "common_api_key"
+ )
+
+
+def test_get_api_key_legacy_order_prefers_xai_key_over_generic_key(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ assert (
+ XAIModelInfo.get_api_key(None, legacy_generic_before_env=True)
+ == "xai_key_value"
+ )
+
+
+def test_get_api_key_returns_none_when_no_key_is_available(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", None)
+ monkeypatch.delenv("XAI_API_KEY", raising=False)
+
+ assert XAIModelInfo.get_api_key(None) is None
+
+
+def test_chat_config_uses_xai_key_fallback(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", None)
+ monkeypatch.delenv("XAI_API_KEY", raising=False)
+
+ _, api_key = XAIChatConfig()._get_openai_compatible_provider_info(None, None)
+
+ assert api_key == "xai_key_value"
+
+
+def test_chat_config_uses_environment_key_fallback(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", None)
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ _, api_key = XAIChatConfig()._get_openai_compatible_provider_info(None, None)
+
+ assert api_key == "env_api_key"
+
+
+def test_chat_config_does_not_use_generic_key_fallback(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.delenv("XAI_API_KEY", raising=False)
+
+ _, api_key = XAIChatConfig()._get_openai_compatible_provider_info(None, None)
+
+ assert api_key is None
+
+
+def test_chat_config_prefers_explicit_api_key(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ _, api_key = XAIChatConfig()._get_openai_compatible_provider_info(
+ None, "param_api_key"
+ )
+
+ assert api_key == "param_api_key"
+
+
+def test_responses_config_preserves_generic_key_precedence(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ headers = XAIResponsesAPIConfig().validate_environment({}, "xai/grok-3-mini", None)
+
+ assert headers["Authorization"] == "Bearer common_api_key"
+
+
+def test_responses_config_prefers_litellm_params_api_key(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ headers = XAIResponsesAPIConfig().validate_environment(
+ {},
+ "xai/grok-3-mini",
+ GenericLiteLLMParams(api_key="param_api_key"),
+ )
+
+ assert headers["Authorization"] == "Bearer param_api_key"
+
+
+def test_responses_config_uses_environment_key_fallback(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", None)
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ headers = XAIResponsesAPIConfig().validate_environment({}, "xai/grok-3-mini", None)
+
+ assert headers["Authorization"] == "Bearer env_api_key"
+
+
+def test_responses_config_raises_when_no_key_is_available(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", None)
+ monkeypatch.delenv("XAI_API_KEY", raising=False)
+
+ with pytest.raises(ValueError) as exc_info:
+ XAIResponsesAPIConfig().validate_environment({}, "xai/grok-3-mini", None)
+
+ error_message = str(exc_info.value)
+ assert "api_key" in error_message
+ assert "litellm.xai_key" in error_message
+ assert "litellm.api_key" in error_message
+ assert "XAI_API_KEY" in error_message
+
+
+def test_responses_config_prefers_xai_key_over_generic_key(monkeypatch):
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+
+ headers = XAIResponsesAPIConfig().validate_environment({}, "xai/grok-3-mini", None)
+
+ assert headers["Authorization"] == "Bearer xai_key_value"
+
+
+def test_realtime_config_uses_xai_key_through_provider_resolution(monkeypatch):
+ captured_kwargs = {}
+
+ async def mock_async_realtime(**kwargs):
+ captured_kwargs.update(kwargs)
+
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+ monkeypatch.setattr(
+ realtime_main.xai_realtime, "async_realtime", mock_async_realtime
+ )
+
+ asyncio.run(
+ realtime_main._arealtime(
+ model="xai/grok-4-1-fast-non-reasoning",
+ websocket=object(),
+ litellm_logging_obj=FakeLogging(),
+ )
+ )
+
+ assert captured_kwargs["api_key"] == "xai_key_value"
+
+
+def test_realtime_config_uses_xai_key_when_provider_does_not_resolve_key(monkeypatch):
+ captured_kwargs = {}
+
+ async def mock_async_realtime(**kwargs):
+ captured_kwargs.update(kwargs)
+
+ def mock_get_llm_provider(model, api_base, api_key):
+ return model, "xai", None, api_base
+
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.setenv("XAI_API_KEY", "env_api_key")
+ monkeypatch.setattr(realtime_main, "get_llm_provider", mock_get_llm_provider)
+ monkeypatch.setattr(
+ realtime_main.xai_realtime, "async_realtime", mock_async_realtime
+ )
+
+ asyncio.run(
+ realtime_main._arealtime(
+ model="xai/grok-4-1-fast-non-reasoning",
+ websocket=object(),
+ litellm_logging_obj=FakeLogging(),
+ )
+ )
+
+ assert captured_kwargs["api_key"] == "xai_key_value"
+
+
+def test_realtime_config_uses_generic_key_when_provider_does_not_resolve_key(
+ monkeypatch,
+):
+ captured_kwargs = {}
+
+ async def mock_async_realtime(**kwargs):
+ captured_kwargs.update(kwargs)
+
+ def mock_get_llm_provider(model, api_base, api_key):
+ return model, "xai", None, api_base
+
+ monkeypatch.setattr(litellm, "xai_key", None)
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.delenv("XAI_API_KEY", raising=False)
+ monkeypatch.setattr(realtime_main, "get_llm_provider", mock_get_llm_provider)
+ monkeypatch.setattr(
+ realtime_main.xai_realtime, "async_realtime", mock_async_realtime
+ )
+
+ asyncio.run(
+ realtime_main._arealtime(
+ model="xai/grok-4-1-fast-non-reasoning",
+ websocket=object(),
+ litellm_logging_obj=FakeLogging(),
+ )
+ )
+
+ assert captured_kwargs["api_key"] == "common_api_key"
+
+
+def test_get_models_uses_xai_key_fallback(monkeypatch):
+ captured_kwargs = {}
+
+ class FakeResponse:
+ status_code = 200
+ text = "{}"
+
+ def raise_for_status(self):
+ pass
+
+ def json(self):
+ return {"data": [{"id": "grok-test"}]}
+
+ def mock_get(**kwargs):
+ captured_kwargs.update(kwargs)
+ return FakeResponse()
+
+ monkeypatch.setattr(litellm, "xai_key", "xai_key_value")
+ monkeypatch.setattr(litellm, "api_key", "common_api_key")
+ monkeypatch.delenv("XAI_API_KEY", raising=False)
+ monkeypatch.setattr(litellm.module_level_client, "get", mock_get)
+
+ assert XAIModelInfo().get_models() == ["xai/grok-test"]
+ assert captured_kwargs["headers"]["Authorization"] == "Bearer xai_key_value"
diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.py
index 52e7a0ff373..6f6c4508333 100644
--- a/tests/test_litellm/proxy/auth/test_auth_checks.py
+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py
@@ -1628,7 +1628,8 @@ async def test_reject_clientside_metadata_tags_non_llm_route():
@pytest.mark.asyncio
async def test_reject_clientside_metadata_tags_allows_key_tags_without_client_tags():
"""Key metadata.tags are injected after the reject check; requests without
- client metadata.tags must not be blocked when reject_clientside_metadata_tags is on."""
+ client metadata.tags must not be blocked when reject_clientside_metadata_tags is on.
+ """
from fastapi import Request
from litellm.proxy.auth.auth_checks import common_checks
@@ -3513,3 +3514,111 @@ async def test_cache_team_object_writes_team_id_and_invalidates_team_alias():
for c in cache2.async_set_cache.await_args_list
]
assert written_keys_aliasless == ["team_id:team-no-alias"]
+
+
+MODEL_DISCOVERY_ROUTES = [
+ "/v1/models",
+ "/models",
+ "/model/info",
+ "/v1/model/info",
+ "/v2/model/info",
+ "/model_group/info",
+]
+
+
[email protected]("route", MODEL_DISCOVERY_ROUTES)
+async def test_model_discovery_route_bypasses_team_budget(route):
+ """Regression for #27923: an exhausted team budget must not block model-discovery routes,
+ otherwise OpenAI-compatible clients calling GET /v1/models at startup break."""
+ from litellm.proxy.auth.auth_checks import common_checks
+
+ team_object = LiteLLM_TeamTable(team_id="test-team", spend=150.0, max_budget=100.0)
+
+ result = await common_checks(
+ request_body={},
+ team_object=team_object,
+ user_object=None,
+ end_user_object=None,
+ global_proxy_spend=None,
+ general_settings={},
+ route=route,
+ llm_router=None,
+ proxy_logging_obj=AsyncMock(),
+ valid_token=UserAPIKeyAuth(token="test-token", team_id="test-team"),
+ request=MagicMock(),
+ )
+
+ assert result is True
+
+
+async def test_model_discovery_route_bypasses_user_budget():
+ """Regression for #27923: an exhausted user budget must not block model discovery."""
+ from litellm.proxy.auth.auth_checks import common_checks
+
+ user_object = LiteLLM_UserTable(user_id="test-user", spend=100.0, max_budget=50.0)
+
+ result = await common_checks(
+ request_body={},
+ team_object=None,
+ user_object=user_object,
+ end_user_object=None,
+ global_proxy_spend=None,
+ general_settings={},
+ route="/v1/models",
+ llm_router=None,
+ proxy_logging_obj=AsyncMock(),
+ valid_token=UserAPIKeyAuth(token="test-token", user_id="test-user"),
+ request=MagicMock(),
+ )
+
+ assert result is True
+
+
+async def test_side_effectful_info_route_still_enforces_budget():
+ """#27923 keeps the bypass narrow: /health/services can fire Slack/email/webhook test
+ messages, so an exhausted budget must still block it. Widening the exemption back to
+ is_info_route() would regress this."""
+ from litellm.proxy.auth.auth_checks import common_checks
+
+ team_object = LiteLLM_TeamTable(team_id="test-team", spend=150.0, max_budget=100.0)
+
+ with pytest.raises(litellm.BudgetExceededError):
+ await common_checks(
+ request_body={},
+ team_object=team_object,
+ user_object=None,
+ end_user_object=None,
+ global_proxy_spend=None,
+ general_settings={},
+ route="/health/services",
+ llm_router=None,
+ proxy_logging_obj=AsyncMock(),
+ valid_token=UserAPIKeyAuth(token="test-token", team_id="test-team"),
+ request=MagicMock(),
+ )
+
+
+async def test_inference_route_still_enforces_team_budget():
+ """Control for #27923: inference routes stay fully budget-enforced."""
+ from litellm.proxy.auth.auth_checks import common_checks
+
+ team_object = LiteLLM_TeamTable(team_id="test-team", spend=150.0, max_budget=100.0)
+
+ with pytest.raises(litellm.BudgetExceededError):
+ await common_checks(
+ request_body={},
+ team_object=team_object,
+ user_object=None,
+ end_user_object=None,
+ global_proxy_spend=None,
+ general_settings={},
+ route="/v1/chat/completions",
+ llm_router=None,
+ proxy_logging_obj=AsyncMock(),
+ valid_token=UserAPIKeyAuth(token="test-token", team_id="test-team"),
+ request=MagicMock(),
+ )
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py
index 716b4470d25..d31dbdd4348 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py
@@ -28,6 +28,7 @@ from litellm.types.utils import (
ChatCompletionMessageToolCall,
Choices,
ModelResponse,
+ ModelResponseStream,
)
@@ -676,6 +677,49 @@ class TestToolPermissionGuardrail:
assert new_data["function_call"] == "none"
assert new_data["tool_choice"] == "none"
+ @pytest.mark.asyncio
+ async def test_async_post_call_streaming_iterator_hook_plain_text_yields_chunks(
+ self,
+ ):
+ """Regression test: hook must re-emit chunks when LLM replies with plain text.
+
+ Before the fix, the `if not tool_calls:` branch did a bare `return` inside
+ the async generator, which yielded nothing. Clients received only
+ `data: [DONE]` with no content.
+ """
+ text_chunk = ModelResponseStream(
+ id="chatcmpl-plain-text",
+ created=1700000000,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[],
+ )
+
+ async def _fake_stream():
+ yield text_chunk
+
+ assembled = ModelResponse(
+ choices=[Choices(message={"content": "Hello, world!"})]
+ )
+
+ with patch("litellm.main.stream_chunk_builder", return_value=assembled):
+ chunks = []
+ async for chunk in self.guardrail.async_post_call_streaming_iterator_hook(
+ user_api_key_dict=UserAPIKeyAuth(),
+ response=_fake_stream(),
+ request_data={},
+ ):
+ chunks.append(chunk)
+
+ assert len(chunks) >= 1, (
+ "Hook must yield at least one chunk for plain-text responses; "
+ "got none — bare return bug"
+ )
+ assert chunks[0].choices[0].delta.content == "Hello, world!", (
+ "Hook must preserve the original response content; "
+ f"got: {chunks[0].choices[0].delta.content!r}"
+ )
+
def test_modify_response_with_permission_errors(self):
# Setup a response with one tool_call
tool_call = ChatCompletionMessageToolCall(
diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
index 3559008642f..aef91ed3c77 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
@@ -1621,6 +1621,71 @@ async def test_ui_view_spend_logs_with_model_id(client, monkeypatch):
app.dependency_overrides.pop(ps.user_api_key_auth, None)
+async def test_ui_view_spend_logs_with_model_group(client, monkeypatch):
+ """Test that the model_group query param filters spend logs by model group."""
+ mock_spend_logs = [
+ {
+ "id": "log1",
+ "request_id": "req1",
+ "api_key": "sk-test-key",
+ "user": "test_user_1",
+ "team_id": "team1",
+ "spend": 0.05,
+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),
+ "model": "gpt-3.5-turbo",
+ "model_group": "gpt-3.5-turbo",
+ "status": "success",
+ },
+ {
+ "id": "log2",
+ "request_id": "req2",
+ "api_key": "sk-test-key",
+ "user": "test_user_2",
+ "team_id": "team1",
+ "spend": 0.10,
+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),
+ "model": "gpt-4-0613",
+ "model_group": "gpt-4",
+ "status": "success",
+ },
+ ]
+
+ def filter_by_model_group(where):
+ if "model_group" in where and where["model_group"] == "gpt-4":
+ return [mock_spend_logs[1]]
+ return mock_spend_logs
+
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.prisma_client",
+ make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_model_group),
+ )
+
+ start_date, end_date = _default_date_range()
+
+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN
+ )
+ try:
+ response = client.get(
+ "/spend/logs/ui",
+ params={
+ "model_group": "gpt-4",
+ "start_date": start_date,
+ "end_date": end_date,
+ },
+ headers={"Authorization": "Bearer sk-test"},
+ )
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["total"] == 1
+ assert len(data["data"]) == 1
+ assert data["data"][0]["model_group"] == "gpt-4"
+ finally:
+ app.dependency_overrides.pop(ps.user_api_key_auth, None)
+
+
@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_key_hash(client, monkeypatch):
mock_spend_logs = [
diff --git a/tests/test_litellm/test_secret_redaction.py b/tests/test_litellm/test_secret_redaction.py
index 8a0a2221c11..85430ba752b 100644
--- a/tests/test_litellm/test_secret_redaction.py
+++ b/tests/test_litellm/test_secret_redaction.py
@@ -215,6 +215,38 @@ def test_json_excepthook_redacts_traceback_secrets():
assert "REDACTED" in output
+def test_xai_key_redaction_catches_proxy_log_and_config_dump():
+ """xai_key is redacted in proxy log and config dump formats."""
+ cases = [
+ ("setting litellm.xai_key=xai-test-secret-123456", "xai-test-secret-123456"),
+ ("'xai_key': 'xai-test-secret-123456'", "xai-test-secret-123456"),
+ ]
+ for secret_line, secret in cases:
+ result = redact_string(secret_line)
+ assert secret not in result
+ assert "REDACTED" in result, f"xai_key redaction missed: {secret_line!r}"
+
+
+def test_module_level_provider_key_redaction_catches_proxy_log_format():
+ """Provider module-level keys are redacted when logged by proxy startup."""
+ cases = [
+ ("setting litellm.groq_key=gsk-test-secret-123456", "gsk-test-secret-123456"),
+ (
+ "setting litellm.openai_key=openai-test-secret-123456",
+ "openai-test-secret-123456",
+ ),
+ ]
+ for secret_line, secret in cases:
+ result = redact_string(secret_line)
+ assert secret not in result
+ assert (
+ "REDACTED" in result
+ ), f"Module-level key redaction missed: {secret_line!r}"
+
+ safe = "cache_key=cache-value-123456"
+ assert redact_string(safe) == safe
+
+
def test_key_name_redaction_catches_secrets_in_dict_repr():
"""Secrets inside dict repr strings are redacted based on key names."""
cases = [