diff --git a/.github/workflows/check-ui-api-types.yml b/.github/workflows/check-ui-api-types.yml index 285676a0ddd..312a80103f8 100644 --- a/.github/workflows/check-ui-api-types.yml +++ b/.github/workflows/check-ui-api-types.yml @@ -83,6 +83,24 @@ jobs: if: steps.changes.outputs.relevant == 'true' run: uv run --no-sync prisma generate --schema litellm/proxy/schema.prisma + - name: Regenerate the lazy OpenAPI snapshot + if: steps.changes.outputs.relevant == 'true' + run: uv run --no-sync python -m litellm.proxy._lazy_openapi_snapshot + + - name: Fail if the lazy OpenAPI snapshot is stale + if: steps.changes.outputs.relevant == 'true' + run: | + if ! git diff --exit-code -- litellm/proxy/_lazy_openapi_snapshot.json; then + echo "::error file=litellm/proxy/_lazy_openapi_snapshot.json::The lazy OpenAPI snapshot is out of sync with the lazily loaded routes." + echo "" + echo "A lazily loaded route or model changed without regenerating the snapshot that /openapi.json serves for unloaded features." + echo "To fix, run from the repo root:" + echo " uv run python -m litellm.proxy._lazy_openapi_snapshot" + echo "then run npm run gen:api from ui/litellm-dashboard and commit both files." + exit 1 + fi + echo "_lazy_openapi_snapshot.json is in sync with the lazily loaded routes." + - name: Set up Node.js if: steps.changes.outputs.relevant == 'true' uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 diff --git a/db_scripts/partition_spend_logs.sql b/db_scripts/partition_spend_logs.sql index 08fcbddb6f8..4e4a93539d7 100644 --- a/db_scripts/partition_spend_logs.sql +++ b/db_scripts/partition_spend_logs.sql @@ -10,6 +10,11 @@ -- partitioned, so existing installs are unaffected until you run this. -- -- IMPORTANT +-- * After partitioning, `prisma db push` (including the proxy's +-- --use_prisma_db_push startup mode) is NOT supported: it tries to rewrite +-- the primary key back to ("request_id"), which Postgres rejects on a +-- partitioned table. The proxy detects this and exits with guidance. +-- Use the default startup path (`prisma migrate deploy`) instead. -- * Test on a staging copy first and take a backup. -- * Postgres cannot convert a populated table to partitioned in place, so this -- renames the old table aside and creates a fresh partitioned table. diff --git a/enterprise/pyproject.toml b/enterprise/pyproject.toml index b7a62e52cf9..3653aba67ef 100644 --- a/enterprise/pyproject.toml +++ b/enterprise/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "litellm-enterprise" -version = "0.1.60" +version = "0.1.61" description = "Package for LiteLLM Enterprise features" readme = "README.md" requires-python = ">=3.9" @@ -26,7 +26,7 @@ required-version = ">=0.10.9" module-root = "" [tool.commitizen] -version = "0.1.60" +version = "0.1.61" version_files = [ "pyproject.toml:^version", "../pyproject.toml:litellm-enterprise==", diff --git a/litellm-proxy-extras/litellm_proxy_extras/utils.py b/litellm-proxy-extras/litellm_proxy_extras/utils.py index 5118865e43a..b27221c9beb 100644 --- a/litellm-proxy-extras/litellm_proxy_extras/utils.py +++ b/litellm-proxy-extras/litellm_proxy_extras/utils.py @@ -40,6 +40,65 @@ def _get_prisma_env() -> dict: _MIGRATION_TS_RE = re.compile(r"^(\d{14})_") +_SPEND_LOGS_ALTER_RE = re.compile(r'^ALTER\s+TABLE\s+"LiteLLM_SpendLogs"\s', re.IGNORECASE) +_SPEND_LOGS_ARTIFACT_DROP_RE = re.compile( + r'^DROP\s+TABLE\s+"LiteLLM_SpendLogs_[^"]*"', re.IGNORECASE +) +_SPEND_LOGS_PK_CLAUSE_RE = re.compile( + r'^(?:DROP\s+CONSTRAINT\s+"[^"]*_pkey"' + r'|ADD\s+(?:CONSTRAINT\s+"[^"]*"\s+)?PRIMARY\s+KEY\s*\([^)]*\))$', + re.IGNORECASE, +) + +PARTITIONED_SPEND_LOGS_PUSH_ERROR = ( + "LiteLLM_SpendLogs is a partitioned table (see db_scripts/partition_spend_logs.sql), " + "so its primary key must include the partition key (\"startTime\"). `prisma db push` " + "reconciles the database against schema.prisma, which declares the unpartitioned " + "primary key (\"request_id\"), and Postgres rejects that rewrite with: unique " + "constraint on partitioned table must include all partitioning columns. Start the " + "proxy without --use_prisma_db_push so it uses `prisma migrate deploy`, which only " + "applies shipped migrations and leaves the partitioned primary key alone." +) + + +def _without_sql_comments(statement: str) -> str: + return "\n".join( + line + for line in statement.splitlines() + if line.strip() and not line.strip().startswith("--") + ).strip() + + +def _without_spend_logs_pk_clauses(statement: str) -> Optional[str]: + prefix_match = _SPEND_LOGS_ALTER_RE.match(statement) + if not prefix_match: + return statement + kept = tuple( + clause.strip() + for clause in statement[prefix_match.end():].split(",\n") + if not _SPEND_LOGS_PK_CLAUSE_RE.match(clause.strip()) + ) + if not kept: + return None + return statement[: prefix_match.end()] + ",\n".join(kept) + + +def filter_partitioned_spend_logs_diff(diff_sql: str) -> str: + """Drop statements from a `prisma migrate diff` script that fight the + SpendLogs partitioning runbook (db_scripts/partition_spend_logs.sql): the + primary-key rewrite on "LiteLLM_SpendLogs", which Postgres rejects on a + partitioned table, and drops of runbook artifacts such as + "LiteLLM_SpendLogs_legacy".""" + kept = tuple( + filtered + for statement in diff_sql.split(";") + for bare in (_without_sql_comments(statement),) + if bare and not _SPEND_LOGS_ARTIFACT_DROP_RE.match(bare) + for filtered in (_without_spend_logs_pk_clauses(bare),) + if filtered is not None + ) + return "".join(f"{statement};\n\n" for statement in kept) + def _migration_timestamp(name: str) -> int: """Extract the leading `YYYYMMDDHHMMSS` timestamp from a migration name. @@ -355,7 +414,24 @@ class ProxyExtrasDBManager: return logger.info(f"Migration diff created at {diff_sql_path}") + if ProxyExtrasDBManager.spend_logs_is_partitioned(): + filtered_sql = filter_partitioned_spend_logs_diff( + diff_sql_path.read_text() + ) + diff_sql_path.write_text(filtered_sql) + logger.info( + "LiteLLM_SpendLogs is partitioned; removed its primary-key " + "rewrite and partitioning artifacts from the drift script" + ) + if not filtered_sql.strip(): + logger.info("Drift script is empty after filtering; nothing to apply") + if not mark_all_applied: + return + ProxyExtrasDBManager._mark_migrations_applied(migrations_dir) + return + # 2. Run prisma db execute to apply the migration + applied_ok = False try: logger.info("Running prisma db execute to apply the migration diff...") result = subprocess.run( @@ -376,6 +452,7 @@ class ProxyExtrasDBManager: ) logger.info(f"prisma db execute stdout: {result.stdout}") logger.info("✅ Migration diff applied successfully") + applied_ok = True except subprocess.CalledProcessError as e: logger.warning(f"Failed to apply migration diff: {e.stderr}") except subprocess.TimeoutExpired: @@ -384,6 +461,16 @@ class ProxyExtrasDBManager: # 3. Mark all migrations as applied if not mark_all_applied: return + if not applied_ok: + logger.warning( + "Drift script failed to apply; NOT marking migrations as " + "applied so a later migration run can retry them" + ) + return + ProxyExtrasDBManager._mark_migrations_applied(migrations_dir) + + @staticmethod + def _mark_migrations_applied(migrations_dir: str): migration_names = ProxyExtrasDBManager._get_migration_names(migrations_dir) logger.info(f"Resolving {len(migration_names)} migrations") for migration_name in migration_names: @@ -410,6 +497,55 @@ class ProxyExtrasDBManager: f"Failed to resolve migration {migration_name}: {e.stderr}" ) + @staticmethod + def spend_logs_is_partitioned() -> bool: + """True when the connected database's LiteLLM_SpendLogs is a + partitioned table in Prisma's target schema (the `schema` URL param, + falling back to Prisma's default target, public), i.e. the operator + ran db_scripts/partition_spend_logs.sql. Returns False when psycopg is + unavailable or the database cannot be reached, preserving the + pre-existing behavior in those cases.""" + database_url = os.getenv("DATABASE_URL") + if not database_url: + return False + + try: + import psycopg + except ImportError: + return False + + cleaned_url = ProxyExtrasDBManager._strip_prisma_query_params(database_url) + try: + with psycopg.connect( + cleaned_url, connect_timeout=10, autocommit=True + ) as conn: + row = conn.execute( + "SELECT 1 " + "FROM pg_partitioned_table pt " + "JOIN pg_class c ON c.oid = pt.partrelid " + "JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE c.relname = 'LiteLLM_SpendLogs' " + " AND n.nspname = %s", + ( + ProxyExtrasDBManager._prisma_schema_param(database_url) + or "public", + ), + ).fetchone() + except (psycopg.OperationalError, psycopg.DatabaseError): + return False + return row is not None + + @staticmethod + def _prisma_schema_param(url: str) -> Optional[str]: + """The `schema` query param Prisma uses to pick its target schema, + or None when the URL does not set one.""" + from urllib.parse import urlparse, parse_qsl + + return next( + (v for k, v in parse_qsl(urlparse(url).query) if k == "schema"), + None, + ) + @staticmethod def _strip_prisma_query_params(url: str) -> str: """Remove Prisma-specific query params (connection_limit, pool_timeout, @@ -528,7 +664,8 @@ class ProxyExtrasDBManager: migrations_dir = ProxyExtrasDBManager._get_prisma_dir() if not use_migrate: - # Preserve `prisma db push` path unchanged. + if ProxyExtrasDBManager.spend_logs_is_partitioned(): + raise RuntimeError(PARTITIONED_SPEND_LOGS_PUSH_ERROR) original_dir = os.getcwd() os.chdir(migrations_dir) try: @@ -972,6 +1109,8 @@ class ProxyExtrasDBManager: ) raise else: + if ProxyExtrasDBManager.spend_logs_is_partitioned(): + raise RuntimeError(PARTITIONED_SPEND_LOGS_PUSH_ERROR) # Use prisma db push with increased timeout subprocess.run( [_get_prisma_command(), "db", "push", "--accept-data-loss"], diff --git a/litellm-proxy-extras/pyproject.toml b/litellm-proxy-extras/pyproject.toml index 98a3d8d535e..0ef5cd1e856 100644 --- a/litellm-proxy-extras/pyproject.toml +++ b/litellm-proxy-extras/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "litellm-proxy-extras" -version = "0.4.89" +version = "0.4.90" description = "Additional files for the LiteLLM Proxy. Reduces the size of the main litellm package." readme = "README.md" requires-python = ">=3.9" @@ -26,7 +26,7 @@ required-version = ">=0.10.9" module-root = "" [tool.commitizen] -version = "0.4.89" +version = "0.4.90" version_files = [ "pyproject.toml:^version", "../pyproject.toml:litellm-proxy-extras==", diff --git a/litellm/__init__.py b/litellm/__init__.py index eebd2dad91e..ec2960c196e 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -445,6 +445,7 @@ max_ui_session_budget: Optional[float] = ( 1.0 # USD budget for each dashboard login session (playground, test connection) ) internal_user_budget_duration: Optional[str] = None +budget_rollover: bool = False # carry spend beyond max_budget into the next window instead of zeroing it tag_budget_config: Optional[Dict[str, "BudgetConfig"]] = None max_end_user_budget: Optional[float] = None max_end_user_budget_id: Optional[str] = None diff --git a/litellm/constants.py b/litellm/constants.py index 816397ef047..ed89474600e 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -1473,6 +1473,12 @@ LITELLM_PROXY_MASTER_KEY_ALIAS: Final = "litellm_proxy_master_key" # ``ProxyLogging._handle_logging_proxy_only_error``. LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL: Final = "litellm_no_upstream_llm_call" +# Key/team metadata fields naming the OTel Resource ``service.name``, highest +# precedence first. Shared between the OTel v2 tenant router (which reads them +# out of ``user_api_key_auth_metadata``) and proxy request setup (which re-applies +# the key's values after the team metadata merge so a key outranks its team). +OTEL_SERVICE_NAME_METADATA_KEYS: Final = ("otel_service_name_override", "otel_service_name") + # Key Rotation Constants LITELLM_KEY_ROTATION_ENABLED: Final = os.getenv("LITELLM_KEY_ROTATION_ENABLED", "false") LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS: Final = int( @@ -1646,6 +1652,7 @@ LITELLM_SETTINGS_SAFE_DB_OVERRIDES: Final = [ "enable_anthropic_prompt_caching", "anthropic_prompt_caching_ttl", "max_ui_session_budget", + "budget_rollover", ] SPECIAL_LITELLM_AUTH_TOKEN: Final = ["ui-token"] DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL = int(os.getenv("DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL", 60)) diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py index 37a79e2f6d4..457baddd232 100644 --- a/litellm/cost_calculator.py +++ b/litellm/cost_calculator.py @@ -557,9 +557,10 @@ def cost_per_token( ) elif call_type == "atranscription" or call_type == "transcription": if _transcription_usage_has_token_details(usage_block): - return openai_cost_per_token( + return generic_cost_per_token( model=model_without_prefix, usage=usage_block, + custom_llm_provider=custom_llm_provider, service_tier=service_tier, data_residency=data_residency, ) diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py index be9d2b88e99..f0a1bff8fdc 100644 --- a/litellm/experimental_mcp_client/client.py +++ b/litellm/experimental_mcp_client/client.py @@ -56,6 +56,9 @@ from litellm.types.mcp import ( MCPStdioConfig, MCPTransport, MCPTransportType, + credential_redirect_hook, + has_header, + without_header, ) @@ -273,6 +276,7 @@ class MCPClient: transport_type: MCPTransportType = MCPTransport.http, auth_type: MCPAuthType = None, auth_value: str | dict[str, str] | None = None, + auth_header_name: str | None = None, timeout: float | None = None, stdio_config: MCPStdioConfig | None = None, extra_headers: dict[str, str] | None = None, @@ -288,6 +292,11 @@ class MCPClient: self.auth_type: MCPAuthType = auth_type self.timeout: float = timeout if timeout is not None else MCP_CLIENT_TIMEOUT self._mcp_auth_value: str | dict[str, str] | None = None + # The one place this client decides which header its credential occupies: the operator's + # configured slot on the v1 path, or the slot the v2 resolver's auth object already owns. + # Every consumer reads this rather than re-deriving it, since each re-derivation so far + # picked up a different bug. + self._credential_slot: str | None = auth_header_name or getattr(resolved_auth, "header_name", None) self.stdio_config: MCPStdioConfig | None = stdio_config self.extra_headers: dict[str, str] | None = extra_headers self.ssl_verify: VerifyTypes | None = ssl_verify @@ -501,26 +510,33 @@ class MCPClient: else: self._mcp_auth_value = mcp_auth_value + def _header_slot(self, default: str) -> str: + return self._credential_slot or default + def _get_auth_headers(self) -> dict: """Generate authentication headers based on auth type.""" headers: Final = {} if self._mcp_auth_value: if isinstance(self._mcp_auth_value, str): if self.auth_type == MCPAuth.bearer_token: - headers["Authorization"] = f"Bearer {strip_auth_scheme(self._mcp_auth_value, 'Bearer')}" + static_bearer: Final = strip_auth_scheme(self._mcp_auth_value, "Bearer") + headers[self._header_slot("Authorization")] = f"Bearer {static_bearer}" elif self.auth_type == MCPAuth.basic: - headers["Authorization"] = f"Basic {self._mcp_auth_value}" + headers[self._header_slot("Authorization")] = f"Basic {self._mcp_auth_value}" elif self.auth_type == MCPAuth.api_key: - headers["X-API-Key"] = self._mcp_auth_value + headers[self._header_slot("X-API-Key")] = self._mcp_auth_value elif self.auth_type == MCPAuth.authorization: # This auth type means the caller owns the whole header value. - headers["Authorization"] = self._mcp_auth_value + headers[self._header_slot("Authorization")] = self._mcp_auth_value elif self.auth_type == MCPAuth.oauth2: - headers["Authorization"] = f"Bearer {strip_auth_scheme(self._mcp_auth_value, 'Bearer')}" + oauth2_bearer: Final = strip_auth_scheme(self._mcp_auth_value, "Bearer") + headers[self._header_slot("Authorization")] = f"Bearer {oauth2_bearer}" elif self.auth_type == MCPAuth.token: - headers["Authorization"] = f"token {strip_auth_scheme(self._mcp_auth_value, 'token')}" + scheme_token: Final = strip_auth_scheme(self._mcp_auth_value, "token") + headers[self._header_slot("Authorization")] = f"token {scheme_token}" elif self.auth_type == MCPAuth.oauth2_token_exchange: - headers["Authorization"] = f"Bearer {strip_auth_scheme(self._mcp_auth_value, 'Bearer')}" + exchanged_bearer: Final = strip_auth_scheme(self._mcp_auth_value, "Bearer") + headers[self._header_slot("Authorization")] = f"Bearer {exchanged_bearer}" elif isinstance(self._mcp_auth_value, dict): headers.update(self._mcp_auth_value) # Note: aws_sigv4 auth is not handled here — SigV4 requires per-request @@ -528,7 +544,14 @@ class MCPClient: # of static headers. See MCPSigV4Auth and _create_httpx_client_factory(). # update the headers with the extra headers if self.extra_headers: - headers.update(self.extra_headers) + # Mirrors _resolve_v2_auth: when the operator named a slot for the credential the + # gateway resolved, no injected header may shadow it, case-insensitively, since HTTP + # header names are. Without a configured slot the old precedence stands unchanged. + slot: Final = self._credential_slot + injected: Final = ( + without_header(self.extra_headers, slot) if slot and has_header(headers, slot) else self.extra_headers + ) + headers.update(injected or {}) return _strip_header_whitespace(headers) def _create_httpx_client_factory(self) -> Callable[..., httpx.AsyncClient]: @@ -556,12 +579,14 @@ class MCPClient: # SigV4 aws_auth. Both are None for the common case — no behavior change. fallback_auth: Final = self._resolved_auth if self._resolved_auth is not None else self._aws_auth effective_auth: Final = auth if auth is not None else fallback_auth + guard: Final = credential_redirect_hook(self.server_url, self._credential_slot) return httpx.AsyncClient( headers=headers, timeout=timeout, auth=effective_auth, verify=ssl_config, follow_redirects=True, + event_hooks={"request": [guard]} if guard else {}, ) return factory diff --git a/litellm/integrations/dotprompt/prompt_manager.py b/litellm/integrations/dotprompt/prompt_manager.py index a0d5be71392..fd0b17ba746 100644 --- a/litellm/integrations/dotprompt/prompt_manager.py +++ b/litellm/integrations/dotprompt/prompt_manager.py @@ -149,7 +149,6 @@ class PromptManager: ) self.prompts[template_id] = template except Exception: - # Optional: print(f"Error loading prompt from JSON: {template_id}") pass def _load_prompt_file(self, file_path: str | Path, prompt_id: str) -> PromptTemplate: diff --git a/litellm/integrations/otel/emitter.py b/litellm/integrations/otel/emitter.py index 244e58eddf3..101dbc6538d 100644 --- a/litellm/integrations/otel/emitter.py +++ b/litellm/integrations/otel/emitter.py @@ -146,7 +146,7 @@ class SpanEmitter: For callers that own and manage their own span lifecycle. ``tracer`` overrides the bound tracer for this span only, used for per-request multi-tenant credential routing. ``links`` records related-but-not-parent - spans (e.g. the transport span of an MCP message, per MCP semconv). + spans (e.g. the trace context an MCP client propagated in ``params._meta``). """ return (tracer or self._tracer).start_span( name, @@ -196,8 +196,8 @@ class SpanEmitter: Return the span, or ``None`` if it was deduplicated away. ``tracer`` overrides the bound tracer for this span, used for per-request routing. - ``links`` records related-but-not-parent spans (the transport span of an - MCP message). + ``links`` records related-but-not-parent spans (e.g. the trace context an + MCP client propagated in ``params._meta``). """ # LLM-call and MCP tool-call spans carry a dedup key (their request's # call id), so a sync+async double-firing coalesces. ``isinstance`` narrows diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.py index 4359b222d06..d2a32ef73b6 100644 --- a/litellm/integrations/otel/logger.py +++ b/litellm/integrations/otel/logger.py @@ -390,10 +390,10 @@ class OpenTelemetryV2(CustomLogger): MCP tool calls reach the success/failure callbacks like any other request (with ``call_type`` ``call_mcp_tool``), but they are not LLM calls and have - no ``pre_call`` carrier — so they get their own CLIENT span here. Per the MCP - semconv it parents to the trace context the client propagated in - ``params._meta`` (or starts a new root) and links the transport span, rather - than nesting under the HTTP/session span. Returns whether it handled the + no ``pre_call`` carrier — so they get their own CLIENT span here. It nests + under the transport span of the request carrying this message, and trace + context the client propagated in ``params._meta`` is recorded as a span + link (see ``resolve_mcp_span_context``). Returns whether it handled the event, so the caller skips the LLM-call path. The whole span is emitted at once (there is no boundary to open it at), deduped on the call id. """ @@ -436,9 +436,9 @@ class OpenTelemetryV2(CustomLogger): Like a tool call, listing reaches the success/failure callbacks (here with ``call_type`` ``list_mcp_tools``) with no ``pre_call`` carrier, so it gets its - own CLIENT span. Per the MCP semconv it parents to the ``params._meta`` trace - context (or starts a new root) and links the transport span, rather than - nesting under the HTTP/session span. Returns whether it handled the event so + own CLIENT span, nested under the transport span of the request carrying + this message with any ``params._meta`` trace context recorded as a span + link (see ``resolve_mcp_span_context``). Returns whether it handled the event so the caller skips the LLM-call path. """ raw_payload: Final = kwargs.get("standard_logging_object") diff --git a/litellm/integrations/otel/model/spans.py b/litellm/integrations/otel/model/spans.py index 08318f78b7c..35fc50a2a83 100644 --- a/litellm/integrations/otel/model/spans.py +++ b/litellm/integrations/otel/model/spans.py @@ -10,6 +10,8 @@ Canonical hierarchy:: │ └── DB_CALL (CLIENT) # its key/user/team lookups nest here ├── GUARDRAIL (INTERNAL) # request-lifecycle hook, sibling of LLM_CALL ├── LLM_CALL (CLIENT) + ├── MCP_TOOL_CALL (CLIENT) # nests under the POST carrying the message + ├── MCP_LIST_TOOLS (CLIENT) # (client-propagated context is a span link) └── DB_CALL (CLIENT) # e.g. the spend-log write Guardrails parent to PROXY_REQUEST, not LLM_CALL: pre/during/post-call guardrail @@ -18,14 +20,14 @@ before the LLM call even starts), so a guardrail is a sibling of the LLM call, not a child of it. The emitter parents every span to the ambient OTel context (the active server span), which matches this. -MCP spans (``MCP_TOOL_CALL``, ``MCP_LIST_TOOLS``) have two shapes, chosen at emit -time by :func:`resolve_mcp_span_context`. When the client propagates trace context -in ``params._meta`` MCP and the HTTP transport are independent contexts per the -OTel GenAI MCP semconv, so the span parents to that propagated context and records -the ``PROXY_REQUEST`` transport span as a span *link*, never a parent — the shape -this registry's ``parent=None, links=PROXY_REQUEST`` entry encodes. When nothing is -propagated (the common case) the span nests under the transport span of the request -carrying that message, so the tool call stays in one trace. +MCP spans (``MCP_TOOL_CALL``, ``MCP_LIST_TOOLS``) are parented at emit time by +:func:`resolve_mcp_span_context`: they nest under the ``PROXY_REQUEST`` transport +span of the request carrying that message, so the tool call stays in one trace. +Trace context the client propagated in ``params._meta`` (SEP-414) is recorded as +a span *link*, never the parent — a remote parent would root the span in a trace +whose root never reaches the gateway's tracing backend. Links always target that +remote client context, never a registry role, so ``SpanSpec`` declares no link +field; the concrete transport parent is resolved per message at emit time. Not every service call becomes a span — :func:`span_role_for_service` decides: @@ -85,25 +87,19 @@ class SpanSpec: role: SpanRole kind: LiteLLMSpanKind parent: SpanRole | None - links: SpanRole | None = None SPAN_REGISTRY: Final[dict[SpanRole, SpanSpec]] = { SpanRole.PROXY_REQUEST: SpanSpec(SpanRole.PROXY_REQUEST, LiteLLMSpanKind.SERVER, parent=None), SpanRole.LLM_CALL: SpanSpec(SpanRole.LLM_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST), # The proxy is an MCP client to the upstream server, so MCP spans are CLIENT - # spans. With trace context propagated in ``params._meta``, MCP and the HTTP - # transport are independent contexts (OTel GenAI MCP semconv): the span parents - # to the propagated context and records the PROXY_REQUEST transport span as a - # span *link*, never a parent — the shape ``parent=None, links=PROXY_REQUEST`` - # encodes. With nothing propagated, ``resolve_mcp_span_context`` nests the span - # under that message's transport span instead, keeping the call in one trace. - SpanRole.MCP_TOOL_CALL: SpanSpec( - SpanRole.MCP_TOOL_CALL, LiteLLMSpanKind.CLIENT, parent=None, links=SpanRole.PROXY_REQUEST - ), - SpanRole.MCP_LIST_TOOLS: SpanSpec( - SpanRole.MCP_LIST_TOOLS, LiteLLMSpanKind.CLIENT, parent=None, links=SpanRole.PROXY_REQUEST - ), + # spans. ``resolve_mcp_span_context`` nests them under the PROXY_REQUEST + # transport span of the request carrying that message (resolved per message at + # emit time), keeping the call in one trace. Trace context the client + # propagated in ``params._meta`` becomes a span *link* to that remote context, + # which is not a registry role, so ``SpanSpec`` has no link field. + SpanRole.MCP_TOOL_CALL: SpanSpec(SpanRole.MCP_TOOL_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST), + SpanRole.MCP_LIST_TOOLS: SpanSpec(SpanRole.MCP_LIST_TOOLS, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST), SpanRole.GUARDRAIL: SpanSpec(SpanRole.GUARDRAIL, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST), SpanRole.DB_CALL: SpanSpec(SpanRole.DB_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST), SpanRole.SERVICE: SpanSpec(SpanRole.SERVICE, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST), @@ -209,8 +205,8 @@ def service_span_name(data: "ServiceSpanData") -> str: def root_roles() -> list[SpanRole]: - """Roles with no in-process parent. They start a new trace unless they adopt a - remote parent (e.g. an MCP span joining the client's propagated context).""" + """Roles with no in-process parent, i.e. they start a new trace (only the + instrumentor-owned ``PROXY_REQUEST`` server span today).""" return [role for role, spec in SPAN_REGISTRY.items() if spec.parent is None] @@ -227,8 +223,6 @@ def validate_registry( raise ValueError(f"SPAN_REGISTRY[{role}] has mismatched role {spec.role}") if spec.parent is not None and spec.parent not in reg: raise ValueError(f"span role {role} declares unknown parent {spec.parent}") - if spec.links is not None and spec.links not in reg: - raise ValueError(f"span role {role} declares unknown link target {spec.links}") missing: Final = [role for role in SpanRole if role not in reg] if missing: raise ValueError(f"SPAN_REGISTRY is missing roles: {missing}") diff --git a/litellm/integrations/otel/plumbing/context.py b/litellm/integrations/otel/plumbing/context.py index 19b36c0b967..159a84b121f 100644 --- a/litellm/integrations/otel/plumbing/context.py +++ b/litellm/integrations/otel/plumbing/context.py @@ -57,8 +57,8 @@ def request_root_span() -> "Span | None": # The W3C trace-context carrier (``traceparent``/``tracestate``/``baggage``) the # MCP client propagated in the current request's ``params._meta``. The MCP gateway -# sets it per message so the MCP span can parent to the client's span rather than -# to the transport. A ``ContextVar`` because, like the root-span anchor, it must +# sets it per message so the MCP span can record the client's span as a span +# link. A ``ContextVar`` because, like the root-span anchor, it must # ride the request task and be readable by the inline success-logging callback. _mcp_message_trace_carrier: Final["ContextVar[Mapping[str, str] | None]"] = ContextVar( "litellm_otel_mcp_message_trace_carrier", default=None @@ -148,10 +148,10 @@ def _mcp_transport_span_context() -> "SpanContext | None": Prefers the transport the gateway published for this specific message; falls back to the ambient request anchor for paths that emit an MCP span on the - request task itself (the REST MCP endpoints, the SDK). Parenting and linking - only need the immutable context, and unlike ``mcp_message_transport_span`` they - stay correct against a transport that has already finished, so this does not - require the span to still be recording. + request task itself (the REST MCP endpoints). Parenting needs only the + immutable context, and unlike ``mcp_message_transport_span`` it stays correct + against a transport that has already finished, so this does not require the + span to still be recording. """ published: Final = _mcp_message_transport_span.get() if published is not None: @@ -222,25 +222,31 @@ def resolve_mcp_span_context( ) -> "tuple[Context, tuple[Link, ...]]": """Parent context + links for an MCP message span. + The span always nests under the transport span of the request carrying this + message, so a tool call and the ``POST`` that carried it stay in one trace. + The transport comes from :func:`_mcp_transport_span_context`, which is the + *current message's* POST rather than whatever request happened to open the + session, so a long-lived session does not glue every message under its first + request. + When the client propagates W3C trace context in the request's ``params._meta`` - (SEP-414), MCP and the underlying transport are independent lifecycles — one - streamable-HTTP session multiplexes many messages, and the client's own span is - the truthful parent. So, per the OTel GenAI MCP semconv: + (SEP-414), that remote context is recorded as a span *link*, never the parent. + The OTel GenAI MCP semconv prefers the inverse (remote parent, transport link), + but the gateway's tracing backend only ever receives the gateway's half of such + a trace: parenting into the client's trace id roots the span in a trace whose + root span never reaches the backend, so the span is unreachable from the trace + view and the transport transaction shows a dangling link (observed with + clients that propagate synthetic trace ids). Anchoring to the gateway's own + request and linking the client's context keeps every trace renderable while + preserving the client-side correlation. - * parent to the trace context the client propagated (a *remote* parent), and - * record the transport span as a *link*, never the parent. - - Almost no client implements SEP-414 yet, so in practice nothing is propagated. - Rooting the span there splits a single tool call into two disconnected traces - joined only by a link, which is how it surfaces in APM: the ``POST`` transaction - and the ``tools/call`` span share no trace. With no remote parent to honor, - parent to the transport span of the request carrying this message instead, so - the call stays in one trace; no link is added since the transport is now the - real parent. The transport comes from :func:`_mcp_transport_span_context`, which - is the *current message's* POST rather than whatever request happened to open - the session, so a long-lived session does not glue every message under its - first request. With neither a remote parent nor a transport the returned context - carries no span and the span legitimately starts its own root trace. + With no transport at all the span starts its own root trace, still carrying + the link — the client context is only ever a link, so this event keeps one + shape everywhere. Both returned contexts are built on an explicitly empty + base, so ambient (stale session) state can never leak in, and the span + inherits the transport's sampling decision exactly like every other + request-level span — a client's sampled flag neither forces nor suppresses + recording. Only trace context (``traceparent``/``tracestate``) is extracted, never the client's W3C Baggage: ``params._meta`` is caller-controlled, and the otel @@ -251,13 +257,12 @@ def resolve_mcp_span_context( never fall through to the ambient (stale session) span. """ source: Final = carrier if carrier is not None else _mcp_message_trace_carrier.get() - parent: Final = _PROPAGATOR.extract(dict(source or {}), context=Context()) + propagated: Final = get_current_span(_PROPAGATOR.extract(dict(source or {}), context=Context())) + links: Final = (Link(propagated.get_span_context()),) if is_recordable_span(propagated) else () transport: Final = _mcp_transport_span_context() - if is_recordable_span(get_current_span(parent)): - return parent, (Link(transport),) if transport is not None else () - if transport is not None: - return context_from_span(NonRecordingSpan(transport)), () - return parent, () + if transport is None: + return Context(), links + return context_from_span(NonRecordingSpan(transport), context=Context()), links def is_recordable_span(obj: object) -> bool: diff --git a/litellm/integrations/otel/plumbing/routing.py b/litellm/integrations/otel/plumbing/routing.py index d2457b9ce57..dc2db823a8d 100644 --- a/litellm/integrations/otel/plumbing/routing.py +++ b/litellm/integrations/otel/plumbing/routing.py @@ -2,12 +2,13 @@ When a request carries team/key vendor credentials in ``standard_callback_dynamic_params``, or the key/team config resolved at auth -names a destination project, its spans must export through a -``TracerProvider`` whose OTLP headers carry those credentials / that project. -``TenantTracerCache`` builds and caches one provider per distinct -(credentials, project) pair, and otherwise hands back the logger's default -tracer. This lets a single logger fan requests out to many tenants without -needing a logger per tenant. +names a destination project or a service name, its spans must export through a +``TracerProvider`` whose OTLP headers carry those credentials / that project, +or whose Resource carries that ``service.name``. ``TenantTracerCache`` builds +and caches one provider per distinct (credentials, project, service name) +tuple, and otherwise hands back the logger's default tracer. This lets a +single logger fan requests out to many tenants without needing a logger per +tenant. """ import threading @@ -22,6 +23,7 @@ from opentelemetry.sdk.trace import TracerProvider from opentelemetry.trace import Tracer from litellm._logging import verbose_logger +from litellm.constants import OTEL_SERVICE_NAME_METADATA_KEYS from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config from litellm.integrations.otel.plumbing.providers import ( build_tracer_provider, @@ -65,8 +67,30 @@ _MAX_RETIRED_PROVIDERS: Final = 64 _HeaderItems: TypeAlias = tuple[tuple[str, str], ...] +_RouteKey: TypeAlias = tuple[_HeaderItems, _HeaderItems, str | None, str | None] + _NO_HEADERS: Final[Mapping[str, str]] = MappingProxyType({}) +#: Key/team config fields naming the Resource ``service.name``, highest +#: precedence first. Read only from ``user_api_key_auth_metadata`` (the config +#: the proxy resolved at auth), never from client-supplied request metadata: +#: the service name picks the dataset/service traces land in (Honeycomb routes +#: datasets by it), so a caller must not be able to choose one. +_SERVICE_NAME_KEYS: Final = OTEL_SERVICE_NAME_METADATA_KEYS + + +def tenant_service_name(auth_metadata: Mapping[str, str] | None) -> str | None: + """The per-request ``service.name`` override for this key/team, if any. + + ``None`` keeps the env-configured default (``OTEL_SERVICE_NAME``). + """ + if not auth_metadata: + return None + return next( + (stripped for key in _SERVICE_NAME_KEYS if (stripped := (auth_metadata.get(key) or "").strip())), + None, + ) + def _shutdown_provider(provider: TracerProvider) -> None: """Flush + stop an evicted provider's processors (reclaims their threads). @@ -116,7 +140,7 @@ class TenantRoute: class TenantTracerCache: - """Credential/project-scoped ``TracerProvider`` cache keyed by the routing headers.""" + """Tenant-scoped ``TracerProvider`` cache keyed by routing headers and service name.""" def __init__( self, @@ -131,7 +155,7 @@ class TenantTracerCache: # thread-pool workers concurrently with the event loop, so cache # updates, span counts, and retirement must be atomic. self._lock: Final = threading.Lock() - self._providers: OrderedDict[tuple[_HeaderItems, _HeaderItems, str | None], TracerProvider] = ( + self._providers: OrderedDict[_RouteKey, TracerProvider] = ( OrderedDict() # mutable-ok: bounded LRU; eviction needs in-place ordered mutation ) self._open_span_counts: dict[TracerProvider, int] = {} # mutable-ok: live refcount state @@ -172,10 +196,11 @@ class TenantTracerCache: ) -> TenantRoute: """Return the tracer (and trace-detachment flag) for this request. - Use ``default`` unless the request's dynamic credentials or its key/team - project require a scoped tracer, in which case build (or reuse) one. The - cache is a bounded LRU: the least-recently-used provider is flushed and - shut down on overflow so its exporter threads don't accumulate. + Use ``default`` unless the request's dynamic credentials, its key/team + project, or its key/team service name require a scoped tracer, in + which case build (or reuse) one. The cache is a bounded LRU: the + least-recently-used provider is flushed and shut down on overflow so + its exporter threads don't accumulate. A routed provider is returned already held — its open-span count is incremented in the same critical section as the cache update — so a @@ -184,7 +209,8 @@ class TenantTracerCache: """ credential_headers: Final = dynamic_otlp_headers(self._callback_name, dynamic_params) or _NO_HEADERS project_headers: Final = self._project_headers(auth_metadata) - if not credential_headers and not project_headers: + service_name: Final = tenant_service_name(auth_metadata) + if not credential_headers and not project_headers and service_name is None: return TenantRoute(tracer=default, detached=False) # A fixed per-integration region endpoint (New Relic us/eu), never a # caller-supplied host; ``None`` keeps the preset's own endpoint. @@ -193,9 +219,12 @@ class TenantTracerCache: tuple(sorted(credential_headers.items())), tuple(sorted(project_headers.items())), endpoint, + service_name, ) with self._lock: - provider: Final = self._cached_provider_locked(cache_key, credential_headers, project_headers, endpoint) + provider: Final = self._cached_provider_locked( + cache_key, credential_headers, project_headers, endpoint, service_name + ) self._open_span_counts[provider] = self._open_span_counts.get(provider, 0) + 1 evicted: Final = self._evicted_on_overflow_locked() if evicted is not None: @@ -208,16 +237,19 @@ class TenantTracerCache: def _cached_provider_locked( self, - cache_key: tuple[_HeaderItems, _HeaderItems, str | None], + cache_key: _RouteKey, credential_headers: Mapping[str, str], project_headers: Mapping[str, str], endpoint: str | None, + service_name: str | None, ) -> TracerProvider: cached: Final = self._providers.get(cache_key) if cached is not None: self._providers.move_to_end(cache_key) return cached - built: Final = build_tracer_provider(self._routed_config(credential_headers, project_headers, endpoint)) + built: Final = build_tracer_provider( + self._routed_config(credential_headers, project_headers, endpoint, service_name) + ) self._providers[cache_key] = built return built @@ -267,6 +299,7 @@ class TenantTracerCache: credential_headers: Mapping[str, str], project_headers: Mapping[str, str], endpoint: str | None = None, + service_name: str | None = None, ) -> OpenTelemetryV2Config: """Clone the config, rewriting headers on the callback's own exporter. @@ -285,7 +318,10 @@ class TenantTracerCache: self._routed_exporter(spec, credential_headers, project_headers, endpoint) for spec in self._config.exporters ] - return self._config.model_copy(update={"exporters": exporters}) + update: Final = ( + {"exporters": exporters} if service_name is None else {"exporters": exporters, "service_name": service_name} + ) + return self._config.model_copy(update=update) def _routed_exporter( self, diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py index dc245d42862..70374f87b99 100644 --- a/litellm/litellm_core_utils/exception_mapping_utils.py +++ b/litellm/litellm_core_utils/exception_mapping_utils.py @@ -2341,6 +2341,7 @@ def exception_type( litellm_response_headers: Final = _get_response_headers(original_exception=original_exception) try: error_str = redact_string(str(original_exception)) if _ENABLE_SECRET_REDACTION else str(original_exception) + extra_information = "" if model or custom_llm_provider: if hasattr(original_exception, "message"): error_str = ( @@ -2357,7 +2358,6 @@ def exception_type( # Common Extra information needed for all providers # We pass num retries, api_base, vertex_deployment etc to the exception here ################################################################################ - extra_information = "" try: _api_base: Final = litellm.get_api_base(model=model, optional_params=extra_kwargs) messages: Final = litellm.get_first_chars_messages(kwargs=completion_kwargs) diff --git a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py index 9a2c4e244fb..9250b92e268 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py +++ b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py @@ -7,7 +7,9 @@ from typing import Any, Final, Literal import litellm from litellm.constants import OPENAI_FILE_SEARCH_COST_PER_1K_CALLS -from litellm.litellm_core_utils.llm_cost_calc.utils import get_web_search_requests +from litellm.litellm_core_utils.llm_cost_calc.utils import ( + get_web_search_requests_from_usage, +) from litellm.types.llms.openai import ( FileSearchTool, ResponsesAPIResponse, @@ -368,7 +370,7 @@ class StandardBuiltInToolCostTracking: get_anthropic_web_search_requests_from_response, ) - if usage is not None and (get_web_search_requests(getattr(usage, "server_tool_use", None)) is not None): + if usage is not None and (get_web_search_requests_from_usage(usage) is not None): return usage web_search_requests: Final = get_anthropic_web_search_requests_from_response(response_object) if web_search_requests is None: @@ -416,7 +418,7 @@ class StandardBuiltInToolCostTracking: # Anthropic Claude (direct API and Vertex AI) uses server_tool_use.web_search_requests. # Without this check, Claude ModelResponse always falls through to return False # and _handle_web_search_cost() is never called. - if hasattr(usage, "server_tool_use") and get_web_search_requests(usage.server_tool_use) is not None: + if get_web_search_requests_from_usage(usage) is not None: return True # xAI reports usage.server_side_tool_usage_details.web_search_calls; a searched # answer with no url_citation annotations has no other chat-path signal @@ -429,16 +431,12 @@ class StandardBuiltInToolCostTracking: response_object=response_object, output_type="web_search_call" ) elif usage is not None: - if ( - hasattr(usage, "server_tool_use") - and get_web_search_requests(usage.server_tool_use) is not None - or ( - hasattr(usage, "prompt_tokens_details") - and usage.prompt_tokens_details is not None - and isinstance(usage.prompt_tokens_details, PromptTokensDetailsWrapper) - and hasattr(usage.prompt_tokens_details, "web_search_requests") - and usage.prompt_tokens_details.web_search_requests is not None - ) + if get_web_search_requests_from_usage(usage) is not None or ( + hasattr(usage, "prompt_tokens_details") + and usage.prompt_tokens_details is not None + and isinstance(usage.prompt_tokens_details, PromptTokensDetailsWrapper) + and hasattr(usage.prompt_tokens_details, "web_search_requests") + and usage.prompt_tokens_details.web_search_requests is not None ): return True if _usage_reports_server_side_web_search_calls(usage): diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py index 9d782cf7a4d..bdbaee00c19 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/utils.py +++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py @@ -92,6 +92,16 @@ def get_web_search_requests(server_tool_use: Any) -> int | None: return getattr(server_tool_use, "web_search_requests", None) +def get_web_search_requests_from_usage(usage: Usage) -> int | None: + """Read ``web_search_requests`` from a ``Usage``'s ``server_tool_use``. + + ``Usage`` deletes unset optional fields from ``__dict__`` (see + ``SafeAttributeModel``), so direct attribute access can raise + ``AttributeError``; ``getattr`` with a default is required here. + """ + return get_web_search_requests(getattr(usage, "server_tool_use", None)) + + def _is_above_128k(tokens: float) -> bool: if tokens > 128000: return True diff --git a/litellm/litellm_core_utils/realtime_streaming.py b/litellm/litellm_core_utils/realtime_streaming.py index 10056d64a20..9125ed6e70a 100644 --- a/litellm/litellm_core_utils/realtime_streaming.py +++ b/litellm/litellm_core_utils/realtime_streaming.py @@ -330,6 +330,24 @@ class RealTimeStreaming: except (AttributeError, TypeError): pass + def _flush_unbilled_transcription_usage(self) -> None: + if self.provider_config is None: + return + usage: Final = self.provider_config.unbilled_usage_on_session_close(self.model) + if usage is None: + return + flush_event: Final = ( + cast( # cast-ok: usage-only partial event, the same shape _capture_transcription_usage logs + OpenAIRealtimeEvents, + { + "type": "conversation.item.input_audio_transcription.completed", + "usage": usage, + }, + ) + ) + self.store_message(flush_event) + self._capture_transcription_usage(flush_event) + def _collect_tool_calls_from_response_done(self, event_obj: dict | OpenAIRealtimeEvents) -> None: """Extract function_call items from response.done events for spend logging.""" try: @@ -955,6 +973,7 @@ class RealTimeStreaming: transcript = event.get("transcript", "") self._collect_user_input_from_backend_event(cast(dict, event)) self.store_message(event_str) + self._capture_transcription_usage(event) await self._send_event_to_client(event, event_str) blocked = await self.run_realtime_guardrails( cast(str, transcript), @@ -1068,6 +1087,7 @@ class RealTimeStreaming: except Exception as e: verbose_logger.exception("Error in backend to client send messages: %s", e) finally: + self._flush_unbilled_transcription_usage() await self.log_messages() @staticmethod diff --git a/litellm/llms/anthropic/cost_calculation.py b/litellm/llms/anthropic/cost_calculation.py index ec6c480efcc..95615b8e748 100644 --- a/litellm/llms/anthropic/cost_calculation.py +++ b/litellm/llms/anthropic/cost_calculation.py @@ -10,7 +10,7 @@ from pydantic import BaseModel, ValidationError from litellm.litellm_core_utils.llm_cost_calc.utils import ( generic_cost_per_token, get_provider_specific_geo_multiplier, - get_web_search_requests, + get_web_search_requests_from_usage, ) if TYPE_CHECKING: @@ -104,7 +104,7 @@ def get_cost_for_anthropic_web_search( if usage is None: return 0.0 - web_search_requests: Final = get_web_search_requests(getattr(usage, "server_tool_use", None)) + web_search_requests: Final = get_web_search_requests_from_usage(usage) if web_search_requests is None: return 0.0 diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py index d7b527824ea..3597b8c329e 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py @@ -1358,12 +1358,10 @@ class LiteLLMAnthropicMessagesAdapter: @classmethod def _get_web_search_request_count(cls, usage: Usage) -> int: from litellm.litellm_core_utils.llm_cost_calc.utils import ( - get_web_search_requests, + get_web_search_requests_from_usage, ) - from_server_tool_use: Final = cls._positive_int( - get_web_search_requests(getattr(usage, "server_tool_use", None)) - ) + from_server_tool_use: Final = cls._positive_int(get_web_search_requests_from_usage(usage)) if from_server_tool_use > 0: return from_server_tool_use return cls._first_positive_prompt_tokens_detail_value(usage, ("web_search_requests",)) diff --git a/litellm/llms/base_llm/realtime/transformation.py b/litellm/llms/base_llm/realtime/transformation.py index 26c189504df..cfcde7c6e9e 100644 --- a/litellm/llms/base_llm/realtime/transformation.py +++ b/litellm/llms/base_llm/realtime/transformation.py @@ -5,6 +5,7 @@ import httpx from litellm.types.llms.openai import OpenAIRealtimeStreamSessionEvents from litellm.types.realtime import ( + RealtimeInputAudioTranscriptionUsage, RealtimeResponseTransformInput, RealtimeResponseTypedDict, ) @@ -70,6 +71,9 @@ class BaseRealtimeConfig(ABC): def session_configuration_request(self, model: str) -> str | None: # message sent to setup the realtime session return None + def unbilled_usage_on_session_close(self, model: str) -> RealtimeInputAudioTranscriptionUsage | None: + return None + def transform_session_created_event( self, model: str, diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.py index db6f2c0d491..4332848e545 100644 --- a/litellm/llms/bedrock/base_aws_llm.py +++ b/litellm/llms/bedrock/base_aws_llm.py @@ -1434,9 +1434,12 @@ class BaseAWSLLM: data: str | bytes, headers: dict, api_key: str | None = None, + supports_bearer_token: bool = True, ) -> AWSPreparedRequest: - if api_key is not None: - aws_bearer_token: str | None = api_key + if not supports_bearer_token: + aws_bearer_token: str | None = None + elif api_key is not None: + aws_bearer_token = api_key else: aws_bearer_token = get_secret_str("AWS_BEARER_TOKEN_BEDROCK") diff --git a/litellm/llms/bedrock/rerank/handler.py b/litellm/llms/bedrock/rerank/handler.py index a2a1acec80c..4860c99268e 100644 --- a/litellm/llms/bedrock/rerank/handler.py +++ b/litellm/llms/bedrock/rerank/handler.py @@ -138,11 +138,6 @@ class BedrockRerankHandler(BaseAWSLLM): data: dict, optional_params: dict, ) -> BedrockPreparedRequest: - try: - from botocore.auth import SigV4Auth - from botocore.awsrequest import AWSRequest - except ImportError: - raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") boto3_credentials_info: Final = self._get_boto_credentials_from_optional_params(optional_params, model) ### SET RUNTIME ENDPOINT ### @@ -153,24 +148,21 @@ class BedrockRerankHandler(BaseAWSLLM): ) proxy_endpoint_url = proxy_endpoint_url.replace("bedrock-runtime", "bedrock-agent-runtime") proxy_endpoint_url = f"{proxy_endpoint_url}/rerank" - sigv4: Final = SigV4Auth( - boto3_credentials_info.credentials, - "bedrock", - boto3_credentials_info.aws_region_name, - ) - # Make POST Request - body: Final = json.dumps(data).encode("utf-8") + body: Final = json.dumps(data).encode("utf-8") headers = {"Content-Type": "application/json"} if extra_headers is not None: headers = {"Content-Type": "application/json", **extra_headers} - request: Final = AWSRequest(method="POST", url=proxy_endpoint_url, data=body, headers=headers) - sigv4.add_auth(request) - if ( - extra_headers is not None and "Authorization" in extra_headers - ): # prevent sigv4 from overwriting the auth header - request.headers["Authorization"] = extra_headers["Authorization"] - prepped: Final = request.prepare() + + prepped: Final = self.get_request_headers( + credentials=boto3_credentials_info.credentials, + aws_region_name=boto3_credentials_info.aws_region_name, + extra_headers=extra_headers, + endpoint_url=proxy_endpoint_url, + data=body, + headers=headers, + supports_bearer_token=False, + ) return BedrockPreparedRequest( endpoint_url=proxy_endpoint_url, diff --git a/litellm/llms/gemini/audio_transcription/__init__.py b/litellm/llms/gemini/audio_transcription/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/litellm/llms/gemini/audio_transcription/transformation.py b/litellm/llms/gemini/audio_transcription/transformation.py new file mode 100644 index 00000000000..8b7733fa3c8 --- /dev/null +++ b/litellm/llms/gemini/audio_transcription/transformation.py @@ -0,0 +1,250 @@ +import base64 +from collections.abc import Mapping, Sequence +from typing import Final + +from httpx import Headers, Response + +from litellm.litellm_core_utils.audio_utils.utils import ( + normalize_transcription_language_to_bcp47, + process_audio_file, +) +from litellm.llms.base_llm.audio_transcription.transformation import ( + AudioTranscriptionRequestData, + BaseAudioTranscriptionConfig, +) +from litellm.llms.base_llm.chat.transformation import BaseLLMException +from litellm.llms.gemini.common_utils import GeminiError, GeminiModelInfo +from litellm.types.llms.gemini_audio_transcription import ( + GeminiTranscriptionAudioInput, + GeminiTranscriptionConfig, + GeminiTranscriptionInteractionRequest, + GeminiTranscriptionInteractionResponse, + GeminiTranscriptionWordAnnotation, +) +from litellm.types.llms.openai import ( + AllMessageValues, + OpenAIAudioTranscriptionOptionalParams, +) +from litellm.types.utils import ( + FileTypes, + TranscriptionResponse, + TranscriptionUsageInputTokenDetailsObject, + TranscriptionUsageTokensObject, +) + +INTERACTIONS_API_REVISION: Final = "2026-05-20" +WORD_INFO_ANNOTATION_TYPE: Final = "word_info" + + +class GeminiAudioTranscriptionConfig(BaseAudioTranscriptionConfig): + """ + Maps OpenAI /v1/audio/transcriptions onto the Gemini Interactions API + (POST /v1beta/interactions) for transcription models like + gemini-3.5-transcribe. https://ai.google.dev/gemini-api/docs/transcribe + """ + + def get_supported_openai_params( + self, model: str + ) -> list[OpenAIAudioTranscriptionOptionalParams]: # mutable-ok: BaseAudioTranscriptionConfig signature + return ["language", "response_format", "timestamp_granularities"] # mutable-ok: base contract returns a list + + def map_openai_params( + self, + non_default_params: Mapping[str, object], + optional_params: Mapping[str, object], + model: str, + drop_params: bool, + ) -> dict: # mutable-ok: BaseAudioTranscriptionConfig signature + supported_params: Final = frozenset(self.get_supported_openai_params(model)) + accepted: Final = tuple((k, v) for k, v in non_default_params.items() if k in supported_params) + return dict((*optional_params.items(), *accepted)) # mutable-ok: base contract returns a plain dict + + def get_error_class( + self, + error_message: str, + status_code: int, + headers: dict | Headers, # mutable-ok: base signature and BaseLLMException take dict | Headers + ) -> BaseLLMException: + return GeminiError(status_code=status_code, message=error_message, headers=headers) + + def validate_environment( + self, + headers: Mapping[str, str], + model: str, + messages: Sequence[AllMessageValues], + optional_params: Mapping[str, object], + litellm_params: Mapping[str, object], + api_key: str | None = None, + api_base: str | None = None, + ) -> dict: # mutable-ok: BaseAudioTranscriptionConfig signature + resolved_api_key: Final = GeminiModelInfo.get_api_key(api_key) + if not resolved_api_key: + raise GeminiError( + status_code=401, + message="Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable.", + ) + return { # mutable-ok: the http handler passes these headers straight to httpx + **headers, + "Content-Type": "application/json", + "x-goog-api-key": resolved_api_key, + "Api-Revision": INTERACTIONS_API_REVISION, + } + + def get_complete_url( + self, + api_base: str | None, + api_key: str | None, + model: str, + optional_params: Mapping[str, object], + litellm_params: Mapping[str, object], + stream: bool | None = None, + ) -> str: + resolved_api_base: Final = GeminiModelInfo.get_api_base(api_base) + return f"{resolved_api_base}/v1beta/interactions" + + def transform_audio_transcription_request( + self, + model: str, + audio_file: FileTypes, + optional_params: Mapping[str, object], + litellm_params: Mapping[str, object], + ) -> AudioTranscriptionRequestData: + processed_audio: Final = process_audio_file(audio_file) + audio_input: Final = GeminiTranscriptionAudioInput( + type="audio", + data=base64.b64encode(processed_audio.file_content).decode("utf-8"), + mime_type=processed_audio.content_type, + ) + request: Final = _build_interaction_request( + model=model, + audio_input=audio_input, + transcription_config=_build_transcription_config(optional_params), + ) + return AudioTranscriptionRequestData(data=dict(request)) # mutable-ok: AudioTranscriptionRequestData wants dict + + def transform_audio_transcription_response( + self, + raw_response: Response, + ) -> TranscriptionResponse: + try: + response_json: Final = raw_response.json() + except ValueError: + raise GeminiError( + status_code=raw_response.status_code, + message=f"Received non-JSON response from Gemini Interactions API: {raw_response.text}", + ) + parsed: Final = GeminiTranscriptionInteractionResponse.model_validate(response_json) + if parsed.status != "completed": + raise GeminiError( + status_code=raw_response.status_code, + message=f"Gemini transcription interaction did not complete (status={parsed.status}): {raw_response.text}", + ) + text_contents: Final = tuple( + content + for step in parsed.steps + for content in step.content + if content.type == "text" and content.text is not None + ) + response: Final = TranscriptionResponse(text=" ".join(content.text or "" for content in text_contents)) + response["task"] = "transcribe" + words: Final = tuple( + word + for content in text_contents + for annotation in content.annotations + if (word := _annotation_to_word(annotation)) is not None + ) + if words: + response["words"] = list(words) # mutable-ok: verbose_json words is a JSON array + last_word_end: Final = words[-1].get("end") + if last_word_end is not None: + response["duration"] = last_word_end + if parsed.usage is not None: + audio_tokens: Final = sum( + by_modality.tokens + for by_modality in parsed.usage.input_tokens_by_modality + if by_modality.modality == "audio" + ) + response.usage = TranscriptionUsageTokensObject( + type="tokens", + input_tokens=parsed.usage.total_input_tokens, + output_tokens=parsed.usage.total_output_tokens, + total_tokens=parsed.usage.total_tokens, + input_token_details=TranscriptionUsageInputTokenDetailsObject( + audio_tokens=audio_tokens, + text_tokens=parsed.usage.total_input_tokens - audio_tokens, + ), + ) + return response + + +_EMPTY_TRANSCRIPTION_CONFIG: Final[GeminiTranscriptionConfig] = {} +_WORD_TIMESTAMP_CONFIG: Final[GeminiTranscriptionConfig] = { + "mode": { + "type": "verbatim", + "timestamp_granularities": ("word",), + "diarization_mode": "speaker", + }, +} + + +def _build_interaction_request( + model: str, + audio_input: GeminiTranscriptionAudioInput, + transcription_config: GeminiTranscriptionConfig, +) -> GeminiTranscriptionInteractionRequest: + if not transcription_config: + bare_request: Final[GeminiTranscriptionInteractionRequest] = { + "model": model.removeprefix("gemini/"), + "input": (audio_input,), + } + return bare_request + configured_request: Final[GeminiTranscriptionInteractionRequest] = { + "model": model.removeprefix("gemini/"), + "input": (audio_input,), + "generation_config": {"transcription_config": transcription_config}, + } + return configured_request + + +def _language_config(language: object) -> GeminiTranscriptionConfig: + if not isinstance(language, str) or not language: + return _EMPTY_TRANSCRIPTION_CONFIG + language_config: Final[GeminiTranscriptionConfig] = { + "language_codes": (normalize_transcription_language_to_bcp47(language),), + } + return language_config + + +def _timestamp_config(timestamp_granularities: object) -> GeminiTranscriptionConfig: + if isinstance(timestamp_granularities, list) and "word" in timestamp_granularities: + return _WORD_TIMESTAMP_CONFIG + return _EMPTY_TRANSCRIPTION_CONFIG + + +def _build_transcription_config(optional_params: Mapping[str, object]) -> GeminiTranscriptionConfig: + transcription_config: Final[GeminiTranscriptionConfig] = { + **_language_config(optional_params.get("language")), + **_timestamp_config(optional_params.get("timestamp_granularities")), + } + return transcription_config + + +def _annotation_to_word(annotation: GeminiTranscriptionWordAnnotation) -> Mapping[str, str | float] | None: + if annotation.type != WORD_INFO_ANNOTATION_TYPE or annotation.text is None: + return None + entries: Final = ( + ("word", annotation.text), + ("start", _parse_offset_seconds(annotation.start_offset)), + ("end", _parse_offset_seconds(annotation.end_offset)), + ("speaker", annotation.speaker), + ) + return {key: value for key, value in entries if value is not None} # mutable-ok: word entries serialize to JSON + + +def _parse_offset_seconds(offset: str | None) -> float | None: + if offset is None or not offset.endswith("s"): + return None + try: + return float(offset[:-1]) + except ValueError: + return None diff --git a/litellm/llms/gemini/cost_calculator.py b/litellm/llms/gemini/cost_calculator.py index 52285af1f5f..b82103b0ff8 100644 --- a/litellm/llms/gemini/cost_calculator.py +++ b/litellm/llms/gemini/cost_calculator.py @@ -39,7 +39,9 @@ def cost_per_web_search_request(usage: "Usage", model_info: "ModelInfo") -> floa ``model_info`` when available, falling back to $0.035 for models not yet updated in the pricing JSON. """ - from litellm.litellm_core_utils.llm_cost_calc.utils import get_web_search_requests + from litellm.litellm_core_utils.llm_cost_calc.utils import ( + get_web_search_requests_from_usage, + ) from litellm.types.utils import PromptTokensDetailsWrapper _DEFAULT_COST: Final = 35e-3 @@ -57,7 +59,7 @@ def cost_per_web_search_request(usage: "Usage", model_info: "ModelInfo") -> floa ) else None ) - requests_from_server_tool_use: Final = get_web_search_requests(getattr(usage, "server_tool_use", None)) + requests_from_server_tool_use: Final = get_web_search_requests_from_usage(usage) number_of_web_search_requests: Final = requests_from_prompt_details or requests_from_server_tool_use or 0 billing_mode: Final = model_info.get("web_search_billing_unit") or "per_prompt" diff --git a/litellm/llms/gemini/realtime/transformation.py b/litellm/llms/gemini/realtime/transformation.py index 51801e91356..367619db37d 100644 --- a/litellm/llms/gemini/realtime/transformation.py +++ b/litellm/llms/gemini/realtime/transformation.py @@ -4,7 +4,7 @@ This file contains the transformation logic for the Gemini realtime API. import json from collections import OrderedDict -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from typing import Any, Final, cast import litellm @@ -53,6 +53,7 @@ from litellm.types.llms.vertex_ai import ( ) from litellm.types.realtime import ( ALL_DELTA_TYPES, + RealtimeInputAudioTranscriptionUsage, RealtimeModalityResponseTransformOutput, RealtimeResponseTransformInput, RealtimeResponseTypedDict, @@ -95,6 +96,18 @@ def _gemini_live_speech_config(voice: object) -> Mapping[str, object] | None: return VertexGeminiConfig()._map_audio_params({"voice": voice}) +# Google bills Live transcription at an estimated 25 audio tokens/sec of input and +# 175 text tokens/min of output (ai.google.dev/gemini-api/docs/pricing). +GEMINI_LIVE_TRANSCRIBE_AUDIO_TOKENS_PER_SECOND: Final = 25 +GEMINI_LIVE_TRANSCRIBE_OUTPUT_TEXT_TOKENS_PER_MINUTE: Final = 175 +PCM16_INPUT_AUDIO_BYTES_PER_SECOND: Final = 48000 + + +def _base64_decoded_byte_count(data: str) -> int: + padding: Final = 2 if data.endswith("==") else 1 if data.endswith("=") else 0 + return max(len(data) * 3 // 4 - padding, 0) + + class GeminiRealtimeConfig(BaseRealtimeConfig): _TOOL_CALL_ID_TO_NAME_MAX = 256 # LRU cap for call_id→name mapping @@ -104,6 +117,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): # Gemini Live sometimes emits usageMetadata in a standalone frame between # turns; buffer it here so the next response.done carries the token counts. self._pending_usage_metadata: dict | None = None + self._unbilled_input_audio_bytes: int = 0 def is_setup_message(self, msg_obj: dict) -> bool: return "setup" in msg_obj @@ -384,17 +398,25 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): return bool(entry.get("gemini_native_audio") or entry.get("gemini_audio_only_live")) @staticmethod - def _coerce_response_modalities(model: str, modalities: list[Any]) -> list[str]: - """Map unsupported TEXT responseModalities to AUDIO for audio-only Live models.""" - normalized: Final = [ + def _is_text_only_live_model(model: str) -> bool: + return GeminiRealtimeConfig._model_cost_entry(model).get("mode") == "audio_transcription" + + @staticmethod + def _default_response_modality(model: str) -> GeminiResponseModalities: + return "TEXT" if GeminiRealtimeConfig._is_text_only_live_model(model) else "AUDIO" + + @staticmethod + def _coerce_response_modalities(model: str, modalities: Sequence[Any]) -> tuple[str, ...]: + """Swap responseModalities a Live model cannot produce: TEXT to AUDIO for + audio-only models, AUDIO to TEXT for text-only ones (e.g. transcribe-live).""" + normalized: Final = tuple( modality.upper() if isinstance(modality, str) else str(modality).upper() for modality in modalities - ] - if not GeminiRealtimeConfig._is_audio_only_live_model(model): - return normalized - if "TEXT" not in normalized: - return normalized - without_text: Final = [modality for modality in normalized if modality != "TEXT"] - return without_text if without_text else ["AUDIO"] + ) + if GeminiRealtimeConfig._is_audio_only_live_model(model) and "TEXT" in normalized: + return tuple(modality for modality in normalized if modality != "TEXT") or ("AUDIO",) + if GeminiRealtimeConfig._is_text_only_live_model(model) and "AUDIO" in normalized: + return tuple(modality for modality in normalized if modality != "AUDIO") or ("TEXT",) + return normalized @staticmethod def _finalize_gemini_live_setup(model: str, setup: dict[str, Any]) -> dict[str, Any]: @@ -436,7 +458,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): if session_configuration_request is None: generation_config: Final = new_overrides.setdefault("generationConfig", {}) - generation_config.setdefault("responseModalities", ["AUDIO"]) + generation_config.setdefault("responseModalities", [GeminiRealtimeConfig._default_response_modality(model)]) new_overrides.setdefault("inputAudioTranscription", {}) new_overrides["model"] = f"models/{model}" verbose_logger.debug("Gemini Realtime: Sending initial setup with tools to backend") @@ -558,9 +580,10 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): return self._handle_conversation_item(json_message) if msg_type == "input_audio_buffer.append": - realtime_input_dict["audio"] = HttpxBlobType( - mimeType=self.get_audio_mime_type(), data=json_message["audio"] - ) + audio_b64: Final = json_message["audio"] + if isinstance(audio_b64, str): + self._unbilled_input_audio_bytes += _base64_decoded_byte_count(audio_b64) + realtime_input_dict["audio"] = HttpxBlobType(mimeType=self.get_audio_mime_type(), data=audio_b64) realtime_input_dict = cast( BidiGenerateContentRealtimeInput, @@ -1151,6 +1174,26 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): raise ValueError(f"Unknown openai event: {key}, value: {value}") return openai_event + def _consume_input_transcription_usage_estimate(self, model: str) -> RealtimeInputAudioTranscriptionUsage | None: + """Gemini Live sends no usageMetadata for transcribe sessions; estimate billing from streamed audio duration.""" + if self._unbilled_input_audio_bytes <= 0 or not self._is_text_only_live_model(model): + return None + audio_seconds: Final = self._unbilled_input_audio_bytes / PCM16_INPUT_AUDIO_BYTES_PER_SECOND + self._unbilled_input_audio_bytes = 0 + audio_tokens: Final = round(audio_seconds * GEMINI_LIVE_TRANSCRIBE_AUDIO_TOKENS_PER_SECOND) + output_tokens: Final = round(audio_seconds * GEMINI_LIVE_TRANSCRIBE_OUTPUT_TEXT_TOKENS_PER_MINUTE / 60) + usage: Final[RealtimeInputAudioTranscriptionUsage] = { + "type": "tokens", + "input_tokens": audio_tokens, + "output_tokens": output_tokens, + "total_tokens": audio_tokens + output_tokens, + "input_token_details": {"text_tokens": 0, "audio_tokens": audio_tokens}, + } + return usage + + def unbilled_usage_on_session_close(self, model: str) -> RealtimeInputAudioTranscriptionUsage | None: + return self._consume_input_transcription_usage_estimate(model) + def transform_realtime_response( self, message: str | bytes, @@ -1190,6 +1233,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): if isinstance(server_content, dict): input_tx: Final = server_content.get("inputTranscription") if isinstance(input_tx, dict) and input_tx.get("text"): + transcription_usage: Final = self._consume_input_transcription_usage_estimate(model) returned_message.append( cast( OpenAIRealtimeEvents, @@ -1199,6 +1243,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): "transcript": input_tx["text"], "item_id": f"item_{uuid.uuid4()}", "content_index": 0, + **({} if transcription_usage is None else {"usage": transcription_usage}), }, ) ) @@ -1235,6 +1280,12 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): ) ) + # Transcription-only models emit generationComplete with no prior + # modelTurn delta; there is no started OpenAI response to close, so + # drop it and let siblings (turnComplete, usageMetadata) process. + if current_delta_type is None and "modelTurn" not in server_content: + server_content.pop("generationComplete", None) + # Mark transcription-only serverContent as handled so the main loop # skips it; sibling keys like toolCall are still processed below. _model_content_keys: Final = { @@ -1583,7 +1634,9 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): ``` """ - response_modalities: Final[list[GeminiResponseModalities]] = ["AUDIO"] + response_modalities: Final[list[GeminiResponseModalities]] = [ + GeminiRealtimeConfig._default_response_modality(model) + ] output_audio_transcription: Final = False # if "audio" in model: ## UNCOMMENT THIS WHEN AUDIO IS SUPPORTED # output_audio_transcription = True diff --git a/litellm/llms/together_ai/chat/transformation.py b/litellm/llms/together_ai/chat/transformation.py index d06bcb22119..47a11230cb1 100644 --- a/litellm/llms/together_ai/chat/transformation.py +++ b/litellm/llms/together_ai/chat/transformation.py @@ -4,7 +4,8 @@ Translates from OpenAI's `/v1/chat/completions` to Together AI's `/v1/chat/compl Docs: https://docs.together.ai/docs/chat-overview """ -from collections.abc import Callable, Container, Coroutine +from collections.abc import Callable, Container, Coroutine, Mapping +from types import MappingProxyType from typing import ( Final, Literal, @@ -12,11 +13,13 @@ from typing import ( overload, ) +from typing_extensions import ReadOnly, TypedDict + import litellm from litellm._logging import verbose_logger from litellm.exceptions import UnsupportedParamsError from litellm.types.llms.openai import AllMessageValues -from litellm.utils import supports_function_calling, supports_response_schema +from litellm.utils import supports_function_calling, supports_reasoning, supports_response_schema from ...openai.chat.gpt_transformation import OpenAIGPTConfig @@ -38,6 +41,34 @@ def _registry_verdict(model: str, flag: str, check: Callable[[str], bool]) -> bo return None +ADJUSTABLE_EFFORT_REASONING_MODELS: Final = frozenset( + { + "openai/gpt-oss-120b", + "openai/gpt-oss-20b", + } +) +HYBRID_REASONING_MODELS: Final = frozenset( + { + "MiniMaxAI/MiniMax-M3", + "Qwen/Qwen3.5-9B", + "Qwen/Qwen3.6-Plus", + "deepseek-ai/DeepSeek-V4-Pro", + "moonshotai/Kimi-K3", + "nvidia/nemotron-3-ultra-550b-a55b", + "zai-org/GLM-5.2", + } +) +HIGH_MAX_EFFORT_MODEL_PREFIX: Final = "deepseek-ai/DeepSeek-V4-Pro" +EFFORT_TRANSLATION: Final = MappingProxyType({"minimal": "low", "xhigh": "high", "max": "high"}) +HIGH_MAX_EFFORT_TRANSLATION: Final = MappingProxyType( + {"minimal": "high", "low": "high", "medium": "high", "xhigh": "max"} +) + + +class TogetherReasoningToggle(TypedDict): + enabled: ReadOnly[bool] + + def _function_calling_verdict(model: str) -> bool | None: return _registry_verdict( model, @@ -83,6 +114,36 @@ def _tool_params_to_drop(passed_params: Container[str], model: str, drop_params: ) +def _supports_together_reasoning(model: str) -> bool: + if model in ADJUSTABLE_EFFORT_REASONING_MODELS or model in HYBRID_REASONING_MODELS: + return True + if model.startswith(HIGH_MAX_EFFORT_MODEL_PREFIX): + return True + return supports_reasoning(model, custom_llm_provider="together_ai") + + +def _adjustable_effort(effort: str, model: str) -> str: + if effort == "none": + verbose_logger.debug( + "together_ai model %s cannot disable reasoning; mapping reasoning_effort=none to low", model + ) + return "low" + return EFFORT_TRANSLATION.get(effort, effort) + + +def _reasoning_effort_payload(effort: str, model: str) -> Mapping[str, object]: + if effort == "default": + return MappingProxyType({}) + if model in ADJUSTABLE_EFFORT_REASONING_MODELS: + return MappingProxyType({"reasoning_effort": _adjustable_effort(effort, model)}) + if effort == "none": + disable_reasoning: Final[TogetherReasoningToggle] = {"enabled": False} + return MappingProxyType({"reasoning": disable_reasoning}) + if model.startswith(HIGH_MAX_EFFORT_MODEL_PREFIX): + return MappingProxyType({"reasoning_effort": HIGH_MAX_EFFORT_TRANSLATION.get(effort, effort)}) + return MappingProxyType({"reasoning_effort": EFFORT_TRANSLATION.get(effort, effort)}) + + def _drop_response_format(passed_params: Container[str], model: str, drop_params: bool) -> bool: if "response_format" not in passed_params: return False @@ -153,6 +214,15 @@ class TogetherAIChatConfig(OpenAIGPTConfig): return super()._transform_messages(stripped, model, is_async=True) return super()._transform_messages(stripped, model, is_async=False) + def get_supported_openai_params(self, model: str) -> list: # mutable-ok: inherited contract + supported_params: Final = super().get_supported_openai_params(model) + if not _supports_together_reasoning(model): + return supported_params + return [ # mutable-ok: the inherited contract returns a plain list; building fresh avoids mutating the base class's value + *supported_params, + "reasoning_effort", + ] + def map_openai_params( self, non_default_params: dict, @@ -165,4 +235,10 @@ class TogetherAIChatConfig(OpenAIGPTConfig): mapped_openai_params.pop(param) if _drop_response_format(mapped_openai_params, model, drop_params): mapped_openai_params.pop("response_format") + effort: Final = mapped_openai_params.get("reasoning_effort") + if not isinstance(effort, str): + return mapped_openai_params + mapped_openai_params.pop("reasoning_effort") + for key, value in _reasoning_effort_payload(effort, model).items(): + mapped_openai_params.setdefault(key, value) return mapped_openai_params diff --git a/litellm/main.py b/litellm/main.py index 8ee102f5d07..583c5b3f92a 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -1219,6 +1219,7 @@ def _register_custom_pricing_for_request( shared_key: CustomPricingLiteLLMParams.strip_custom_pricing_fields(entry), }, persist_across_reloads=False, + warning_display_name=shared_key, ) diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 7f8c464f5b9..82e45337b1f 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -4691,7 +4691,7 @@ "supports_web_search": false }, "azure/gpt-4.1-nano": { - "deprecation_date": "2026-10-14", + "deprecation_date": "2027-04-14", "cache_read_input_token_cost": 2.5e-08, "input_cost_per_token": 1e-07, "input_cost_per_token_batches": 5e-08, @@ -4724,7 +4724,7 @@ "supports_vision": true }, "azure/gpt-4.1-nano-2025-04-14": { - "deprecation_date": "2026-10-14", + "deprecation_date": "2027-04-14", "cache_read_input_token_cost": 2.5e-08, "input_cost_per_token": 1e-07, "input_cost_per_token_batches": 5e-08, @@ -15167,6 +15167,34 @@ "output_dbu_cost_per_token": 7.143e-06, "source": "https://www.databricks.com/product/pricing/foundation-model-serving" }, + "databricks/databricks-glm-5-2": { + "cache_creation_input_token_cost": 1.4e-06, + "cache_read_input_token_cost": 2.5998e-07, + "input_cost_per_token": 1.4e-06, + "input_dbu_cost_per_token": 2e-05, + "litellm_provider": "databricks", + "max_input_tokens": 1000000, + "max_output_tokens": 131072, + "max_tokens": 131072, + "metadata": { + "notes": "Input/output cost per token is dbu cost * $0.070. Billing reads the per-token dollar fields; the '*_dbu_cost_per_token' fields are the published Databricks rates, kept for reference." + }, + "mode": "chat", + "output_cost_per_token": 4.39999e-06, + "output_dbu_cost_per_token": 6.2857e-05, + "source": "https://www.databricks.com/product/pricing/foundation-model-serving", + "supported_modalities": [ + "text" + ], + "supported_output_modalities": [ + "text" + ], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, "databricks/databricks-gpt-5": { "cache_creation_input_token_cost": 1.24999e-06, "cache_read_input_token_cost": 1.2502e-07, @@ -15434,6 +15462,35 @@ "output_vector_size": 1024, "source": "https://www.databricks.com/product/pricing/foundation-model-serving" }, + "databricks/databricks-kimi-k3": { + "cache_creation_input_token_cost": 2.99999e-06, + "cache_read_input_token_cost": 3.0002e-07, + "input_cost_per_token": 2.99999e-06, + "input_dbu_cost_per_token": 4.2857e-05, + "litellm_provider": "databricks", + "max_input_tokens": 1000000, + "max_output_tokens": 1048576, + "max_tokens": 1048576, + "metadata": { + "notes": "Input/output cost per token is dbu cost * $0.070. Billing reads the per-token dollar fields; the '*_dbu_cost_per_token' fields are the published Databricks rates, kept for reference." + }, + "mode": "chat", + "output_cost_per_token": 1.500002e-05, + "output_dbu_cost_per_token": 0.000214286, + "source": "https://www.databricks.com/product/pricing/foundation-model-serving", + "supported_modalities": [ + "text", + "image" + ], + "supported_output_modalities": [ + "text" + ], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": true + }, "databricks/databricks-llama-2-70b-chat": { "cache_creation_input_token_cost": 5.0001e-07, "cache_read_input_token_cost": 5.0001e-07, @@ -16112,12 +16169,13 @@ "max_tokens": 4096, "max_input_tokens": 4096, "max_output_tokens": 4096, - "input_cost_per_token": 8e-08, - "output_cost_per_token": 9e-08, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/NousResearch/Hermes-3-Llama-3.1-405B": { "max_tokens": 131072, @@ -16134,11 +16192,12 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 3e-07, - "output_cost_per_token": 3e-07, + "input_cost_per_token": 7e-07, + "output_cost_per_token": 7e-07, "litellm_provider": "deepinfra", "mode": "chat", - "supports_tool_choice": false + "supports_tool_choice": false, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/QwQ-32B": { "max_tokens": 131072, @@ -16155,12 +16214,13 @@ "max_tokens": 32768, "max_input_tokens": 32768, "max_output_tokens": 32768, - "input_cost_per_token": 1.2e-07, - "output_cost_per_token": 3.9e-07, + "input_cost_per_token": 3.6e-07, + "output_cost_per_token": 4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen2.5-7B-Instruct": { "max_tokens": 32768, @@ -16188,12 +16248,13 @@ "max_tokens": 40960, "max_input_tokens": 40960, "max_output_tokens": 40960, - "input_cost_per_token": 6e-08, + "input_cost_per_token": 1.2e-07, "output_cost_per_token": 2.4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-235B-A22B": { "max_tokens": 40960, @@ -16211,11 +16272,12 @@ "max_input_tokens": 262144, "max_output_tokens": 262144, "input_cost_per_token": 9e-08, - "output_cost_per_token": 6e-07, + "output_cost_per_token": 5.5e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-235B-A22B-Thinking-2507": { "max_tokens": 262144, @@ -16232,23 +16294,25 @@ "max_tokens": 40960, "max_input_tokens": 40960, "max_output_tokens": 40960, - "input_cost_per_token": 8e-08, - "output_cost_per_token": 2.9e-07, + "input_cost_per_token": 1.2e-07, + "output_cost_per_token": 5e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-32B": { "max_tokens": 40960, "max_input_tokens": 40960, "max_output_tokens": 40960, - "input_cost_per_token": 1e-07, + "input_cost_per_token": 8e-08, "output_cost_per_token": 2.8e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-Coder-480B-A35B-Instruct": { "max_tokens": 262144, @@ -16265,23 +16329,27 @@ "max_tokens": 262144, "max_input_tokens": 262144, "max_output_tokens": 262144, - "input_cost_per_token": 2.9e-07, - "output_cost_per_token": 1.2e-06, + "input_cost_per_token": 3e-07, + "output_cost_per_token": 1e-06, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-Next-80B-A3B-Instruct": { "max_tokens": 262144, "max_input_tokens": 262144, "max_output_tokens": 262144, - "input_cost_per_token": 1.4e-07, - "output_cost_per_token": 1.4e-06, + "input_cost_per_token": 9e-08, + "output_cost_per_token": 1.1e-06, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-Next-80B-A3B-Thinking": { "max_tokens": 262144, @@ -16308,11 +16376,12 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 6.5e-07, - "output_cost_per_token": 7.5e-07, + "input_cost_per_token": 8.5e-07, + "output_cost_per_token": 8.5e-07, "litellm_provider": "deepinfra", "mode": "chat", - "supports_tool_choice": false + "supports_tool_choice": false, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Sao10K/L3.3-70B-Euryale-v2.3": { "max_tokens": 131072, @@ -16438,36 +16507,41 @@ "max_tokens": 163840, "max_input_tokens": 163840, "max_output_tokens": 163840, - "input_cost_per_token": 3.8e-07, + "input_cost_per_token": 3.2e-07, "output_cost_per_token": 8.9e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/deepseek-ai/DeepSeek-V3-0324": { "max_tokens": 163840, "max_input_tokens": 163840, "max_output_tokens": 163840, - "input_cost_per_token": 2.5e-07, - "output_cost_per_token": 8.8e-07, + "input_cost_per_token": 2.4e-07, + "output_cost_per_token": 9e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "cache_read_input_token_cost": 1.35e-07, + "supports_prompt_caching": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/deepseek-ai/DeepSeek-V3.1": { "max_tokens": 163840, "max_input_tokens": 163840, "max_output_tokens": 163840, - "input_cost_per_token": 2.7e-07, - "output_cost_per_token": 1e-06, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 9.5e-07, "cache_read_input_token_cost": 2.16e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, "supports_reasoning": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/deepseek-ai/DeepSeek-V3.1-Terminus": { "max_tokens": 163840, @@ -16521,33 +16595,36 @@ "max_input_tokens": 131072, "max_output_tokens": 131072, "input_cost_per_token": 5e-08, - "output_cost_per_token": 1e-07, + "output_cost_per_token": 1.5e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/google/gemma-3-27b-it": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 9e-08, + "input_cost_per_token": 8e-08, "output_cost_per_token": 1.6e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/google/gemma-3-4b-it": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 4e-08, - "output_cost_per_token": 8e-08, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 1e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-3.2-11B-Vision-Instruct": { "max_tokens": 131072, @@ -16585,34 +16662,37 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 1.3e-07, - "output_cost_per_token": 3.9e-07, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 3.2e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_function_calling": true, - "supports_tool_choice": true + "supports_tool_choice": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8": { "max_tokens": 1048576, "max_input_tokens": 1048576, "max_output_tokens": 1048576, - "input_cost_per_token": 1.5e-07, - "output_cost_per_token": 6e-07, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 8e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-4-Scout-17B-16E-Instruct": { "max_tokens": 327680, "max_input_tokens": 327680, "max_output_tokens": 327680, - "input_cost_per_token": 8e-08, + "input_cost_per_token": 1e-07, "output_cost_per_token": 3e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-Guard-3-8B": { "max_tokens": 131072, @@ -16660,12 +16740,13 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 1e-07, - "output_cost_per_token": 2.8e-07, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Meta-Llama-3.1-8B-Instruct": { "max_tokens": 131072, @@ -16683,11 +16764,12 @@ "max_input_tokens": 131072, "max_output_tokens": 131072, "input_cost_per_token": 2e-08, - "output_cost_per_token": 3e-08, + "output_cost_per_token": 4e-08, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/microsoft/WizardLM-2-8x22B": { "max_tokens": 65536, @@ -16714,12 +16796,13 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 2e-08, - "output_cost_per_token": 4e-08, + "input_cost_per_token": 1.9e-08, + "output_cost_per_token": 3e-08, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/mistralai/Mistral-Small-24B-Instruct-2501": { "max_tokens": 32768, @@ -16801,14 +16884,16 @@ }, "deepinfra/nvidia/NVIDIA-Nemotron-3.5-Lightning": { "max_input_tokens": 262144, - "input_cost_per_token": 5e-08, + "input_cost_per_token": 8e-08, "output_cost_per_token": 2e-07, "litellm_provider": "deepinfra", "mode": "chat", - "source": "https://deepinfra.com/nvidia/NVIDIA-Nemotron-3.5-Lightning", + "source": "https://deepinfra.com/pricing", "supports_tool_choice": true, "supports_function_calling": true, - "supports_reasoning": true + "supports_reasoning": true, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true }, "deepinfra/nvidia/NVIDIA-Nemotron-Nano-9B-v2": { "max_tokens": 131072, @@ -16825,23 +16910,25 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 5e-08, - "output_cost_per_token": 4.5e-07, + "input_cost_per_token": 3.7e-08, + "output_cost_per_token": 1.7e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/openai/gpt-oss-20b": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 4e-08, - "output_cost_per_token": 1.5e-07, + "input_cost_per_token": 3e-08, + "output_cost_per_token": 1.4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/zai-org/GLM-4.5": { "max_tokens": 131072, @@ -18636,6 +18723,22 @@ "supports_tool_choice": true, "supports_vision": false }, + "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813": { + "cache_read_input_token_cost": 4.4e-08, + "input_cost_per_token": 1.32e-06, + "litellm_provider": "fireworks_ai", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 3.96e-06, + "source": "https://docs.fireworks.ai/serverless/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, "fireworks_ai/accounts/fireworks/models/firefunction-v2": { "input_cost_per_token": 9e-07, "litellm_provider": "fireworks_ai", @@ -20342,7 +20445,7 @@ "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -20522,7 +20625,7 @@ "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, - "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-preview", + "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22114,7 +22217,7 @@ "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, "rpm": 15, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22162,7 +22265,7 @@ "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, "rpm": 15, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22209,7 +22312,7 @@ "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, "rpm": 15, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22257,7 +22360,7 @@ "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, "rpm": 15, - "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-lite", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -30839,6 +30942,152 @@ "supports_response_schema": true, "supports_tool_choice": true }, + "mistral/ministral-14b-2512": { + "input_cost_per_token": 2e-07, + "litellm_provider": "mistral", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 2e-07, + "source": "https://docs.mistral.ai/models/ministral-3-14b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/ministral-14b-latest": { + "input_cost_per_token": 2e-07, + "litellm_provider": "mistral", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 2e-07, + "source": "https://docs.mistral.ai/models/ministral-3-14b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/ministral-3b-2512": { + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 131072, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1e-07, + "source": "https://docs.mistral.ai/models/ministral-3-3b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/ministral-3b-latest": { + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 131072, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1e-07, + "source": "https://docs.mistral.ai/models/ministral-3-3b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/mistral-embed-2312": { + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 8192, + "max_tokens": 8192, + "mode": "embedding", + "source": "https://docs.mistral.ai/models/mistral-embed-23-12" + }, + "mistral/mistral-medium-3": { + "input_cost_per_token": 1.5e-06, + "litellm_provider": "mistral", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 7.5e-06, + "source": "https://docs.mistral.ai/models/model-cards/mistral-medium-3-5-26-04", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/voxtral-mini-transcribe-realtime-latest": { + "input_cost_per_second": 0.0001, + "litellm_provider": "mistral", + "mode": "audio_transcription", + "source": "https://docs.mistral.ai/models/model-cards/voxtral-mini-transcribe-realtime-26-02", + "supported_endpoints": [ + "/v1/audio/transcriptions" + ], + "supported_modalities": [ + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true + }, + "mistral/voxtral-mini-tts-latest": { + "litellm_provider": "mistral", + "mode": "audio_speech", + "output_cost_per_character": 1.6e-05, + "source": "https://docs.mistral.ai/models/model-cards/voxtral-tts-26-03", + "supported_endpoints": [ + "/v1/audio/speech" + ], + "supported_modalities": [ + "text" + ], + "supported_output_modalities": [ + "audio" + ], + "supports_audio_output": true + }, + "mistral/voxtral-small-2507": { + "input_cost_per_second": 6.666666666666667e-05, + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 32768, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 4e-07, + "source": "https://docs.mistral.ai/models/voxtral-small-25-07", + "supports_audio_input": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true + }, + "mistral/voxtral-small-latest": { + "input_cost_per_second": 6.666666666666667e-05, + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 32768, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 4e-07, + "source": "https://docs.mistral.ai/models/voxtral-small-25-07", + "supports_audio_input": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true + }, "mistral/zai-glm-5-2": { "cache_read_input_token_cost": 1.4e-07, "input_cost_per_token": 1.4e-06, @@ -38137,7 +38386,7 @@ "max_output_tokens": 20480, "max_tokens": 20480, "metadata": { - "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro" + "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813" }, "mode": "chat", "output_cost_per_token": 7e-06, @@ -38166,7 +38415,7 @@ "max_output_tokens": 8192, "max_tokens": 8192, "metadata": { - "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro" + "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813" }, "mode": "chat", "output_cost_per_token": 1.25e-06, @@ -38181,7 +38430,7 @@ "litellm_provider": "together_ai", "max_tokens": 16384, "metadata": { - "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro" + "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813" }, "mode": "chat", "output_cost_per_token": 1.7e-06, @@ -38472,6 +38721,7 @@ "supports_tool_choice": true }, "together_ai/Qwen/Qwen3.5-397B-A17B": { + "cache_read_input_token_cost": 3.5e-07, "deprecation_date": "2026-06-29", "input_cost_per_token": 6e-07, "litellm_provider": "together_ai", @@ -38481,10 +38731,12 @@ "source": "https://www.together.ai/models/Qwen/Qwen3.5-397B-A17B", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/MiniMaxAI/MiniMax-M3": { + "cache_read_input_token_cost": 6e-08, "input_cost_per_token": 3e-07, "litellm_provider": "together_ai", "max_input_tokens": 524288, @@ -38495,6 +38747,7 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, @@ -38538,6 +38791,7 @@ "supports_reasoning": true }, "together_ai/Qwen/Qwen3.7-Max": { + "cache_read_input_token_cost": 1.3e-07, "input_cost_per_token": 1.25e-06, "litellm_provider": "together_ai", "max_input_tokens": 1000000, @@ -38545,7 +38799,8 @@ "max_tokens": 1000000, "mode": "chat", "output_cost_per_token": 3.75e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/Qwen/Qwen3.7-Plus": { "input_cost_per_token": 3.2e-07, @@ -38558,6 +38813,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/Qwen/Qwen3.8-2.4T-A95B": { + "cache_read_input_token_cost": 5e-07, "input_cost_per_token": 2.5e-06, "litellm_provider": "together_ai", "max_input_tokens": 1010000, @@ -38565,7 +38821,8 @@ "max_tokens": 1010000, "mode": "chat", "output_cost_per_token": 6.25e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/arize-ai/qwen-2-1.5b-instruct": { "input_cost_per_token": 1e-07, @@ -38578,6 +38835,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/deepseek-ai/DeepSeek-V4-Flash-0731": { + "cache_read_input_token_cost": 3e-08, "input_cost_per_token": 1.4e-07, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38588,10 +38846,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/deepseek-ai/DeepSeek-V4-Pro": { + "deprecation_date": "2026-08-27", + "cache_read_input_token_cost": 2e-07, "input_cost_per_token": 1.74e-06, "litellm_provider": "together_ai", "max_input_tokens": 512000, @@ -38602,11 +38863,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813": { + "cache_read_input_token_cost": 1.3e-07, "input_cost_per_token": 1.32e-06, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38617,10 +38880,12 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/google/gemma-3n-E4B-it": { + "deprecation_date": "2026-08-25", "input_cost_per_token": 6e-08, "litellm_provider": "together_ai", "max_input_tokens": 32768, @@ -38656,6 +38921,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/meta-llama/Llama-Guard-4-12B": { + "deprecation_date": "2026-08-25", "input_cost_per_token": 2e-07, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38666,6 +38932,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/meta-models/Muse-Glimmer-30B": { + "cache_read_input_token_cost": 4e-08, "input_cost_per_token": 3.5e-07, "litellm_provider": "together_ai", "max_input_tokens": 131072, @@ -38673,9 +38940,12 @@ "max_tokens": 131072, "mode": "chat", "output_cost_per_token": 1.5e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/moonshotai/Kimi-K2.7-Code": { + "deprecation_date": "2026-08-27", + "cache_read_input_token_cost": 1.9e-07, "input_cost_per_token": 9.5e-07, "litellm_provider": "together_ai", "max_input_tokens": 262144, @@ -38686,11 +38956,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true }, "together_ai/moonshotai/Kimi-K3": { + "cache_read_input_token_cost": 3e-07, "input_cost_per_token": 3e-06, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38701,12 +38973,15 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true }, "together_ai/nvidia/nemotron-3-ultra-550b-a55b": { + "deprecation_date": "2026-08-27", + "cache_read_input_token_cost": 2e-07, "input_cost_per_token": 6e-07, "litellm_provider": "together_ai", "max_input_tokens": 512288, @@ -38717,11 +38992,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/pearl-ai/gemma-4-31b-it": { + "deprecation_date": "2026-08-27", "input_cost_per_token": 2.8e-07, "litellm_provider": "together_ai", "max_input_tokens": 262144, @@ -38732,6 +39009,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/thinkingmachines/Inkling": { + "cache_read_input_token_cost": 1.7e-07, "input_cost_per_token": 1e-06, "litellm_provider": "together_ai", "max_input_tokens": 524288, @@ -38742,10 +39020,12 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/thinkingmachines/Inkling-Small": { + "cache_read_input_token_cost": 1e-07, "input_cost_per_token": 5e-07, "litellm_provider": "together_ai", "max_input_tokens": 524288, @@ -38753,9 +39033,11 @@ "max_tokens": 524288, "mode": "chat", "output_cost_per_token": 1.2e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/zai-org/GLM-5.2": { + "cache_read_input_token_cost": 2.6e-07, "input_cost_per_token": 1.4e-06, "litellm_provider": "together_ai", "max_input_tokens": 1048575, @@ -38766,6 +39048,7 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true @@ -43061,19 +43344,21 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 0.015, - "output_cost_per_token": 0.06, + "input_cost_per_token": 3e-08, + "output_cost_per_token": 1.7e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/openai/gpt-oss-20b": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 0.005, - "output_cost_per_token": 0.02, + "input_cost_per_token": 3e-08, + "output_cost_per_token": 1.3e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/zai-org/GLM-4.5": { "max_tokens": 131072, @@ -43097,10 +43382,11 @@ "max_tokens": 262144, "max_input_tokens": 262144, "max_output_tokens": 262144, - "input_cost_per_token": 0.1, - "output_cost_per_token": 0.15, + "input_cost_per_token": 1e-06, + "output_cost_per_token": 1.5e-06, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/Qwen/Qwen3-235B-A22B-Thinking-2507": { "max_tokens": 262144, @@ -43152,19 +43438,21 @@ "max_tokens": 128000, "max_input_tokens": 128000, "max_output_tokens": 128000, - "input_cost_per_token": 0.022, - "output_cost_per_token": 0.022, + "input_cost_per_token": 2.2e-07, + "output_cost_per_token": 2.2e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/deepseek-ai/DeepSeek-V3.1": { "max_tokens": 128000, - "max_input_tokens": 128000, + "max_input_tokens": 161000, "max_output_tokens": 128000, - "input_cost_per_token": 0.055, - "output_cost_per_token": 0.165, + "input_cost_per_token": 5.5e-07, + "output_cost_per_token": 1.65e-06, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/deepseek-ai/DeepSeek-R1-0528": { "max_tokens": 161000, @@ -43188,10 +43476,11 @@ "max_tokens": 128000, "max_input_tokens": 128000, "max_output_tokens": 128000, - "input_cost_per_token": 0.071, - "output_cost_per_token": 0.071, + "input_cost_per_token": 7.1e-07, + "output_cost_per_token": 7.1e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/meta-llama/Llama-4-Scout-17B-16E-Instruct": { "max_tokens": 64000, @@ -43577,85 +43866,6 @@ "/v1/audio/transcriptions" ] }, - "xai/grok-2": { - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_web_search": true - }, - "xai/grok-2-1212": { - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_web_search": true - }, - "xai/grok-2-latest": { - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_web_search": true - }, - "xai/grok-2-vision": { - "input_cost_per_image": 2e-06, - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 32768, - "max_output_tokens": 32768, - "max_tokens": 32768, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, - "xai/grok-2-vision-1212": { - "deprecation_date": "2026-02-28", - "input_cost_per_image": 2e-06, - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 32768, - "max_output_tokens": 32768, - "max_tokens": 32768, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, - "xai/grok-2-vision-latest": { - "input_cost_per_image": 2e-06, - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 32768, - "max_output_tokens": 32768, - "max_tokens": 32768, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, "xai/grok-3": { "cache_read_input_token_cost": 7.5e-07, "input_cost_per_token": 3e-06, @@ -44041,7 +44251,7 @@ "max_input_tokens": 1000000, "max_output_tokens": 1000000, "max_tokens": 1000000, - "mode": "chat", + "mode": "responses", "output_cost_per_token": 2.5e-06, "source": "https://docs.x.ai/docs/models", "supports_function_calling": true, @@ -44053,7 +44263,10 @@ "input_cost_per_token_above_200k_tokens": 2.5e-06, "output_cost_per_token_above_200k_tokens": 5e-06, "cache_read_input_token_cost_above_200k_tokens": 4e-07, - "supports_response_schema": true + "supports_response_schema": true, + "supported_endpoints": [ + "/v1/responses" + ] }, "xai/grok-4.20-beta-0309-reasoning": { "cache_read_input_token_cost": 2e-07, @@ -44222,19 +44435,6 @@ "supports_vision": true, "supports_web_search": true }, - "xai/grok-beta": { - "input_cost_per_token": 5e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1.5e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, "xai/grok-code-fast": { "cache_read_input_token_cost": 2e-07, "input_cost_per_token": 1e-06, @@ -44298,20 +44498,6 @@ "supports_vision": true, "deprecation_date": "2026-05-15" }, - "xai/grok-vision-beta": { - "input_cost_per_image": 5e-06, - "input_cost_per_token": 5e-06, - "litellm_provider": "xai", - "max_input_tokens": 8192, - "max_output_tokens": 8192, - "max_tokens": 8192, - "mode": "chat", - "output_cost_per_token": 1.5e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, "zai.glm-4.7": { "input_cost_per_token": 6e-07, "litellm_provider": "bedrock_converse", @@ -44370,6 +44556,21 @@ "supports_tool_choice": true, "source": "https://docs.z.ai/guides/overview/pricing" }, + "zai/glm-5.3": { + "cache_creation_input_token_cost": 0, + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.4e-06, + "litellm_provider": "zai", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://docs.z.ai/guides/overview/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true + }, "zai/glm-5.1": { "cache_creation_input_token_cost": 0, "cache_read_input_token_cost": 2.6e-07, @@ -44575,6 +44776,7 @@ ] }, "azure/sora-2": { + "deprecation_date": "2026-10-15", "litellm_provider": "azure", "mode": "video_generation", "output_cost_per_video_per_second": 0.1, @@ -47158,8 +47360,8 @@ "novita/xiaomimimo/mimo-v2-flash": { "litellm_provider": "novita", "mode": "chat", - "input_cost_per_token": 1e-07, - "output_cost_per_token": 3e-07, + "input_cost_per_token": 1.1e-07, + "output_cost_per_token": 3.3e-07, "max_input_tokens": 262144, "max_output_tokens": 32000, "max_tokens": 32000, @@ -47168,8 +47370,8 @@ "supports_tool_choice": true, "supports_system_messages": true, "supports_response_schema": true, - "cache_read_input_token_cost": 2e-08, - "input_cost_per_token_cache_hit": 2e-08, + "cache_read_input_token_cost": 2.4e-08, + "input_cost_per_token_cache_hit": 2.4e-08, "supports_reasoning": true }, "novita/zai-org/autoglm-phone-9b-multilingual": { @@ -47189,14 +47391,16 @@ "input_cost_per_token": 6e-07, "output_cost_per_token": 2.5e-06, "max_input_tokens": 262144, - "max_output_tokens": 262144, - "max_tokens": 262144, + "max_output_tokens": 100352, + "max_tokens": 100352, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, "supports_response_schema": true, - "supports_reasoning": true + "supports_reasoning": true, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true }, "novita/minimax/minimax-m2": { "litellm_provider": "novita", @@ -47212,7 +47416,8 @@ "supports_system_messages": true, "cache_read_input_token_cost": 3e-08, "input_cost_per_token_cache_hit": 3e-08, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/paddlepaddle/paddleocr-vl": { "litellm_provider": "novita", @@ -47250,7 +47455,9 @@ "max_tokens": 32768, "supports_vision": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "novita/zai-org/glm-4.6v": { "litellm_provider": "novita", @@ -47315,7 +47522,8 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_response_schema": true + "supports_response_schema": true, + "supports_reasoning": true }, "novita/qwen/qwen3-next-80b-a3b-thinking": { "litellm_provider": "novita", @@ -47427,8 +47635,8 @@ "input_cost_per_token": 6e-07, "output_cost_per_token": 2.5e-06, "max_input_tokens": 262144, - "max_output_tokens": 262144, - "max_tokens": 262144, + "max_output_tokens": 100352, + "max_tokens": 100352, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -47438,8 +47646,8 @@ "novita/qwen/qwen3-coder-480b-a35b-instruct": { "litellm_provider": "novita", "mode": "chat", - "input_cost_per_token": 3e-07, - "output_cost_per_token": 1.3e-06, + "input_cost_per_token": 3.8e-07, + "output_cost_per_token": 1.55e-06, "max_input_tokens": 262144, "max_output_tokens": 65536, "max_tokens": 65536, @@ -47485,8 +47693,8 @@ "input_cost_per_token": 5.7e-07, "output_cost_per_token": 2.3e-06, "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, + "max_output_tokens": 100352, + "max_tokens": 100352, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -47499,8 +47707,8 @@ "input_cost_per_token": 2.7e-07, "output_cost_per_token": 1.12e-06, "max_input_tokens": 163840, - "max_output_tokens": 163840, - "max_tokens": 163840, + "max_output_tokens": 65536, + "max_tokens": 65536, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -47547,7 +47755,8 @@ "max_input_tokens": 16384, "max_output_tokens": 16384, "max_tokens": 16384, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/google/gemma-3-12b-it": { "litellm_provider": "novita", @@ -47626,13 +47835,14 @@ "mode": "chat", "input_cost_per_token": 1.35e-07, "output_cost_per_token": 4e-07, - "max_input_tokens": 131072, - "max_output_tokens": 120000, - "max_tokens": 120000, + "max_input_tokens": 12288, + "max_output_tokens": 12288, + "max_tokens": 12288, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/qwen/qwen-2.5-72b-instruct": { "litellm_provider": "novita", @@ -47672,7 +47882,8 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/deepseek/deepseek-r1-0528": { "litellm_provider": "novita", @@ -47712,7 +47923,8 @@ "max_input_tokens": 8192, "max_output_tokens": 8192, "max_tokens": 8192, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/microsoft/wizardlm-2-8x22b": { "litellm_provider": "novita", @@ -47722,7 +47934,8 @@ "max_input_tokens": 65535, "max_output_tokens": 8000, "max_tokens": 8000, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/deepseek/deepseek-r1-0528-qwen3-8b": { "litellm_provider": "novita", @@ -47769,7 +47982,8 @@ "max_output_tokens": 20000, "max_tokens": 20000, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/meta-llama/llama-4-maverick-17b-128e-instruct-fp8": { "litellm_provider": "novita", @@ -47780,7 +47994,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "supports_vision": true, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/meta-llama/llama-4-scout-17b-16e-instruct": { "litellm_provider": "novita", @@ -47916,7 +48131,9 @@ "max_output_tokens": 20000, "max_tokens": 20000, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "novita/google/gemma-3-27b-it": { "litellm_provider": "novita", @@ -47954,7 +48171,8 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/Sao10K/L3-8B-Stheno-v3.2": { "litellm_provider": "novita", @@ -48022,7 +48240,9 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "cache_read_input_token_cost": 2.5e-08, + "supports_prompt_caching": true }, "novita/qwen/qwen3-vl-30b-a3b-instruct": { "litellm_provider": "novita", @@ -48143,10 +48363,12 @@ "input_cost_per_token": 3e-08, "output_cost_per_token": 3e-08, "max_input_tokens": 128000, - "max_output_tokens": 20000, - "max_tokens": 20000, + "max_output_tokens": 8192, + "max_tokens": 8192, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "novita/qwen/qwen2.5-7b-instruct": { "litellm_provider": "novita", @@ -48154,8 +48376,8 @@ "input_cost_per_token": 7e-08, "output_cost_per_token": 7e-08, "max_input_tokens": 32000, - "max_output_tokens": 32000, - "max_tokens": 32000, + "max_output_tokens": 8192, + "max_tokens": 8192, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -49567,14 +49789,14 @@ "supports_tool_choice": true }, "bedrock_mantle/openai.gpt-5.6-sol": { - "input_cost_per_token": 5.5e-06, - "input_cost_per_token_above_272k_tokens": 1.1e-05, - "cache_creation_input_token_cost": 6.875e-06, - "cache_creation_input_token_cost_above_272k_tokens": 1.375e-05, - "cache_read_input_token_cost": 5.5e-07, - "cache_read_input_token_cost_above_272k_tokens": 1.1e-06, - "output_cost_per_token": 3.3e-05, - "output_cost_per_token_above_272k_tokens": 4.95e-05, + "input_cost_per_token": 4.4e-06, + "input_cost_per_token_above_272k_tokens": 8.8e-06, + "cache_creation_input_token_cost": 5.5e-06, + "cache_creation_input_token_cost_above_272k_tokens": 1.1e-05, + "cache_read_input_token_cost": 4.4e-07, + "cache_read_input_token_cost_above_272k_tokens": 8.8e-07, + "output_cost_per_token": 2.2e-05, + "output_cost_per_token_above_272k_tokens": 3.3e-05, "litellm_provider": "bedrock_mantle", "max_input_tokens": 1050000, "max_output_tokens": 128000, @@ -49632,6 +49854,34 @@ "supports_tool_choice": true, "supports_vision": true }, + "bedrock_mantle/openai.gpt-5.6-cyber": { + "input_cost_per_token": 1.375e-05, + "cache_creation_input_token_cost": 1.71875e-05, + "cache_read_input_token_cost": 1.375e-06, + "output_cost_per_token": 8.25e-05, + "litellm_provider": "bedrock_mantle", + "max_input_tokens": 272000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "responses", + "use_openai_responses_path": true, + "supported_endpoints": [ + "/v1/responses" + ], + "supported_modalities": [ + "text", + "image" + ], + "supported_output_modalities": [ + "text" + ], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, "bedrock_mantle/openai.gpt-5.6-luna": { "input_cost_per_token": 2.2e-07, "input_cost_per_token_above_272k_tokens": 4.4e-07, @@ -49666,14 +49916,14 @@ "supports_vision": true }, "us.openai.gpt-5.6-sol": { - "input_cost_per_token": 5.5e-06, - "input_cost_per_token_above_272k_tokens": 1.1e-05, - "cache_creation_input_token_cost": 6.875e-06, - "cache_creation_input_token_cost_above_272k_tokens": 1.375e-05, - "cache_read_input_token_cost": 5.5e-07, - "cache_read_input_token_cost_above_272k_tokens": 1.1e-06, - "output_cost_per_token": 3.3e-05, - "output_cost_per_token_above_272k_tokens": 4.95e-05, + "input_cost_per_token": 4.4e-06, + "input_cost_per_token_above_272k_tokens": 8.8e-06, + "cache_creation_input_token_cost": 5.5e-06, + "cache_creation_input_token_cost_above_272k_tokens": 1.1e-05, + "cache_read_input_token_cost": 4.4e-07, + "cache_read_input_token_cost_above_272k_tokens": 8.8e-07, + "output_cost_per_token": 2.2e-05, + "output_cost_per_token_above_272k_tokens": 3.3e-05, "litellm_provider": "bedrock_converse", "max_input_tokens": 1000000, "max_output_tokens": 128000, @@ -49692,14 +49942,14 @@ "supports_vision": true }, "global.openai.gpt-5.6-sol": { - "input_cost_per_token": 5e-06, - "input_cost_per_token_above_272k_tokens": 1e-05, - "cache_creation_input_token_cost": 6.25e-06, - "cache_creation_input_token_cost_above_272k_tokens": 1.25e-05, - "cache_read_input_token_cost": 5e-07, - "cache_read_input_token_cost_above_272k_tokens": 1e-06, - "output_cost_per_token": 3e-05, - "output_cost_per_token_above_272k_tokens": 4.5e-05, + "input_cost_per_token": 4e-06, + "input_cost_per_token_above_272k_tokens": 8e-06, + "cache_creation_input_token_cost": 5e-06, + "cache_creation_input_token_cost_above_272k_tokens": 1e-05, + "cache_read_input_token_cost": 4e-07, + "cache_read_input_token_cost_above_272k_tokens": 8e-07, + "output_cost_per_token": 2e-05, + "output_cost_per_token_above_272k_tokens": 3e-05, "litellm_provider": "bedrock_converse", "max_input_tokens": 1000000, "max_output_tokens": 128000, @@ -50981,7 +51231,7 @@ "max_input_tokens": 1000000, "max_output_tokens": 1000000, "max_tokens": 1000000, - "mode": "chat", + "mode": "responses", "output_cost_per_token": 2.5e-06, "source": "https://docs.x.ai/docs/models", "supports_function_calling": true, @@ -50993,7 +51243,10 @@ "input_cost_per_token_above_200k_tokens": 2.5e-06, "output_cost_per_token_above_200k_tokens": 5e-06, "cache_read_input_token_cost_above_200k_tokens": 4e-07, - "supports_response_schema": true + "supports_response_schema": true, + "supported_endpoints": [ + "/v1/responses" + ] }, "xai/grok-build-0.1": { "cache_read_input_token_cost": 2e-07, @@ -51357,6 +51610,47 @@ "supports_audio_output": true, "tpm": 250000 }, + "gemini/gemini-3.5-transcribe": { + "input_cost_per_audio_token": 2e-06, + "input_cost_per_token": 2e-06, + "litellm_provider": "gemini", + "mode": "audio_transcription", + "output_cost_per_token": 1.2e-05, + "source": "https://ai.google.dev/gemini-api/docs/pricing", + "supported_endpoints": [ + "/v1/audio/transcriptions" + ], + "supported_modalities": [ + "text", + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true, + "tpm": 800000, + "rpm": 2000 + }, + "gemini/gemini-3.5-transcribe-live": { + "input_cost_per_audio_token": 3.5e-06, + "input_cost_per_token": 3.5e-06, + "litellm_provider": "gemini", + "mode": "audio_transcription", + "output_cost_per_token": 2.1e-05, + "source": "https://ai.google.dev/gemini-api/docs/pricing", + "supported_endpoints": [ + "/v1/realtime" + ], + "supported_modalities": [ + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true, + "tpm": 250000, + "rpm": 10 + }, "perplexity/pplx-embed-context-v1-0.6b": { "input_cost_per_token": 8e-09, "litellm_provider": "perplexity", @@ -51439,14 +51733,14 @@ "supports_embedding_image_input": true }, "fireworks_ai/accounts/fireworks/models/deepseek-v4-flash-0731": { - "cache_read_input_token_cost": 2.8e-08, - "input_cost_per_token": 1.4e-07, + "cache_read_input_token_cost": 7e-09, + "input_cost_per_token": 2.2e-07, "litellm_provider": "fireworks_ai", "max_input_tokens": 1048576, "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 2.8e-07, + "output_cost_per_token": 6.6e-07, "source": "https://docs.fireworks.ai/serverless/pricing", "supports_function_calling": true, "supports_reasoning": true, @@ -51753,5 +52047,2034 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true + }, + "novita/zai-org/glm-5.3": { + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.4e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-v4-pro-0813": { + "cache_read_input_token_cost": 1.3200000000000002e-07, + "input_cost_per_token": 1.32e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 3.96e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/moonshotai/kimi-k3": { + "cache_read_input_token_cost": 3e-07, + "input_cost_per_token": 3e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 1048576, + "max_tokens": 1048576, + "mode": "chat", + "output_cost_per_token": 1.5e-05, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/tencent/hy3": { + "cache_read_input_token_cost": 3.5e-08, + "input_cost_per_token": 1.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 5.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-5.2": { + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.4e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/moonshotai/kimi-k2.7-code": { + "cache_read_input_token_cost": 1.9e-07, + "input_cost_per_token": 9.499999999999999e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek-v4-flash-vision-exp": { + "cache_read_input_token_cost": 2.8e-08, + "input_cost_per_token": 4.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 1.32e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek-v4-flash-0731": { + "cache_read_input_token_cost": 2.8e-08, + "input_cost_per_token": 4.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 1.32e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/mindai/macaron-v1-venti": { + "cache_read_input_token_cost": 3e-07, + "input_cost_per_token": 1.5e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.5e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m3": { + "cache_read_input_token_cost": 6e-08, + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 1000000, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1.2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek-v4-flash": { + "cache_read_input_token_cost": 2.8e-08, + "input_cost_per_token": 1.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 2.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-v4-pro": { + "cache_read_input_token_cost": 1.35e-07, + "input_cost_per_token": 1.6000000000000001e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 3.2000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/inclusionai/ling-3.0-flash-fast": { + "cache_read_input_token_cost": 1.2e-08, + "input_cost_per_token": 6e-08, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 1.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.8-max": { + "cache_read_input_token_cost": 2.5e-07, + "input_cost_per_token": 2e-06, + "litellm_provider": "novita", + "max_input_tokens": 1000000, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 6e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/inclusionai/ling-3.0-flash": { + "cache_read_input_token_cost": 1.2e-08, + "input_cost_per_token": 6e-08, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 1.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/mindai/macaron-v1-tall": { + "cache_read_input_token_cost": 8e-08, + "input_cost_per_token": 4.5000000000000003e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 2.6e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/stepfun/step-3.7-flash": { + "cache_read_input_token_cost": 4e-08, + "input_cost_per_token": 2.0000000000000002e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 256000, + "max_tokens": 256000, + "mode": "chat", + "output_cost_per_token": 1.15e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/nvidia/nemotron-3-nano-30b-a3b": { + "input_cost_per_token": 5.0000000000000004e-08, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 2.0000000000000002e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/baidu/cobuddy": { + "cache_read_input_token_cost": 7e-08, + "input_cost_per_token": 2.8e-07, + "litellm_provider": "novita", + "max_input_tokens": 131072, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 1.13e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/xiaomimimo/mimo-v2.5": { + "cache_read_input_token_cost": 3.4e-09, + "input_cost_per_token": 1.6800000000000002e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 3.3600000000000004e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.7-max": { + "cache_read_input_token_cost": 2.5e-07, + "input_cost_per_token": 1.25e-06, + "litellm_provider": "novita", + "max_input_tokens": 1000000, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.75e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/xiaomimimo/mimo-v2.5-pro": { + "cache_read_input_token_cost": 4.3e-09, + "input_cost_per_token": 5.22e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1.044e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.6-27b": { + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.6000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/moonshotai/kimi-k2.6": { + "cache_read_input_token_cost": 1.6e-07, + "input_cost_per_token": 8.000000000000001e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 3.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/zai-org/glm-5.1": { + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.38e-06, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m2.7-highspeed": { + "cache_read_input_token_cost": 6e-08, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 2.4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-5v-turbo": { + "cache_read_input_token_cost": 2.4e-07, + "input_cost_per_token": 1.2e-06, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/google/gemma-4-26b-a4b-it": { + "input_cost_per_token": 1.3e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.0000000000000003e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/google/gemma-4-31b-it": { + "input_cost_per_token": 1.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.0000000000000003e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/zai-org/glm-5-turbo": { + "cache_read_input_token_cost": 2.4e-07, + "input_cost_per_token": 1.2e-06, + "litellm_provider": "novita", + "max_input_tokens": 202800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m2.7": { + "cache_read_input_token_cost": 6e-08, + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1.2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m2.5-highspeed": { + "cache_read_input_token_cost": 3e-08, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131100, + "max_tokens": 131100, + "mode": "chat", + "output_cost_per_token": 2.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.5-27b": { + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 2.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.5-122b-a10b": { + "input_cost_per_token": 4.0000000000000003e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.2000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.5-35b-a3b": { + "input_cost_per_token": 2.5e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.5-397b-a17b": { + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.6000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/minimax/minimax-m2.5": { + "cache_read_input_token_cost": 3e-08, + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131100, + "max_tokens": 131100, + "mode": "chat", + "output_cost_per_token": 1.2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-5": { + "cache_read_input_token_cost": 2.0000000000000002e-07, + "input_cost_per_token": 1e-06, + "litellm_provider": "novita", + "max_input_tokens": 202800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 3.2000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3-coder-next": { + "input_cost_per_token": 2.0000000000000002e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 1.5e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-ocr-2": { + "input_cost_per_token": 3e-08, + "litellm_provider": "novita", + "max_input_tokens": 8192, + "max_output_tokens": 8192, + "max_tokens": 8192, + "mode": "chat", + "output_cost_per_token": 3e-08, + "source": "https://novita.ai/pricing", + "supports_vision": true + }, + "novita/moonshotai/kimi-k2.5": { + "cache_read_input_token_cost": 1.0000000000000001e-07, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 3e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/zai-org/glm-4.7-h": { + "cache_read_input_token_cost": 1.1e-07, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 2.2e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-4.7-flash": { + "cache_read_input_token_cost": 1e-08, + "input_cost_per_token": 7e-08, + "litellm_provider": "novita", + "max_input_tokens": 200000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 4.0000000000000003e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.6-35b-a3b": { + "input_cost_per_token": 2.48e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 1.4850000000000002e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek_v3": { + "input_cost_per_token": 8.900000000000001e-07, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 16000, + "max_tokens": 16000, + "mode": "chat", + "output_cost_per_token": 8.900000000000001e-07, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-r1": { + "input_cost_per_token": 4e-06, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 16000, + "max_tokens": 16000, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-v3/community": { + "input_cost_per_token": 8.900000000000001e-07, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 8000, + "max_tokens": 8000, + "mode": "chat", + "output_cost_per_token": 8.900000000000001e-07, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-r1/community": { + "input_cost_per_token": 4e-06, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 8000, + "max_tokens": 8000, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/thudm/glm-4-32b-0414": { + "input_cost_per_token": 5.5e-07, + "litellm_provider": "novita", + "max_input_tokens": 32000, + "max_output_tokens": 32000, + "max_tokens": 32000, + "mode": "chat", + "output_cost_per_token": 1.66e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/meta-llama/llama-3.2-1b-instruct": { + "input_cost_per_token": 2e-08, + "litellm_provider": "novita", + "max_input_tokens": 131000, + "max_output_tokens": 32000, + "max_tokens": 32000, + "mode": "chat", + "output_cost_per_token": 2e-08, + "source": "https://api.novita.ai/v3/openai/models", + "supports_response_schema": true, + "supports_vision": false + }, + "wandb/deepseek-ai/DeepSeek-V4-Flash": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 2.8e-07, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/deepseek-ai/DeepSeek-V4-Flash-0731": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.3e-07, + "output_cost_per_token": 2.8e-07, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/deepseek-ai/DeepSeek-V4-Pro": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.15e-06, + "output_cost_per_token": 2.55e-06, + "cache_read_input_token_cost": 2e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/google/gemma-4-31B-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 3.4e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/ibm-granite/granite-4.1-8b": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 1e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/JetBrains/Mellum2-12B-A2.5B-Instruct": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 1e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/meta-llama/Llama-3.1-70B-Instruct": { + "max_tokens": 128000, + "max_input_tokens": 128000, + "input_cost_per_token": 8e-07, + "output_cost_per_token": 8e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/MiniMaxAI/MiniMax-M3": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.3e-07, + "output_cost_per_token": 9.6e-07, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/moonshotai/Kimi-K2.7-Code": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.1e-07, + "output_cost_per_token": 3.5e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/moonshotai/Kimi-K2.6": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 6.5e-07, + "output_cost_per_token": 3.41e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 2.5e-07, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 2.75e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/OpenPipe/Qwen3-14B-Instruct": { + "max_tokens": 32768, + "max_input_tokens": 32768, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 2.2e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.8-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.6-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.25e-06, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.6-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 6e-07, + "output_cost_per_token": 3.6e-06, + "cache_read_input_token_cost": 1.2e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.5-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.25e-06, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3-30B-A3B-Instruct-2507": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 3e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/zai-org/GLM-5.2": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.6e-07, + "output_cost_per_token": 2.42e-06, + "cache_read_input_token_cost": 1.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "deepinfra/openai/gpt-oss-120b-Turbo": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 6e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/MiniMaxAI/MiniMax-M2.7": { + "max_tokens": 196608, + "max_input_tokens": 196608, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1e-06, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.8-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-31B-it-Ultra": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2.7e-07, + "output_cost_per_token": 7.6e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K2.5": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4.5e-07, + "output_cost_per_token": 2.25e-06, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-4.7-Flash": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 6e-08, + "output_cost_per_token": 4e-07, + "cache_read_input_token_cost": 1e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-4.6": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 2e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-opus-4-8": { + "input_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "prompt_cache_min_tokens": 1024, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/anthropic/claude-sonnet-4-6": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 3e-06, + "output_cost_per_token": 1.5e-05, + "litellm_provider": "deepinfra", + "mode": "chat", + "prompt_cache_min_tokens": 1024, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_adaptive_thinking": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.5-flash": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 1.5e-06, + "output_cost_per_token": 9e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/XiaomiMiMo/MiMo-V2.5": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 2e-06, + "cache_read_input_token_cost": 8e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-Max": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1.2e-06, + "output_cost_per_token": 6e-06, + "cache_read_input_token_cost": 2.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-31B-it-turbo": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 9e-08, + "output_cost_per_token": 3.4e-07, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/thinkingmachines/Inkling-Small": { + "max_tokens": 524288, + "max_input_tokens": 524288, + "input_cost_per_token": 4.5e-07, + "output_cost_per_token": 1.2e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/meta-models/Muse-Glimmer-30B": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 3e-07, + "output_cost_per_token": 1.2e-06, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-Max-Thinking": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1.2e-06, + "output_cost_per_token": 6e-06, + "cache_read_input_token_cost": 2.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-VL-235B-A22B-Instruct": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 8.8e-07, + "cache_read_input_token_cost": 1.1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-VL-30B-A3B-Instruct": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 6e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.6e-07, + "output_cost_per_token": 2.6e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.6-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 9.5e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/nvidia/Nemotron-Content-Safety-3.5": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 2e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-opus-5": { + "input_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "prompt_cache_min_tokens": 512, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/thinkingmachines/Inkling": { + "max_tokens": 524288, + "max_input_tokens": 524288, + "input_cost_per_token": 9.5e-07, + "output_cost_per_token": 4.05e-06, + "cache_read_input_token_cost": 1.6e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K2.6": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 3.5e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Pro-0813": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.3e-06, + "output_cost_per_token": 2.6e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.7-Max": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 2.5e-06, + "output_cost_per_token": 7.5e-06, + "cache_read_input_token_cost": 5e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-2.0-mini": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 4e-07, + "cache_read_input_token_cost": 2e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.8-2.4T-A95B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2e-06, + "output_cost_per_token": 6e-06, + "cache_read_input_token_cost": 2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/MiniMaxAI/MiniMax-M3": { + "max_tokens": 524288, + "max_input_tokens": 524288, + "input_cost_per_token": 2.8e-07, + "output_cost_per_token": 1.1e-06, + "cache_read_input_token_cost": 5.6e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.1-flash-lite": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.5e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.7-flash": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 3.75e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/inclusionAI/Ling-3.0-flash": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 6e-08, + "output_cost_per_token": 1.8e-07, + "cache_read_input_token_cost": 1.2e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/stepfun-ai/Step-3.7-Flash": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 1.15e-06, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 1e-06, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-1.8": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 2e-06, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/tencent/Hy3": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 5.8e-07, + "cache_read_input_token_cost": 3.5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-2.0-code": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-2.0-pro": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-5": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 6e-07, + "output_cost_per_token": 2.08e-06, + "cache_read_input_token_cost": 1.2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/nvidia/Nemotron-3-Nano-30B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 2e-07, + "cache_read_input_token_cost": 2.5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K2.7-Code": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 6.8e-07, + "output_cost_per_token": 3.4e-06, + "cache_read_input_token_cost": 1.36e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-sonnet-5": { + "input_cost_per_token": 2e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 1e-05, + "prompt_cache_min_tokens": 1024, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/Qwen/Qwen3.5-397B-A17B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4.5e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 2.2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Flash-0731": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 8e-08, + "output_cost_per_token": 1.8e-07, + "cache_read_input_token_cost": 1.6e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-E4B-it": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2e-08, + "output_cost_per_token": 1e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V3.2": { + "max_tokens": 163840, + "max_input_tokens": 163840, + "input_cost_per_token": 2.6e-07, + "output_cost_per_token": 3.8e-07, + "cache_read_input_token_cost": 1.3e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.8-Max": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1.65e-06, + "output_cost_per_token": 4.951e-06, + "cache_read_input_token_cost": 2.06e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-fable-5": { + "input_cost_per_token": 1e-05, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 5e-05, + "prompt_cache_min_tokens": 512, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "thinking_always_on": true + }, + "deepinfra/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 2.2e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-122B-A10B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.9e-07, + "output_cost_per_token": 2.4e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-5.1": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 1.05e-06, + "output_cost_per_token": 3.5e-06, + "cache_read_input_token_cost": 2.05e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Pro": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.3e-06, + "output_cost_per_token": 2.6e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/nvidia/NVIDIA-Nemotron-3-Super-120B-A12B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 8.5e-08, + "output_cost_per_token": 4e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-5.2": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 2.4e-06, + "cache_read_input_token_cost": 1.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K3": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 2.85e-06, + "output_cost_per_token": 1.425e-05, + "cache_read_input_token_cost": 2.85e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-opus-4-7": { + "input_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "prompt_cache_min_tokens": 2048, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/Qwen/Qwen3.6-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 3.2e-07, + "output_cost_per_token": 3.2e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-26B-A4B-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7e-08, + "output_cost_per_token": 3.4e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.1-pro": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 2e-06, + "output_cost_per_token": 1.2e-05, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/XiaomiMiMo/MiMo-V2.5-Pro": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1e-06, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-haiku-4-5": { + "max_tokens": 200000, + "max_input_tokens": 200000, + "input_cost_per_token": 1e-06, + "output_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "prompt_cache_min_tokens": 4096, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Flash": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 9e-08, + "output_cost_per_token": 1.8e-07, + "cache_read_input_token_cost": 1.8e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/openai/gpt-oss-120b-Ultra": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 9.5e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-9B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 1.5e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/MiniMaxAI/MiniMax-M2.7-Turbo": { + "max_tokens": 196608, + "max_input_tokens": 196608, + "input_cost_per_token": 3.8e-07, + "output_cost_per_token": 1.7e-06, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-4.7": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 1.75e-06, + "cache_read_input_token_cost": 8e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-31B-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.3e-07, + "output_cost_per_token": 3.8e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" } } diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py index 308813039ca..2330120adad 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py @@ -34,6 +34,7 @@ from mcp.types import ( ) from mcp.types import Tool as MCPTool from pydantic import AnyUrl, BaseModel +from typing_extensions import ReadOnly import litellm from litellm._logging import verbose_logger @@ -72,6 +73,7 @@ from litellm.proxy._experimental.mcp_server.oauth2_token_cache import ( MCPPerUserTokenCache, mcp_per_user_token_cache, resolve_mcp_auth, + resolved_token_header, ) from litellm.proxy._experimental.mcp_server.oauth_utils import ( _redact_mcp_resource_url, @@ -99,6 +101,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchange_ build_token_exchanger, ) from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( + DEFAULT_CREDENTIAL_HEADER, AuthorizationCodeConfig, ClientCredentialsConfig, CredError, @@ -153,6 +156,8 @@ from litellm.types.mcp import ( MCPAuth, MCPStdioConfig, MCPTokenEndpointAuthMethod, + has_header, + without_header, ) from litellm.types.mcp_server.mcp_server_manager import ( MCPInfo, @@ -349,6 +354,7 @@ class MCPServerConfig(TypedDict, total=False): audience: str subject_token_type: str upstream_resource: str + upstream_token_header: ReadOnly[str] id_jag_resource_token_endpoint: str id_jag_resource: str client_private_key: str @@ -828,18 +834,6 @@ def _should_strip_caller_authorization( ) -def _without_authorization( - headers: dict[str, str] | None, -) -> dict[str, str] | None: - """A copy of ``headers`` with any ``Authorization`` key removed (case-insensitive), or - None if nothing remains. Drops only the credential, keeping other forwarded headers. - """ - if not headers: - return None - filtered: Final = {k: v for k, v in headers.items() if k.lower() != "authorization"} - return filtered or None - - def _format_byok_openapi_auth_header(mcp_server: MCPServer, mcp_auth_header: str) -> str: """Format a raw BYOK credential for OpenAPI tool ``Authorization`` injection. @@ -914,7 +908,9 @@ def _resolve_openapi_tool_auth( if isinstance(per_server, dict): authorization: Final = next((v for k, v in per_server.items() if k.lower() == "authorization"), None) - merged: Final = merge_mcp_headers(extra_headers=forwarded, static_headers=_without_authorization(per_server)) + merged: Final = merge_mcp_headers( + extra_headers=forwarded, static_headers=without_header(per_server, DEFAULT_CREDENTIAL_HEADER) + ) if authorization is None: byok: Final = _format_byok_openapi_auth_header(mcp_server, mcp_auth_header) if mcp_auth_header else None return byok, merged, mcp_auth_header @@ -981,7 +977,7 @@ def _client_forwarded_authorization_headers( raw_headers=raw_headers, user_api_key_auth=user_api_key_auth, ): - return _without_authorization(extra_headers) + return without_header(extra_headers, DEFAULT_CREDENTIAL_HEADER) return extra_headers @@ -994,7 +990,7 @@ def _take_forwarded_authorization( if not headers: return None, headers value: Final = next((v for k, v in headers.items() if k.lower() == "authorization"), None) - return value, _without_authorization(headers) + return value, without_header(headers, DEFAULT_CREDENTIAL_HEADER) def _passthrough_token_from_mcp_auth_header( @@ -2166,6 +2162,7 @@ class MCPServerManager: DEFAULT_SUBJECT_TOKEN_TYPE, ), upstream_resource=server_config.get("upstream_resource", None), + upstream_token_header=server_config.get("upstream_token_header", None), # ID-JAG fields id_jag_resource_token_endpoint=server_config.get("id_jag_resource_token_endpoint", None), id_jag_resource=server_config.get("id_jag_resource", None), @@ -2698,6 +2695,7 @@ class MCPServerManager: or (credentials_dict.get("subject_token_type") if credentials_dict else None) or DEFAULT_SUBJECT_TOKEN_TYPE, upstream_resource=(credentials_dict.get("upstream_resource") if credentials_dict else None), + upstream_token_header=(credentials_dict.get("upstream_token_header") if credentials_dict else None), # ID-JAG fields — read from credentials JSON blob id_jag_resource_token_endpoint=( credentials_dict.get("id_jag_resource_token_endpoint") if credentials_dict else None @@ -3525,10 +3523,9 @@ class MCPServerManager: case Ok(auth): # NoOpAuth has no header_name and so never conflicts. header_name: Final[str | None] = getattr(auth, "header_name", None) - conflicts: Final = bool( - header_name and extra_headers and any(key.lower() == header_name.lower() for key in extra_headers) - ) - if not conflicts: + if header_name is None or not extra_headers: + return auth, extra_headers + if not has_header(extra_headers, header_name): return auth, extra_headers if isinstance( spec.config, @@ -3540,9 +3537,10 @@ class MCPServerManager: # guardrail such as MCPJWTSigner, static_headers, or any other injected # Authorization must NOT shadow it (otherwise the upstream gets e.g. the # signer's JWT instead of the minted token and rejects it, and for M2M the - # one-shot 401 refetch is lost with it). Drop the conflicting header so the - # resolved token reaches upstream. - return auth, _without_authorization(extra_headers) + # one-shot 401 refetch is lost with it). Drop only the header the resolved + # credential is about to occupy, so a static credential the operator aimed at a + # DIFFERENT header still reaches upstream. + return auth, without_header(extra_headers, header_name) # Other modes: an Authorization already supplied via extra_headers (a forwarded caller # header or static_headers) is intentional and wins; v1 applies those last. return None, extra_headers @@ -3650,6 +3648,7 @@ class MCPServerManager: ): spec = None auth_value: Final = await resolve_mcp_auth(resolved_server, mcp_auth_header) if spec is None else None + auth_header_name: Final = resolved_token_header(resolved_server, mcp_auth_header) if spec is None else None # Create sampling and elicitation callbacks for this client sampling_cb = ( @@ -3758,6 +3757,7 @@ class MCPServerManager: transport_type=transport, auth_type=resolved_server.auth_type, auth_value=auth_value, + auth_header_name=auth_header_name, timeout=(resolved_server.timeout if resolved_server.timeout is not None else MCP_CLIENT_TIMEOUT), extra_headers=extra_headers, aws_auth=aws_auth, @@ -5256,7 +5256,9 @@ class MCPServerManager: proxy_logging_obj: Optional ProxyLogging object for hook integration host_progress_callback: Optional callback for progress updates hook_extra_headers: Optional headers injected by pre_mcp_call guardrail - hooks. Merged last (highest priority) into outbound request headers. + hooks. Merged last into outbound request headers, except a hook + Authorization header is dropped when an upstream credential already + occupies the Authorization slot. Returns: CallToolResult from the MCP server @@ -5304,7 +5306,7 @@ class MCPServerManager: raw_headers=raw_headers, user_api_key_auth=user_api_key_auth, ): - extra_headers = _without_authorization(extra_headers) + extra_headers = without_header(extra_headers, DEFAULT_CREDENTIAL_HEADER) elif mcp_server.is_client_forwarded_token: extra_headers = _client_forwarded_authorization_headers( mcp_server=mcp_server, @@ -5347,27 +5349,26 @@ class MCPServerManager: if hook_extra_headers: if extra_headers is None: extra_headers = {} - if "Authorization" in hook_extra_headers: - if "Authorization" in extra_headers: - verbose_logger.warning( - "MCPServerManager: hook_extra_headers 'Authorization' will overwrite " - "the existing Authorization header from static_headers. " - "The hook JWT will take precedence." - ) - elif server_auth_header is not None: - # server_auth_header is passed separately to _create_mcp_client as - # auth_value. Both will reach the upstream server — warn so admins - # know two Authorization credentials are being sent. - verbose_logger.warning( - "MCPServerManager: hook_extra_headers injects 'Authorization' while " - "server '%s' already has a configured authentication_token. " - "Both credentials will be sent; the hook header is in extra_headers " - "and the server token is in auth_value — the upstream server decides " - "which one wins. Consider unsetting authentication_token if you want " - "the hook JWT to be the sole credential.", - mcp_server.server_name or mcp_server.name, - ) - extra_headers.update(hook_extra_headers) + hook_has_authorization: Final = any(k.lower() == "authorization" for k in hook_extra_headers) + existing_has_authorization: Final = any(k.lower() == "authorization" for k in extra_headers) + server_auth_occupies_authorization: Final = ( + any(k.lower() == "authorization" for k in server_auth_header) + if isinstance(server_auth_header, dict) + else server_auth_header is not None and mcp_server.auth_type != MCPAuth.api_key + ) + if hook_has_authorization and (existing_has_authorization or server_auth_occupies_authorization): + # Mirror the tools/list signer guard: an upstream credential (user OAuth, + # static header, or configured authentication_token) already occupies the + # Authorization slot, so the hook must not replace it. + verbose_logger.warning( + "MCPServerManager: dropping hook-injected 'Authorization' header for " + "server '%s' because an upstream credential already occupies the " + "Authorization slot; the existing credential is kept.", + mcp_server.server_name or mcp_server.name, + ) + extra_headers.update({k: v for k, v in hook_extra_headers.items() if k.lower() != "authorization"}) + else: + extra_headers.update(hook_extra_headers) # Reset to None if no headers were actually added if extra_headers is not None and len(extra_headers) == 0: diff --git a/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py index b3f1da51074..a4ef970b87a 100644 --- a/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py +++ b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py @@ -7,6 +7,7 @@ with ``client_id``, ``client_secret``, and ``token_url``. import asyncio import hashlib +from collections.abc import Mapping from typing import TYPE_CHECKING, Final import httpx @@ -313,9 +314,26 @@ async def resolve_mcp_auth( 1. ``mcp_auth_header`` — per-request/per-user override 2. OAuth2 client_credentials token — auto-fetched and cached 3. ``server.authentication_token`` — static token from config/DB + + ``resolved_token_header`` answers, for the same two inputs, which header the value belongs in. """ if mcp_auth_header: return mcp_auth_header if server.has_client_credentials: return await mcp_oauth2_token_cache.async_get_token(server) return server.authentication_token + + +def resolved_token_header( + server: "MCPServer", + mcp_auth_header: str | Mapping[str, str] | None = None, +) -> str | None: + """Which upstream header the value ``resolve_mcp_auth`` just returned belongs in. + + ``None`` means keep the auth_type default. A caller-supplied ``mcp_auth_header`` is the caller's + own credential aimed at the slot the upstream normally uses, so it never moves; only the values + the gateway resolved from its own config (the minted M2M token, the static token) follow + ``upstream_token_header``. Same inputs and same branch order as ``resolve_mcp_auth``, so the two + cannot disagree about which case they are in. + """ + return None if mcp_auth_header else server.upstream_token_header diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py index 083a98cdd36..16f58ef5b76 100644 --- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py +++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py @@ -47,12 +47,14 @@ def sanitize_openapi_tool_name(raw_name: str) -> str: from litellm._logging import verbose_logger from litellm.litellm_core_utils.url_utils import async_safe_get from litellm.llms.custom_httpx.http_handler import ( + AsyncHTTPHandler, get_async_httpx_client, httpxSpecialProvider, ) from litellm.proxy._experimental.mcp_server.tool_registry import ( global_mcp_tool_registry, ) +from litellm.types.mcp import credential_redirect_hook, custom_credential_slot class _OpenAPIJSONSchema(TypedDict, total=False): @@ -119,6 +121,10 @@ _request_resolved_auth_headers: Final[contextvars.ContextVar[dict[str, str] | No "_request_resolved_auth_headers", default=None ) +_request_upstream_url: Final[contextvars.ContextVar[str | None]] = contextvars.ContextVar( + "_request_upstream_url", default=None +) + def _sanitize_path_parameter_value(param_value: object, param_name: str) -> str: """Ensure path params cannot introduce directory traversal.""" @@ -349,6 +355,35 @@ def build_input_schema(operation: _OpenAPIOperation) -> dict[str, object]: } +async def _drop_credential_across_origin(request: httpx.Request) -> None: + """Apply this request's cross-origin credential guard, if it needs one. + + Reads the per-request context rather than closing over it so the hook is one stable object, which + keeps the guarded client cacheable. A closure would key a new entry per call, and the handler it + built would never be closed. + """ + guard: Final = credential_redirect_hook( + _request_upstream_url.get() or "", custom_credential_slot(_request_resolved_auth_headers.get()) + ) + if guard is not None: + await guard(request) + + +def _upstream_client() -> AsyncHTTPHandler: + """The HTTP client for one upstream call, guarded when a credential rides a custom slot. + + A resolved credential outside ``Authorization`` is not stripped across origins by the client + itself, so this arm installs the same hook the MCP client uses. Both variants come from the + shared cache, so a guarded call reuses its connection pool like any other. + """ + if custom_credential_slot(_request_resolved_auth_headers.get()) is None: + return get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP) + return get_async_httpx_client( + llm_provider=httpxSpecialProvider.MCP, + params={"event_hooks": {"request": [_drop_credential_across_origin]}}, + ) + + def _merge_openapi_tool_request_headers( static_headers: dict[str, str], ) -> dict[str, str]: @@ -510,8 +545,9 @@ def create_tool_function( except (json.JSONDecodeError, TypeError): json_body = {"data": body_value} - client: Final = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP) + client: Final = _upstream_client() upstream: Final = server_label or f"{original_method.upper()} {path}" + url_token: Final = _request_upstream_url.set(url) try: if original_method == "get": @@ -529,6 +565,8 @@ def create_tool_function( except MaskedHTTPStatusError as e: _raise_for_upstream_failure(e.response, upstream, relays_upstream_auth) raise + finally: + _request_upstream_url.reset(url_token) _raise_for_upstream_failure(response, upstream, relays_upstream_auth) return response.text diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py index a5dc75e3829..d61f8395677 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py @@ -21,6 +21,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import ( Result, ) from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( + DEFAULT_CREDENTIAL_HEADER, Ambient, ApiKeyConfig, ApiKeySource, @@ -35,6 +36,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( ClientCredentialsConfig, ClientSecretAuth, CredError, + HeaderCarrier, IdJagConfig, NoneConfig, PassthroughConfig, @@ -45,9 +47,11 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( Subject, TokenExchangeConfig, parse_auth_spec_kind, + validate_header_name, ) __all__ = [ + "DEFAULT_CREDENTIAL_HEADER", "Ambient", "ApiKeyConfig", "ApiKeySource", @@ -63,6 +67,7 @@ __all__ = [ "ClientSecretAuth", "CredError", "Error", + "HeaderCarrier", "IdJagConfig", "NoOpAuth", "NoneConfig", @@ -78,4 +83,5 @@ __all__ = [ "TokenExchangeConfig", "UpstreamCredentialProvider", "parse_auth_spec_kind", + "validate_header_name", ] diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py index 98e239b1d1d..4458ac7f190 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py @@ -20,6 +20,7 @@ from typing_extensions import assert_never from litellm.proxy._experimental.mcp_server.oauth_utils import resolve_upstream_resource from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( + DEFAULT_CREDENTIAL_HEADER, ApiKeyConfig, AuthorizationCodeConfig, ClientAuth, @@ -45,6 +46,15 @@ _TOKEN_EXCHANGE_SUBJECT_TOKEN_DEFAULT: Final = "urn:ietf:params:oauth:token-type _ID_JAG_SUBJECT_TOKEN_DEFAULT: Final = "urn:ietf:params:oauth:token-type:id_token" +def token_header(server: MCPServer) -> str: + """The upstream header this server's resolved credential occupies. + + One owner for every arm, so no spec builder spells the default itself and a server can never + hand two arms different answers. + """ + return server.upstream_token_header or DEFAULT_CREDENTIAL_HEADER + + def to_subject(user_api_key_auth: UserAPIKeyAuth | None, subject_token: str | None) -> Subject: """Map v1's authenticated principal onto the resolver's Subject. @@ -122,7 +132,7 @@ def _oauth2_spec(server: MCPServer, resource: str) -> ServerSpec | None: return ServerSpec( server_id=server.server_id, resource=resource, - config=AuthorizationCodeConfig(), + config=AuthorizationCodeConfig(header_name=token_header(server)), ) return None @@ -140,6 +150,7 @@ def _client_credentials_spec(server: MCPServer, resource: str) -> ServerSpec: server_id=server.server_id, resource=resource, config=ClientCredentialsConfig( + header_name=token_header(server), client_id=server.client_id, client_secret=SecretStr(server.client_secret) if server.client_secret else None, token_url=server.effective_token_url, @@ -173,6 +184,7 @@ def _token_exchange_spec(server: MCPServer, resource: str) -> ServerSpec | None: server_id=server.server_id, resource=resource, config=TokenExchangeConfig( + header_name=token_header(server), profile=profile, subject_token_type=server.subject_token_type or DEFAULT_SUBJECT_TOKEN_TYPE, token_exchange_endpoint=endpoint, @@ -206,7 +218,7 @@ def _shared_key_spec( server_id=server.server_id, resource=resource, config=ApiKeyConfig( - header_name=header_name, + header_name=server.upstream_token_header or header_name, value_prefix=value_prefix, key_source=SharedKey(value=SecretStr(value)), ), @@ -231,6 +243,7 @@ def _id_jag_spec(server: MCPServer, resource: str) -> ServerSpec | None: server_id=server.server_id, resource=resource, config=IdJagConfig( + header_name=token_header(server), org_token_endpoint=org_token_endpoint, resource_token_endpoint=resource_token_endpoint, client_id=client_id, diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/bridge_credentials.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/bridge_credentials.py index 3ec267c1a06..ab5fa65480e 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/bridge_credentials.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/bridge_credentials.py @@ -239,5 +239,6 @@ def resolve_bridge_envelope( if opened.identity.server_id != expected_server_id: return BridgeEnvelopeInvalid() grant: Final = opened.grant - upstream_authorization: Final = f"{grant.token_type} {grant.access_token.get_secret_value()}" + authorization_scheme: Final = "Bearer" if grant.token_type.lower() == "bearer" else grant.token_type + upstream_authorization: Final = f"{authorization_scheme} {grant.access_token.get_secret_value()}" return BridgeEnvelopeAdmitted(identity=opened.identity, upstream_authorization=SecretStr(upstream_authorization)) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/client_credentials.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/client_credentials.py index d0053fbe0a8..da00abfe604 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/client_credentials.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/client_credentials.py @@ -50,6 +50,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import ( from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( ClientCredentialsConfig, CredError, + HeaderCarrier, ) @@ -328,14 +329,21 @@ class ClientCredentialsBearerAuth(httpx.Auth): refetch fails, or the retried request 401s again, the upstream's response stands. """ - def __init__(self, access_token: str, refetch: Callable[[str], Awaitable[str | None]]) -> None: - self.header_name = "Authorization" + def __init__( + self, + access_token: str, + refetch: Callable[[str], Awaitable[str | None]], + carrier: HeaderCarrier, + ) -> None: + self._carrier = carrier + self.header_name = carrier.header_name self._access_token = SecretStr(access_token) self._refetch = refetch async def async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]: token: Final = self._access_token.get_secret_value() - request.headers[self.header_name] = f"Bearer {token}" + name, value = self._carrier.header(token) + request.headers[name] = value response: Final = yield request if response.status_code != 401: return @@ -343,7 +351,8 @@ class ClientCredentialsBearerAuth(httpx.Auth): if fresh is None: return self._access_token = SecretStr(fresh) - request.headers[self.header_name] = f"Bearer {fresh}" + fresh_name, fresh_value = self._carrier.header(fresh) + request.headers[fresh_name] = fresh_value yield request def sync_auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]: diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py index 94c59962b70..3af7b51f432 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py @@ -145,8 +145,8 @@ class UpstreamCredentialProvider: return await self._token_exchange(subject, server, config) case IdJagConfig() as config: return await self._id_jag(subject, server, config) - case AuthorizationCodeConfig(): - return await self._authorization_code(subject, server) + case AuthorizationCodeConfig() as config: + return await self._authorization_code(subject, server, config) case AwsSigV4Config(): return _not_implemented(AuthSpecKind.aws_sigv4) assert_never(server.config) @@ -284,15 +284,19 @@ class UpstreamCredentialProvider: match await self._exchanged_tokens.get_or_compute(slot, _exchange, fingerprint=fingerprint): case Ok(access_token): - return Ok(StaticHeaderAuth(f"Bearer {access_token}")) + header_name, header_value = config.header(access_token) + return Ok(StaticHeaderAuth(header_value, header_name=header_name)) case Error(err): return Error(err) - async def _authorization_code(self, subject: Subject, server: ServerSpec) -> Result[StaticHeaderAuth, CredError]: + async def _authorization_code( + self, subject: Subject, server: ServerSpec, config: AuthorizationCodeConfig + ) -> Result[StaticHeaderAuth, CredError]: token: Final = await self._authz_token(subject, server) if token is None: return Error(CredError.of_unauthorized("Authorization required: complete the OAuth flow for this server.")) - return Ok(StaticHeaderAuth(f"Bearer {token.access_token}", header_name="Authorization")) + header_name, header_value = config.header(token.access_token) + return Ok(StaticHeaderAuth(header_value, header_name=header_name)) async def _client_credentials( self, server_id: str, config: ClientCredentialsConfig @@ -307,7 +311,7 @@ class UpstreamCredentialProvider: match await self._client_credentials_source.get(server_id, config): case Ok(token): refetch: Final = partial(self._client_credentials_source.refetch, server_id, config) - return Ok(ClientCredentialsBearerAuth(token.access_token, refetch)) + return Ok(ClientCredentialsBearerAuth(token.access_token, refetch, config)) case Error(err): return Error(err) @@ -332,7 +336,8 @@ class UpstreamCredentialProvider: inbound.get_secret_value(), server, config, tenant_id=subject.tenant_id ): case Ok(token): - return Ok(StaticHeaderAuth(f"Bearer {token.access_token}", header_name="Authorization")) + header_name, header_value = config.header(token.access_token) + return Ok(StaticHeaderAuth(header_value, header_name=header_name)) case Error(err): return Error(err) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py index ce9948f0448..67aad3e443e 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py @@ -31,7 +31,7 @@ from enum import Enum from typing import Annotated, Final, Literal from expression import case, tag, tagged_union -from pydantic import BaseModel, ConfigDict, Field, SecretStr +from pydantic import BaseModel, ConfigDict, Field, SecretStr, field_validator from typing_extensions import assert_never from litellm.proxy._experimental.mcp_server.outbound_credentials.result import ( @@ -39,7 +39,11 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import ( Ok, Result, ) -from litellm.types.mcp import DEFAULT_SUBJECT_TOKEN_TYPE +from litellm.types.mcp import ( + DEFAULT_CREDENTIAL_HEADER, + DEFAULT_SUBJECT_TOKEN_TYPE, + normalize_upstream_header_name, +) class AuthSpecKind(str, Enum): @@ -161,7 +165,52 @@ class CredError: assert_never(self.tag) -class AuthorizationCodeConfig(BaseModel): +def validate_header_name(raw: str) -> Result[str, CredError]: + """``normalize_upstream_header_name`` with this package's error-as-value policy. + + The grammar itself lives in ``litellm.types.mcp`` so the v1 model, the management endpoint and + this vocabulary all judge a header name the same way while each keeps its own failure shape. + """ + normalized: Final = normalize_upstream_header_name(raw) + if normalized is None: + return Error(CredError.of_misconfigured(f"invalid upstream header name: {raw!r}")) + return Ok(normalized) + + +class HeaderCarrier(BaseModel): + """Where a resolved credential is written upstream, and how its value is formatted. + + ``Authorization: Bearer`` is only OAuth's *default* conveyance (RFC 6750 section 2.1), not its + only one: an ESB or API gateway commonly terminates its own credential in a private header while + a second credential passes through to the origin, so a credential has to be able to say which + slot it owns. Modeled like OpenAPI's apiKey scheme, so any upstream convention is expressible + (Authorization + Bearer, a raw value on X-API-Key, Ocp-Apim-Subscription-Key, esb-oauth, ...). + + Every config whose credential the gateway mints or holds inherits this, so no resolver arm names + a header itself and the conflict rule in ``_resolve_v2_auth`` can always ask the auth object + which slot it is about to occupy. ``passthrough`` deliberately does not: it forwards the + caller's own credential into the slot the caller used, and mints nothing to place. + """ + + model_config = ConfigDict(frozen=True) + header_name: str = DEFAULT_CREDENTIAL_HEADER + value_prefix: str = "Bearer" + + @field_validator("header_name") + @classmethod + def _check_header_name(cls, value: str) -> str: + match validate_header_name(value): + case Ok(name): + return name + case Error(err): + raise ValueError(err.summary) + + def header(self, value: str) -> tuple[str, str]: + formatted: Final = f"{self.value_prefix} {value}" if self.value_prefix else value + return self.header_name, formatted + + +class AuthorizationCodeConfig(HeaderCarrier): """Per-user 3LO; the gateway is the OAuth client and stores the user's token. Endpoints are discovered (RFC 9728 -> RFC 8414) and the client is registered via DCR @@ -179,7 +228,7 @@ class AuthorizationCodeConfig(BaseModel): token_url: str | None = None -class ClientCredentialsConfig(BaseModel): +class ClientCredentialsConfig(HeaderCarrier): """M2M service account; one upstream identity for every user. Fields are optional so the config can be built incomplete: a value may be supplied at @@ -203,7 +252,7 @@ class ClientCredentialsConfig(BaseModel): token_endpoint_auth_method: Literal["client_secret_post", "client_secret_basic"] | None = None -class TokenExchangeConfig(BaseModel): +class TokenExchangeConfig(HeaderCarrier): """OBO: swap the caller's live inbound token for a token bound to the upstream's audience. The gateway authenticates to the exchange endpoint as an OAuth client (`client_id`/`client_secret`); the inbound token is sent only to that endpoint, never to the upstream. @@ -255,7 +304,7 @@ class ClientSecretAuth(BaseModel): ClientAuth = Annotated[PrivateKeyJwtAuth | ClientSecretAuth, Field(discriminator="source")] -class IdJagConfig(BaseModel): +class IdJagConfig(HeaderCarrier): """draft-ietf-oauth-identity-assertion-authz-grant (Okta "AI agent token exchange"). Two legs: leg 1 is an RFC 8693 token exchange at the IdP org AS (`org_token_endpoint`) that @@ -297,23 +346,16 @@ class Byok(BaseModel): ApiKeySource = Annotated[SharedKey | Byok, Field(discriminator="source")] -class ApiKeyConfig(BaseModel): +class ApiKeyConfig(HeaderCarrier): """A fixed credential injected as a header. The value is shared (in config) or seeded - per-user (pulled from the store); `header_name` and `value_prefix` say where and how it is - written, modeled like OpenAPI's apiKey scheme so any upstream convention is expressible - (Authorization + Bearer, a raw value on X-API-Key, Ocp-Apim-Subscription-Key, etc.). + per-user (pulled from the store); the inherited `header_name` and `value_prefix` say where + and how it is written. """ model_config = ConfigDict(frozen=True) kind: Literal[AuthSpecKind.api_key] = AuthSpecKind.api_key - header_name: str = "Authorization" - value_prefix: str = "Bearer" key_source: ApiKeySource - def header(self, value: str) -> tuple[str, str]: - formatted: Final = f"{self.value_prefix} {value}" if self.value_prefix else value - return self.header_name, formatted - class PassthroughConfig(BaseModel): """Client-driven upstream OAuth; the gateway forwards the client's upstream token.""" diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py index 3c6eb06bc71..c6b2ac489bb 100644 --- a/litellm/proxy/_experimental/mcp_server/server.py +++ b/litellm/proxy/_experimental/mcp_server/server.py @@ -246,11 +246,12 @@ def _mcp_meta_trace_carrier(req_ctx: object) -> dict[str, str] | None: """The W3C trace context (``traceparent``/``tracestate``) the MCP client propagated in the request's ``params._meta`` (SEP-414), or ``None``. - When present, per the OTel MCP semconv the MCP span parents to this propagated - context rather than to the HTTP transport (which is recorded as a link instead). - When absent, the span nests under the transport span of the request carrying - this specific message, so a streamable-HTTP session that multiplexes many - messages still does not glue every message under the session's first request; + When present, the MCP span records this propagated context as a span *link*, + never the parent — a remote parent would root the span in a trace whose root + never reaches the gateway's tracing backend. The span itself nests under the + transport span of the request carrying this specific message, so a + streamable-HTTP session that multiplexes many messages still does not glue + every message under the session's first request; see ``resolve_mcp_span_context``. The client's W3C Baggage is deliberately excluded: it is caller-controlled, and the otel baggage processor stamps allowlisted baggage keys (``litellm.team.id``, ``litellm.metadata.*``, @@ -432,7 +433,6 @@ if MCP_AVAILABLE: _client_forwarded_authorization_headers, _resolve_openapi_tool_auth, _should_strip_caller_authorization, - _without_authorization, global_mcp_server_manager, ) from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import ( @@ -451,6 +451,7 @@ if MCP_AVAILABLE: split_server_prefix_from_name, strip_known_server_prefix, ) + from litellm.types.mcp import DEFAULT_CREDENTIAL_HEADER, without_header ###################################################### ############ MCP Tools List REST API Response Object # @@ -1732,7 +1733,7 @@ if MCP_AVAILABLE: raw_headers=raw_headers, user_api_key_auth=user_api_key_auth, ): - extra_headers = _without_authorization(extra_headers) + extra_headers = without_header(extra_headers, DEFAULT_CREDENTIAL_HEADER) elif is_client_forwarded_mode: if not withhold_forwarded_authorization: extra_headers = _client_forwarded_authorization_headers( diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.json index 0e3cbbfd560..1963c7799a2 100644 --- a/litellm/proxy/_lazy_openapi_snapshot.json +++ b/litellm/proxy/_lazy_openapi_snapshot.json @@ -17,6 +17,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -283,6 +290,174 @@ } } }, + "a2a_registration": { + "components": { + "schemas": { + "DiscoverAgentRequest": { + "properties": { + "discovery_mode": { + "$ref": "#/components/schemas/DiscoveryMode", + "default": "well_known_fallback", + "description": "How to locate the upstream card. ``well_known_fallback`` for pure A2A agents (try standard paths); ``langgraph_platform`` for LangGraph Platform deployments where the card is shared across assistants and disambiguated by a query parameter." + }, + "params": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "description": "Mode-specific parameters. ``langgraph_platform`` requires ``{'assistant_id': }``. ``well_known_fallback`` ignores this.", + "title": "Params" + }, + "url": { + "description": "Base URL of the upstream agent. Behavior depends on ``discovery_mode``: ``well_known_fallback`` (default) tries /.well-known/agent-card.json, /.well-known/agent.json, /agent.json under this URL in order; ``langgraph_platform`` hits ``/.well-known/agent-card.json?assistant_id=`` instead.", + "title": "Url", + "type": "string" + } + }, + "required": [ + "url" + ], + "title": "DiscoverAgentRequest", + "type": "object" + }, + "DiscoverAgentResponse": { + "properties": { + "agent_card": { + "additionalProperties": true, + "title": "Agent Card", + "type": "object" + }, + "url": { + "title": "Url", + "type": "string" + } + }, + "required": [ + "url", + "agent_card" + ], + "title": "DiscoverAgentResponse", + "type": "object" + }, + "DiscoveryMode": { + "description": "How to locate the upstream agent card.\n\nString-valued so it serializes cleanly over JSON / Pydantic.", + "enum": [ + "well_known_fallback", + "langgraph_platform" + ], + "title": "DiscoveryMode", + "type": "string" + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "title": "Detail", + "type": "array" + } + }, + "title": "HTTPValidationError", + "type": "object" + }, + "ValidationError": { + "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, + "loc": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "title": "Location", + "type": "array" + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + }, + "required": [ + "loc", + "msg", + "type" + ], + "title": "ValidationError", + "type": "object" + } + } + }, + "paths": { + "/v1/a2a/discover": { + "post": { + "description": "Fetch the upstream agent's well-known card so the UI can show the admin\nwhich skills/capabilities the agent exposes.\n\nOnly proxy admins can call this \u2014 the UI uses it during agent registration,\nand we don't want arbitrary keys probing internal URLs.\n\nExample:\n```bash\ncurl -X POST \"http://localhost:4000/v1/a2a/discover\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"url\": \"https://upstream-agent.example.com\"}'\n```", + "operationId": "discover_agent_card_v1_a2a_discover_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiscoverAgentRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiscoverAgentResponse" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Discover Agent Card", + "tags": [ + "a2a_registration" + ] + } + } + } + }, "access_groups": { "components": { "schemas": { @@ -782,6 +957,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -1939,6 +2121,41 @@ "title": "AgentInterface", "type": "object" }, + "AgentKeySummary": { + "properties": { + "key_alias": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Key Alias" + }, + "key_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Key Name" + }, + "token": { + "title": "Token", + "type": "string" + } + }, + "required": [ + "token" + ], + "title": "AgentKeySummary", + "type": "object" + }, "AgentMakePublicResponse": { "properties": { "message": { @@ -2111,6 +2328,20 @@ ], "title": "Extra Headers" }, + "keys": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/AgentKeySummary" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Keys" + }, "litellm_params": { "anyOf": [ { @@ -2418,6 +2649,11 @@ "title": "Total Api Requests", "type": "integer" }, + "total_autorouter_savings_spend": { + "default": 0.0, + "title": "Total Autorouter Savings Spend", + "type": "number" + }, "total_cache_creation_input_tokens": { "default": 0, "title": "Total Cache Creation Input Tokens", @@ -2433,16 +2669,36 @@ "title": "Total Completion Tokens", "type": "integer" }, + "total_compression_saved_tokens": { + "default": 0, + "title": "Total Compression Saved Tokens", + "type": "integer" + }, + "total_compression_savings_spend": { + "default": 0.0, + "title": "Total Compression Savings Spend", + "type": "number" + }, "total_failed_requests": { "default": 0, "title": "Total Failed Requests", "type": "integer" }, + "total_flat_cost": { + "default": 0.0, + "title": "Total Flat Cost", + "type": "number" + }, "total_pages": { "default": 1, "title": "Total Pages", "type": "integer" }, + "total_prompt_caching_savings_spend": { + "default": 0.0, + "title": "Total Prompt Caching Savings Spend", + "type": "number" + }, "total_prompt_tokens": { "default": 0, "title": "Total Prompt Tokens", @@ -2504,8 +2760,7 @@ }, "required": [ "type", - "scheme", - "bearerFormat" + "scheme" ], "title": "HTTPAuthSecurityScheme", "type": "object" @@ -2670,8 +2925,7 @@ }, "required": [ "type", - "flows", - "oauth2MetadataUrl" + "flows" ], "title": "OAuth2SecurityScheme", "type": "object" @@ -2881,6 +3135,11 @@ "title": "Api Requests", "type": "integer" }, + "autorouter_savings_spend": { + "default": 0.0, + "title": "Autorouter Savings Spend", + "type": "number" + }, "cache_creation_input_tokens": { "default": 0, "title": "Cache Creation Input Tokens", @@ -2896,11 +3155,31 @@ "title": "Completion Tokens", "type": "integer" }, + "compression_saved_tokens": { + "default": 0, + "title": "Compression Saved Tokens", + "type": "integer" + }, + "compression_savings_spend": { + "default": 0.0, + "title": "Compression Savings Spend", + "type": "number" + }, "failed_requests": { "default": 0, "title": "Failed Requests", "type": "integer" }, + "flat_cost": { + "default": 0.0, + "title": "Flat Cost", + "type": "number" + }, + "prompt_caching_savings_spend": { + "default": 0.0, + "title": "Prompt Caching Savings Spend", + "type": "number" + }, "prompt_tokens": { "default": 0, "title": "Prompt Tokens", @@ -2927,6 +3206,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -3171,7 +3457,7 @@ ] }, "post": { - "description": "Create a new agent\n\nExample Request:\n```bash\ncurl -X POST \"http://localhost:4000/v1/agents\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"agent_name\": \"my-custom-agent\",\n \"agent_card_params\": {\n \"protocolVersion\": \"1.0\",\n \"name\": \"Hello World Agent\",\n \"description\": \"Just a hello world agent\",\n \"url\": \"http://localhost:9999/\",\n \"version\": \"1.0.0\",\n \"defaultInputModes\": [\"text\"],\n \"defaultOutputModes\": [\"text\"],\n \"capabilities\": {\n \"streaming\": true\n },\n \"skills\": [\n {\n \"id\": \"hello_world\",\n \"name\": \"Returns hello world\",\n \"description\": \"just returns hello world\",\n \"tags\": [\"hello world\"],\n \"examples\": [\"hi\", \"hello world\"]\n }\n ]\n },\n \"litellm_params\": {\n \"make_public\": true\n }\n }'\n```", + "description": "Create a new agent\n\nExample Request:\n```bash\ncurl -X POST \"http://localhost:4000/v1/agents\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"agent_name\": \"my-custom-agent\",\n \"agent_card_params\": {\n \"protocolVersion\": \"1.0\",\n \"name\": \"Hello World Agent\",\n \"description\": \"Just a hello world agent\",\n \"url\": \"http://localhost:9999/\",\n \"version\": \"1.0.0\",\n \"defaultInputModes\": [\"text\"],\n \"defaultOutputModes\": [\"text\"],\n \"capabilities\": {\n \"streaming\": true\n },\n \"skills\": [\n {\n \"id\": \"hello_world\",\n \"name\": \"Returns hello world\",\n \"description\": \"just returns hello world\",\n \"tags\": [\"hello world\"],\n \"examples\": [\"hi\", \"hello world\"]\n }\n ]\n },\n \"litellm_params\": {\n \"make_public\": true\n }\n }'\n```", "operationId": "create_agent_v1_agents_post", "requestBody": { "content": { @@ -3265,7 +3551,7 @@ }, "/v1/agents/{agent_id}": { "delete": { - "description": "Delete an agent\n\nExample Request:\n```bash\ncurl -X DELETE \"http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \"\n```\n\nExample Response:\n```json\n{\n \"message\": \"Agent 123e4567-e89b-12d3-a456-426614174000 deleted successfully\"\n}\n```", + "description": "Delete an agent\n\nExample Request:\n```bash\ncurl -X DELETE \"http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \"\n```\n\nExample Response:\n```json\n{\n \"message\": \"Agent 123e4567-e89b-12d3-a456-426614174000 deleted successfully\"\n}\n```", "operationId": "delete_agent_v1_agents__agent_id__delete", "parameters": [ { @@ -3309,7 +3595,7 @@ ] }, "get": { - "description": "Get a specific agent by ID\n\nExample Request:\n```bash\ncurl -X GET \"http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \"\n```", + "description": "Get a specific agent by ID\n\nExample Request:\n```bash\ncurl -X GET \"http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \"\n```", "operationId": "get_agent_by_id_v1_agents__agent_id__get", "parameters": [ { @@ -3355,7 +3641,7 @@ ] }, "patch": { - "description": "Update an existing agent\n\nExample Request:\n```bash\ncurl -X PUT \"http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"agent\": {\n \"agent_name\": \"updated-agent\",\n \"agent_card_params\": {\n \"protocolVersion\": \"1.0\",\n \"name\": \"Updated Agent\",\n \"description\": \"Updated description\",\n \"url\": \"http://localhost:9999/\",\n \"version\": \"1.1.0\",\n \"defaultInputModes\": [\"text\"],\n \"defaultOutputModes\": [\"text\"],\n \"capabilities\": {\n \"streaming\": true\n },\n \"skills\": []\n },\n \"litellm_params\": {\n \"make_public\": false\n }\n }\n }'\n```", + "description": "Update an existing agent\n\nExample Request:\n```bash\ncurl -X PATCH \"http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"agent_name\": \"updated-agent\",\n \"agent_card_params\": {\n \"protocolVersion\": \"1.0\",\n \"name\": \"Updated Agent\",\n \"description\": \"Updated description\",\n \"url\": \"http://localhost:9999/\",\n \"version\": \"1.1.0\",\n \"defaultInputModes\": [\"text\"],\n \"defaultOutputModes\": [\"text\"],\n \"capabilities\": {\n \"streaming\": true\n },\n \"skills\": []\n },\n \"litellm_params\": {\n \"make_public\": false\n }\n }'\n```", "operationId": "patch_agent_v1_agents__agent_id__patch", "parameters": [ { @@ -3411,7 +3697,7 @@ ] }, "put": { - "description": "Update an existing agent\n\nExample Request:\n```bash\ncurl -X PUT \"http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"agent\": {\n \"agent_name\": \"updated-agent\",\n \"agent_card_params\": {\n \"protocolVersion\": \"1.0\",\n \"name\": \"Updated Agent\",\n \"description\": \"Updated description\",\n \"url\": \"http://localhost:9999/\",\n \"version\": \"1.1.0\",\n \"defaultInputModes\": [\"text\"],\n \"defaultOutputModes\": [\"text\"],\n \"capabilities\": {\n \"streaming\": true\n },\n \"skills\": []\n },\n \"litellm_params\": {\n \"make_public\": false\n }\n }\n }'\n```", + "description": "Update an existing agent\n\nExample Request:\n```bash\ncurl -X PUT \"http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"agent_name\": \"updated-agent\",\n \"agent_card_params\": {\n \"protocolVersion\": \"1.0\",\n \"name\": \"Updated Agent\",\n \"description\": \"Updated description\",\n \"url\": \"http://localhost:9999/\",\n \"version\": \"1.1.0\",\n \"defaultInputModes\": [\"text\"],\n \"defaultOutputModes\": [\"text\"],\n \"capabilities\": {\n \"streaming\": true\n },\n \"skills\": []\n },\n \"litellm_params\": {\n \"make_public\": false\n }\n }'\n```", "operationId": "update_agent_v1_agents__agent_id__put", "parameters": [ { @@ -3535,6 +3821,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -3989,6 +4282,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -4963,7 +5263,7 @@ ] }, "post": { - "description": "Register a new plugin in the LiteLLM marketplace.\n\nLiteLLM acts as a registry/discovery layer. Plugins are hosted on\nGitHub/GitLab/Bitbucket. Claude Code will clone from the git source\nwhen users install.\n\nThis endpoint is create-only and never overwrites. If a plugin with\nthe same name already exists it returns 409 Conflict; use\nPUT /claude-code/plugins/{plugin_name} to update an existing plugin.\n\nParameters:\n - name: Plugin name (kebab-case)\n - source: Git source reference (github, url, or git-subdir format)\n - version: Semantic version (optional)\n - description: Plugin description (optional)\n - author: Author information (optional)\n - homepage: Plugin homepage URL (optional)\n - keywords: Search keywords (optional)\n - category: Plugin category (optional)\n\nReturns:\n Registration status (action is always \"created\") and plugin information.\n\nExample:\n ```bash\n curl -X POST http://localhost:4000/claude-code/plugins \\\n -H \"Authorization: Bearer sk-...\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"my-plugin\",\n \"source\": {\"source\": \"github\", \"repo\": \"org/my-plugin\"},\n \"version\": \"1.0.0\",\n \"description\": \"My awesome plugin\"\n }'\n ```", + "description": "Register a new plugin in the LiteLLM marketplace.\n\nLiteLLM acts as a registry/discovery layer. Plugins are hosted on\nGitHub/GitLab/Bitbucket. Claude Code will clone from the git source\nwhen users install.\n\nThis endpoint is create-only and never overwrites. If a plugin with\nthe same name already exists it returns 409 Conflict; use\nPUT /claude-code/plugins/{plugin_name} to update an existing plugin.\n\nRequires a proxy admin API key.\n\nParameters:\n - name: Plugin name (kebab-case)\n - source: Git source reference (github, url, or git-subdir format)\n - version: Semantic version (optional)\n - description: Plugin description (optional)\n - author: Author information (optional)\n - homepage: Plugin homepage URL (optional)\n - keywords: Search keywords (optional)\n - category: Plugin category (optional)\n\nReturns:\n Registration status (action is always \"created\") and plugin information.\n\nExample:\n ```bash\n curl -X POST http://localhost:4000/claude-code/plugins \\\n -H \"Authorization: Bearer sk-...\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"my-plugin\",\n \"source\": {\"source\": \"github\", \"repo\": \"org/my-plugin\"},\n \"version\": \"1.0.0\",\n \"description\": \"My awesome plugin\"\n }'\n ```", "operationId": "register_plugin_claude_code_plugins_post", "requestBody": { "content": { @@ -5010,7 +5310,7 @@ }, "/claude-code/plugins/{plugin_name}": { "delete": { - "description": "Delete a plugin from the marketplace.\n\nParameters:\n - plugin_name: The name of the plugin to delete", + "description": "Delete a plugin from the marketplace.\n\nRequires a proxy admin API key.\n\nParameters:\n - plugin_name: The name of the plugin to delete", "operationId": "delete_plugin_claude_code_plugins__plugin_name__delete", "parameters": [ { @@ -5098,7 +5398,7 @@ ] }, "put": { - "description": "Update an existing plugin in the LiteLLM marketplace.\n\nThe plugin is identified by its name in the path, which is the resource\nidentity and cannot be changed here. This is a full replace, not a merge:\nthe manifest is rebuilt from the request body, so any optional field left\nout is reset to its default (e.g. an omitted version is cleared, not kept).\nSend the full desired state.\n\nReturns 404 if no plugin with the given name exists; use\nPOST /claude-code/plugins to create a new plugin.\n\nParameters:\n - plugin_name: Name of the plugin to update (path parameter)\n - source: Git source reference (github, url, or git-subdir format)\n - version: Semantic version (optional)\n - description: Plugin description (optional)\n - author: Author information (optional)\n - homepage: Plugin homepage URL (optional)\n - keywords: Search keywords (optional)\n - category: Plugin category (optional)\n\nReturns:\n Update status (action is always \"updated\") and plugin information.\n\nExample:\n ```bash\n curl -X PUT http://localhost:4000/claude-code/plugins/my-plugin \\\n -H \"Authorization: Bearer sk-...\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"source\": {\"source\": \"github\", \"repo\": \"org/my-plugin\"},\n \"version\": \"2.0.0\",\n \"description\": \"My awesome plugin\"\n }'\n ```", + "description": "Update an existing plugin in the LiteLLM marketplace.\n\nThe plugin is identified by its name in the path, which is the resource\nidentity and cannot be changed here. This is a full replace, not a merge:\nthe manifest is rebuilt from the request body, so any optional field left\nout is reset to its default (e.g. an omitted version is cleared, not kept).\nSend the full desired state.\n\nReturns 404 if no plugin with the given name exists; use\nPOST /claude-code/plugins to create a new plugin.\n\nRequires a proxy admin API key.\n\nParameters:\n - plugin_name: Name of the plugin to update (path parameter)\n - source: Git source reference (github, url, or git-subdir format)\n - version: Semantic version (optional)\n - description: Plugin description (optional)\n - author: Author information (optional)\n - homepage: Plugin homepage URL (optional)\n - keywords: Search keywords (optional)\n - category: Plugin category (optional)\n\nReturns:\n Update status (action is always \"updated\") and plugin information.\n\nExample:\n ```bash\n curl -X PUT http://localhost:4000/claude-code/plugins/my-plugin \\\n -H \"Authorization: Bearer sk-...\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"source\": {\"source\": \"github\", \"repo\": \"org/my-plugin\"},\n \"version\": \"2.0.0\",\n \"description\": \"My awesome plugin\"\n }'\n ```", "operationId": "update_plugin_claude_code_plugins__plugin_name__put", "parameters": [ { @@ -5156,7 +5456,7 @@ }, "/claude-code/plugins/{plugin_name}/disable": { "post": { - "description": "Disable a plugin without deleting it.\n\nParameters:\n - plugin_name: The name of the plugin to disable", + "description": "Disable a plugin without deleting it.\n\nRequires a proxy admin API key.\n\nParameters:\n - plugin_name: The name of the plugin to disable", "operationId": "disable_plugin_claude_code_plugins__plugin_name__disable_post", "parameters": [ { @@ -5202,7 +5502,7 @@ }, "/claude-code/plugins/{plugin_name}/enable": { "post": { - "description": "Enable a disabled plugin.\n\nParameters:\n - plugin_name: The name of the plugin to enable", + "description": "Enable a disabled plugin.\n\nRequires a proxy admin API key.\n\nParameters:\n - plugin_name: The name of the plugin to enable", "operationId": "enable_plugin_claude_code_plugins__plugin_name__enable_post", "parameters": [ { @@ -5517,6 +5817,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -5929,6 +6236,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -6245,6 +6559,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -6283,6 +6604,26 @@ "delete": { "description": "Delete Hashicorp Vault configuration. Idempotent.", "operationId": "delete_hashicorp_vault_config_config_overrides_hashicorp_vault_delete", + "parameters": [ + { + "description": "The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability", + "in": "header", + "name": "litellm-changed-by", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability", + "title": "Litellm-Changed-By" + } + } + ], "responses": { "200": { "content": { @@ -6291,6 +6632,16 @@ } }, "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" } }, "security": [ @@ -6331,6 +6682,26 @@ "post": { "description": "Update Hashicorp Vault secret manager configuration.\nSets environment variables, encrypts sensitive fields, and stores in DB.\nReinitializes the secret manager on this pod.", "operationId": "update_hashicorp_vault_config_config_overrides_hashicorp_vault_post", + "parameters": [ + { + "description": "The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability", + "in": "header", + "name": "litellm-changed-by", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability", + "title": "Litellm-Changed-By" + } + } + ], "requestBody": { "content": { "application/json": { @@ -6932,6 +7303,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -7826,6 +8204,251 @@ } } }, + "gemini_agents": { + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "title": "Detail", + "type": "array" + } + }, + "title": "HTTPValidationError", + "type": "object" + }, + "ValidationError": { + "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, + "loc": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "title": "Location", + "type": "array" + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + }, + "required": [ + "loc", + "msg", + "type" + ], + "title": "ValidationError", + "type": "object" + } + } + }, + "paths": { + "/v1beta/agents": { + "get": { + "description": "List all custom agents on the Gemini side.\n\nPass per-request Gemini credentials via the JSON-encoded\n``litellm_params_template`` query parameter. Flat query parameters\n(e.g. ``?api_key=AIza...``) are intentionally ignored \u2014 see\n``_merge_query_params_into_data`` for the rationale.\n\n```bash\ncurl \"http://localhost:4000/v1beta/agents?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D\" \\\n -H \"Authorization: Bearer sk-...\"\n```", + "operationId": "list_gemini_agents_v1beta_agents_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "List Gemini Agents", + "tags": [ + "gemini_agents" + ] + }, + "post": { + "description": "Create a named custom agent on the Gemini side.\n\nExample:\n```bash\ncurl -X POST \"http://localhost:4000/v1beta/agents\" \\\n -H \"Authorization: Bearer sk-...\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"my-custom-slides-agent\",\n \"base_agent\": \"waverunner\",\n \"instructions\": \"You are a helpful assistant that creates slides.\",\n \"base_environment\": {\n \"type\": \"remote\",\n \"sources\": [\n {\"type\": \"gcs\", \"source\": \"gs://eap-templates/slides-skill\",\n \"target\": \"/.agents/skills/slides-skill\"}\n ]\n }\n }'\n```", + "operationId": "create_gemini_agent_v1beta_agents_post", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Create Gemini Agent", + "tags": [ + "gemini_agents" + ] + } + }, + "/v1beta/agents/{name}": { + "delete": { + "description": "Delete a custom agent by name.\n\nPass per-request Gemini credentials via the JSON-encoded\n``litellm_params_template`` query parameter. Flat query parameters\n(e.g. ``?api_key=AIza...``) are intentionally ignored \u2014 see\n``_merge_query_params_into_data`` for the rationale.\n\n```bash\ncurl -X DELETE \"http://localhost:4000/v1beta/agents/my-custom-slides-agent?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D\" \\\n -H \"Authorization: Bearer sk-...\"\n```", + "operationId": "delete_gemini_agent_v1beta_agents__name__delete", + "parameters": [ + { + "in": "path", + "name": "name", + "required": true, + "schema": { + "title": "Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Delete Gemini Agent", + "tags": [ + "gemini_agents" + ] + }, + "get": { + "description": "Get a specific custom agent by name.\n\nPass per-request Gemini credentials via the JSON-encoded\n``litellm_params_template`` query parameter. Flat query parameters\n(e.g. ``?api_key=AIza...``) are intentionally ignored \u2014 see\n``_merge_query_params_into_data`` for the rationale.\n\n```bash\ncurl \"http://localhost:4000/v1beta/agents/my-custom-slides-agent?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D\" \\\n -H \"Authorization: Bearer sk-...\"\n```", + "operationId": "get_gemini_agent_v1beta_agents__name__get", + "parameters": [ + { + "in": "path", + "name": "name", + "required": true, + "schema": { + "title": "Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Get Gemini Agent", + "tags": [ + "gemini_agents" + ] + } + }, + "/v1beta/agents/{name}/versions": { + "get": { + "description": "List versions of a custom agent.\n\nPass per-request Gemini credentials via the JSON-encoded\n``litellm_params_template`` query parameter. Flat query parameters\n(e.g. ``?api_key=AIza...``) are intentionally ignored \u2014 see\n``_merge_query_params_into_data`` for the rationale.\n\n```bash\ncurl \"http://localhost:4000/v1beta/agents/my-custom-slides-agent/versions?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D\" \\\n -H \"Authorization: Bearer sk-...\"\n```", + "operationId": "list_gemini_agent_versions_v1beta_agents__name__versions_get", + "parameters": [ + { + "in": "path", + "name": "name", + "required": true, + "schema": { + "title": "Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "List Gemini Agent Versions", + "tags": [ + "gemini_agents" + ] + } + } + } + }, "guardrails": { "components": { "schemas": { @@ -7917,7 +8540,7 @@ "title": "ApplyGuardrailResponse", "type": "object" }, - "BaseLitellmParams-Input": { + "BaseLitellmParams": { "additionalProperties": true, "properties": { "additional_provider_specific_params": { @@ -8121,7 +8744,7 @@ } ], "default": true, - "description": "Whether to fail the request if Model Armor encounters an error", + "description": "Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.", "title": "Fail On Error" }, "guard_name": { @@ -8196,6 +8819,22 @@ "description": "Optional field if guardrail requires a 'model' parameter", "title": "Model" }, + "on_sensitive_data": { + "anyOf": [ + { + "enum": [ + "block", + "route" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Action to take when sensitive data is detected. 'block' raises an exception (default behavior). 'route' reroutes the request to the model specified in sensitive_data_route_to_model.", + "title": "On Sensitive Data" + }, "on_violation": { "anyOf": [ { @@ -8212,6 +8851,19 @@ "description": "For /v1/realtime sessions: 'warn' speaks the violation message and continues; 'end_session' speaks the message and closes the connection.", "title": "On Violation" }, + "only_scan_new_messages": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "description": "When True, the guardrail only scans messages that have not already been scanned earlier in the same session (identified by litellm_session_id / session_id). Message content is hashed per session and cached; only the diff (new or edited messages) is sent to the guardrail provider on follow-up calls. Falls back to a full scan when the request has no session id or the cache is unavailable. Intended for blocking/detection guardrails; not applied when mask_request_content is set.", + "title": "Only Scan New Messages" + }, "pangea_input_recipe": { "anyOf": [ { @@ -8275,6 +8927,55 @@ "description": "The message the bot speaks aloud when a /v1/realtime guardrail fires. Falls back to violation_message_template if not set.", "title": "Realtime Violation Message" }, + "run_in_parallel": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "When True, this pre_call or post_call guardrail runs concurrently with other opted-in guardrails of the same hook, after the sequential guardrails have run. Use only for block-only guardrails that inspect and reject; do not enable it for guardrails that modify the request or response (e.g. PII masking or sensitive-data routing), since parallel runs share one snapshot and their mutations would race.", + "title": "Run In Parallel" + }, + "sanitize_error_detail": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "For guardrail='model_armor': omit the raw Model Armor response from caller-facing errors and logs by default. Set False to restore verbose output.", + "title": "Sanitize Error Detail" + }, + "scan_only_tool_results": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "When True, unified guardrails only evaluate tool results, the untrusted data an agent feeds back into the model, and skip system, user, and assistant content. Intended for agent harnesses whose own prompt scaffolding is trusted but often trips prompt-attack detectors.", + "title": "Scan Only Tool Results" + }, + "sensitive_data_route_to_model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Model to route requests to when sensitive data is detected and on_sensitive_data='route'. This is typically an on-premise model for data privacy. The routing decision persists for the entire session.", + "title": "Sensitive Data Route To Model" + }, "severity_threshold": { "anyOf": [ { @@ -8296,9 +8997,47 @@ "type": "null" } ], - "description": "When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting.", + "description": "When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting. For Anthropic /v1/messages, the flag applies only to the trusted top-level system prompt. In-sequence system entries are untrusted client input and remain in texts and structured_messages.", "title": "Skip System Message In Guardrail" }, + "skip_tool_message_in_guardrail": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "When True, unified guardrails skip tool-role messages when building evaluation inputs (texts and structured_messages). When False, tool messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_tool_message_in_guardrail setting.", + "title": "Skip Tool Message In Guardrail" + }, + "skip_unscannable_attachments": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "description": "Implemented by guardrail='model_armor'. When True, attachment references that carry no inline bytes (file_id, gs://, or http(s) URLs) pass through unscanned instead of blocking, while fail_on_error still governs real Model Armor API errors. Default False blocks them.", + "title": "Skip Unscannable Attachments" + }, + "sticky_session_routing": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "When True (default), after sensitive data is detected and routed, all subsequent requests in the same session will continue routing to the same model.", + "title": "Sticky Session Routing" + }, "template_id": { "anyOf": [ { @@ -8311,9 +9050,21 @@ "description": "The ID of your Model Armor template", "title": "Template Id" }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Per-request timeout for the guardrail provider API call (seconds). Accepts int, float, or numeric string; coerced to float on load. Each guardrail handler chooses its own default when unset.", + "title": "Timeout" + }, "unreachable_fallback": { "default": "fail_closed", - "description": "Behavior when a guardrail endpoint is unreachable due to network errors. NOTE: This is currently only implemented by guardrail='generic_guardrail_api'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed.", + "description": "Behavior when a guardrail endpoint is unreachable due to network errors. Implemented by guardrail='generic_guardrail_api', 'akto', 'vigil_guard', 'repelloai', 'headroom', and 'compresr'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed.", "enum": [ "fail_closed", "fail_open" @@ -8337,424 +9088,173 @@ "title": "BaseLitellmParams", "type": "object" }, - "BaseLitellmParams-Output": { - "additionalProperties": true, + "BedrockChecksConfigModel": { + "description": "Inline `checks` config for the resource-less Bedrock InvokeGuardrailChecks API.\n\nInclude only the checks you want to run; at least one must be set.", "properties": { - "additional_provider_specific_params": { + "contentFilter": { "anyOf": [ { - "additionalProperties": true, - "type": "object" + "$ref": "#/components/schemas/BedrockChecksContentFilterModel" }, { "type": "null" } - ], - "description": "Additional provider-specific parameters for generic guardrail APIs", - "title": "Additional Provider Specific Params" + ] }, - "api_base": { + "promptAttack": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/BedrockChecksPromptAttackModel" }, { "type": "null" } - ], - "description": "Base URL for the guardrail service API", - "title": "Api Base" + ] }, - "api_endpoint": { + "sensitiveInformation": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/BedrockChecksSensitiveInformationModel" }, { "type": "null" } - ], - "description": "Optional custom API endpoint for Model Armor", - "title": "Api Endpoint" - }, - "api_key": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "API key for the guardrail service", - "title": "Api Key" - }, - "blocked_words": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/BlockedWord" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "List of blocked words with individual actions", - "title": "Blocked Words" - }, - "blocked_words_file": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to YAML file containing blocked_words list", - "title": "Blocked Words File" - }, - "categories": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/ContentFilterCategoryConfig" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "List of prebuilt categories to enable (harmful_*, bias_*)", - "title": "Categories" - }, - "category_thresholds": { - "anyOf": [ - { - "$ref": "#/components/schemas/LakeraCategoryThresholds" - }, - { - "type": "null" - } - ], - "description": "Threshold configuration for Lakera guardrail categories" - }, - "credentials": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to Google Cloud credentials JSON file or JSON string", - "title": "Credentials" - }, - "custom_code": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Python-like code containing the apply_guardrail function for custom guardrail logic", - "title": "Custom Code" - }, - "default_on": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "description": "Whether the guardrail is enabled by default", - "title": "Default On" - }, - "detect_secrets_config": { - "anyOf": [ - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "description": "Configuration for detect-secrets guardrail", - "title": "Detect Secrets Config" - }, - "end_session_after_n_fails": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "For /v1/realtime sessions: automatically close the session after this many guardrail violations.", - "title": "End Session After N Fails" - }, - "experimental_use_latest_role_message_only": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "description": "When True, guardrails only receive the latest message for the relevant role (e.g., newest user input pre-call, newest assistant output post-call)", - "title": "Experimental Use Latest Role Message Only" - }, - "extra_headers": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "Header names to forward from the client request to the guardrail (e.g. x-request-id). Only these headers' values are sent; others may be omitted or sent as [present]. Used by generic_guardrail_api (similar to MCP extra_headers).", - "title": "Extra Headers" - }, - "fail_on_error": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": true, - "description": "Whether to fail the request if Model Armor encounters an error", - "title": "Fail On Error" - }, - "guard_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Name of the guardrail in guardrails.ai", - "title": "Guard Name" - }, - "keyword_redaction_tag": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Tag to use for keyword redaction", - "title": "Keyword Redaction Tag" - }, - "location": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Google Cloud location/region (e.g., us-central1)", - "title": "Location" - }, - "mask_request_content": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "description": "Will mask request content if guardrail makes any changes", - "title": "Mask Request Content" - }, - "mask_response_content": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "description": "Will mask response content if guardrail makes any changes", - "title": "Mask Response Content" - }, - "model": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Optional field if guardrail requires a 'model' parameter", - "title": "Model" - }, - "on_violation": { - "anyOf": [ - { - "enum": [ - "warn", - "end_session" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "description": "For /v1/realtime sessions: 'warn' speaks the violation message and continues; 'end_session' speaks the message and closes the connection.", - "title": "On Violation" - }, - "pangea_input_recipe": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Recipe for input (LLM request)", - "title": "Pangea Input Recipe" - }, - "pangea_output_recipe": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Recipe for output (LLM response)", - "title": "Pangea Output Recipe" - }, - "pattern_redaction_format": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Format string for pattern redaction (use {pattern_name} placeholder)", - "title": "Pattern Redaction Format" - }, - "patterns": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/ContentFilterPattern" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "List of patterns (prebuilt or custom regex) to detect", - "title": "Patterns" - }, - "realtime_violation_message": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The message the bot speaks aloud when a /v1/realtime guardrail fires. Falls back to violation_message_template if not set.", - "title": "Realtime Violation Message" - }, - "severity_threshold": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Minimum severity to block (high, medium, low)", - "title": "Severity Threshold" - }, - "skip_system_message_in_guardrail": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "description": "When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting.", - "title": "Skip System Message In Guardrail" - }, - "template_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The ID of your Model Armor template", - "title": "Template Id" - }, - "unreachable_fallback": { - "default": "fail_closed", - "description": "Behavior when a guardrail endpoint is unreachable due to network errors. NOTE: This is currently only implemented by guardrail='generic_guardrail_api'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed.", - "enum": [ - "fail_closed", - "fail_open" - ], - "title": "Unreachable Fallback", - "type": "string" - }, - "violation_message_template": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Custom message when a guardrail blocks an action. Supports placeholders like {tool_name}, {rule_id}, and {default_message}.", - "title": "Violation Message Template" + ] } }, - "title": "BaseLitellmParams", + "title": "BedrockChecksConfigModel", + "type": "object" + }, + "BedrockChecksContentFilterCategoryItem": { + "properties": { + "category": { + "enum": [ + "VIOLENCE", + "HATE", + "SEXUAL", + "MISCONDUCT", + "INSULTS" + ], + "title": "Category", + "type": "string" + } + }, + "required": [ + "category" + ], + "title": "BedrockChecksContentFilterCategoryItem", + "type": "object" + }, + "BedrockChecksContentFilterModel": { + "properties": { + "categories": { + "items": { + "$ref": "#/components/schemas/BedrockChecksContentFilterCategoryItem" + }, + "title": "Categories", + "type": "array" + } + }, + "required": [ + "categories" + ], + "title": "BedrockChecksContentFilterModel", + "type": "object" + }, + "BedrockChecksPromptAttackCategoryItem": { + "properties": { + "category": { + "enum": [ + "JAILBREAK", + "PROMPT_INJECTION", + "PROMPT_LEAKAGE" + ], + "title": "Category", + "type": "string" + } + }, + "required": [ + "category" + ], + "title": "BedrockChecksPromptAttackCategoryItem", + "type": "object" + }, + "BedrockChecksPromptAttackModel": { + "properties": { + "categories": { + "items": { + "$ref": "#/components/schemas/BedrockChecksPromptAttackCategoryItem" + }, + "title": "Categories", + "type": "array" + } + }, + "required": [ + "categories" + ], + "title": "BedrockChecksPromptAttackModel", + "type": "object" + }, + "BedrockChecksSensitiveInformationEntityItem": { + "properties": { + "type": { + "enum": [ + "ADDRESS", + "AGE", + "AWS_ACCESS_KEY", + "AWS_SECRET_KEY", + "CA_HEALTH_NUMBER", + "CA_SOCIAL_INSURANCE_NUMBER", + "CREDIT_DEBIT_CARD_CVV", + "CREDIT_DEBIT_CARD_EXPIRY", + "CREDIT_DEBIT_CARD_NUMBER", + "DRIVER_ID", + "EMAIL", + "INTERNATIONAL_BANK_ACCOUNT_NUMBER", + "IP_ADDRESS", + "LICENSE_PLATE", + "MAC_ADDRESS", + "NAME", + "PASSWORD", + "PHONE", + "PIN", + "SWIFT_CODE", + "UK_NATIONAL_HEALTH_SERVICE_NUMBER", + "UK_NATIONAL_INSURANCE_NUMBER", + "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER", + "URL", + "USERNAME", + "US_BANK_ACCOUNT_NUMBER", + "US_BANK_ROUTING_NUMBER", + "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER", + "US_PASSPORT_NUMBER", + "US_SOCIAL_SECURITY_NUMBER", + "VEHICLE_IDENTIFICATION_NUMBER" + ], + "title": "Type", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "BedrockChecksSensitiveInformationEntityItem", + "type": "object" + }, + "BedrockChecksSensitiveInformationModel": { + "properties": { + "entities": { + "items": { + "$ref": "#/components/schemas/BedrockChecksSensitiveInformationEntityItem" + }, + "title": "Entities", + "type": "array" + } + }, + "required": [ + "entities" + ], + "title": "BedrockChecksSensitiveInformationModel", "type": "object" }, "BlockedWord": { @@ -8789,6 +9289,187 @@ "title": "BlockedWord", "type": "object" }, + "CiscoAIDefenseGuardrailConfigModelOptionalParams": { + "additionalProperties": true, + "description": "Optional parameters for the Cisco AI Defense guardrail.", + "properties": { + "enabled_rules": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/CiscoAIDefenseRule" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "description": "Explicit list of Cisco AI Defense rules to evaluate. If omitted, the policies configured for the API key in the Cisco AI Defense UI are used.", + "title": "Enabled Rules" + }, + "fallback_on_error": { + "anyOf": [ + { + "enum": [ + "allow", + "block" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": "block", + "description": "Behaviour when the Cisco AI Defense API is unavailable: 'allow' proceeds without scanning (high availability), 'block' rejects the request (maximum security).", + "title": "Fallback On Error" + }, + "inspect_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Override for the inspection endpoint path. Defaults to /api/v1/inspect/chat when inspection_type='chat' and /api/v1/inspect/mcp when inspection_type='mcp'.", + "title": "Inspect Path" + }, + "inspection_type": { + "default": "chat", + "description": "Which Cisco AI Defense inspection surface to use. 'chat' scans LLM model conversations via /api/v1/inspect/chat. 'mcp' scans MCP tool calls via /api/v1/inspect/mcp. Each guardrail instance targets exactly one surface; configure two guardrails to scan both chat and MCP traffic.", + "enum": [ + "chat", + "mcp" + ], + "title": "Inspection Type", + "type": "string" + }, + "integration_profile_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Integration profile id to apply (advanced).", + "title": "Integration Profile Id" + }, + "integration_profile_version": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Integration profile version to apply (advanced).", + "title": "Integration Profile Version" + }, + "integration_tenant_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Integration tenant id to apply (advanced).", + "title": "Integration Tenant Id" + }, + "integration_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Integration type to apply (advanced).", + "title": "Integration Type" + }, + "on_flagged_action": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": "block", + "description": "Action to take when Cisco AI Defense flags content. 'block' raises an HTTPException; 'monitor' logs the detection and lets the request continue.", + "title": "On Flagged Action" + }, + "timeout": { + "anyOf": [ + { + "maximum": 60.0, + "minimum": 1.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": 10.0, + "description": "Timeout (seconds) for Cisco AI Defense API calls (1-60).", + "title": "Timeout" + } + }, + "title": "CiscoAIDefenseGuardrailConfigModelOptionalParams", + "type": "object" + }, + "CiscoAIDefenseRule": { + "description": "A single rule to enable for Cisco AI Defense inspection.", + "properties": { + "entity_types": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "description": "Optional list of entity types for the rule (e.g. 'Email Address', 'Phone Number'). Applies to rules such as PII, PCI, and PHI.", + "title": "Entity Types" + }, + "rule_name": { + "description": "The canonical Cisco AI Defense rule name to evaluate.", + "enum": [ + "Code Detection", + "Harassment", + "Hate Speech", + "PCI", + "PHI", + "PII", + "Prompt Injection", + "Profanity", + "Sexual Content & Exploitation", + "Social Division & Polarization", + "Violence & Public Safety Threats" + ], + "title": "Rule Name", + "type": "string" + } + }, + "required": [ + "rule_name" + ], + "title": "CiscoAIDefenseRule", + "type": "object" + }, "ContentFilterAction": { "description": "Action to take when content filter detects a match", "enum": [ @@ -8933,106 +9614,6 @@ "title": "GUARDRAIL_DEFINITION_LOCATION", "type": "string" }, - "GraySwanGuardrailConfigModelOptionalParams": { - "description": "Optional parameters for the Gray Swan guardrail.", - "properties": { - "categories": { - "anyOf": [ - { - "additionalProperties": { - "type": "string" - }, - "type": "object" - }, - { - "type": "null" - } - ], - "description": "Default Gray Swan category definitions to send with each request.", - "title": "Categories" - }, - "fail_open": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": true, - "description": "If true (default), errors contacting Gray Swan are logged and the request proceeds. If false, errors propagate and block the request.", - "title": "Fail Open" - }, - "guardrail_timeout": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "default": 30.0, - "description": "Timeout in seconds for calling the Gray Swan guardrail service.", - "title": "Guardrail Timeout" - }, - "on_flagged_action": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": "passthrough", - "description": "Action when a violation is detected: 'block' rejects the call (400 error), 'monitor' logs only, 'passthrough' replaces response content with violation message (200 status).", - "title": "On Flagged Action" - }, - "policy_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Gray Swan policy identifier to apply during monitoring.", - "title": "Policy Id" - }, - "reasoning_mode": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Gray Swan reasoning mode override. Accepted values: 'off', 'hybrid', 'thinking'.", - "title": "Reasoning Mode" - }, - "violation_threshold": { - "anyOf": [ - { - "maximum": 1.0, - "minimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 0.5, - "description": "Threshold between 0 and 1 at which Gray Swan violations trigger the configured action.", - "title": "Violation Threshold" - } - }, - "title": "GraySwanGuardrailConfigModelOptionalParams", - "type": "object" - }, "Guardrail": { "properties": { "created_at": { @@ -9156,7 +9737,7 @@ "litellm_params": { "anyOf": [ { - "$ref": "#/components/schemas/BaseLitellmParams-Output" + "$ref": "#/components/schemas/BaseLitellmParams" }, { "type": "null" @@ -9506,7 +10087,7 @@ "type": "null" } ], - "description": "Base URL for the Lakera AI API", + "description": "Regional base URL for the Cisco AI Defense Inspection API. Defaults to https://us.api.inspect.aidefense.security.cisco.com. Supported regions: us (us-west-2), ap (ap-ne-1), eu (eu-central-1). The environment variable `CISCO_AI_DEFENSE_API_BASE` is consulted as a fallback. The endpoint path is derived from inspection_type (/api/v1/inspect/chat for 'chat', /api/v1/inspect/mcp for 'mcp').", "title": "Api Base" }, "api_endpoint": { @@ -9542,7 +10123,7 @@ "type": "null" } ], - "description": "API key for the Lakera AI service", + "description": "API key for the Cisco AI Defense inspection endpoint. If not provided, the `CISCO_AI_DEFENSE_API_KEY` environment variable is used. Sent in the `X-Cisco-AI-Defense-API-Key` header. Both the chat and MCP endpoints use this key.", "title": "Api Key" }, "api_version": { @@ -9597,6 +10178,18 @@ "description": "Custom assertions to validate against the output. Each assertion is a string describing a condition.", "title": "Assertions" }, + "asset_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Repello asset ID whose dashboard policies are enforced. Required; the guardrail raises at init if it is missing.", + "title": "Asset Id" + }, "async_mode": { "anyOf": [ { @@ -9887,6 +10480,24 @@ ], "description": "Threshold configuration for Lakera guardrail categories" }, + "checks": { + "anyOf": [ + { + "$ref": "#/components/schemas/BedrockChecksConfigModel" + }, + { + "type": "null" + } + ], + "description": "Inline safeguards for the resource-less InvokeGuardrailChecks API (contentFilter / promptAttack / sensitiveInformation). When set, the guardrail calls InvokeGuardrailChecks instead of ApplyGuardrail and no guardrailIdentifier is required. Mutually exclusive with guardrailIdentifier." + }, + "chunk_budget_chars": { + "default": 25000, + "description": "ApplyGuardrail: batch size, in characters, used to re-send content after AWS has rejected a request as too large. Requests AWS accepts are always sent in a single call, so this has no effect until a rejection happens. Defaults to 25,000; a batch AWS still rejects is bisected automatically, so this value only trades round trips against batch size and cannot fail a request on its own.", + "exclusiveMinimum": 0.0, + "title": "Chunk Budget Chars", + "type": "integer" + }, "confidence_threshold": { "default": 0.5, "default_value": 0.5, @@ -9913,6 +10524,21 @@ "description": "Additional configuration for the guardrail", "title": "Config" }, + "content_filter_threshold": { + "anyOf": [ + { + "maximum": 1.0, + "minimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": 0.5, + "description": "InvokeGuardrailChecks: block when any contentFilter severityScore >= this value (scores are in [0,1]). Set to null to make the content filter detect-only (logged, never blocks).", + "title": "Content Filter Threshold" + }, "content_moderation_check": { "anyOf": [ { @@ -9949,6 +10575,18 @@ "description": "Python-like code containing the apply_guardrail function for custom guardrail logic", "title": "Custom Code" }, + "deepkeep_firewall_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The DeepKeep Firewall ID to use for guardrail evaluation. If not provided, the `DEEPKEEP_FIREWALL_ID` environment variable is checked.", + "title": "Deepkeep Firewall Id" + }, "default_action": { "default": "deny", "description": "Fallback decision when no rule matches", @@ -10115,7 +10753,7 @@ } ], "default": true, - "description": "Whether to fail the request if Model Armor encounters an error", + "description": "Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.", "title": "Fail On Error" }, "grounding_check": { @@ -10388,7 +11026,7 @@ "type": "null" } ], - "description": "Optional field if guardrail requires a 'model' parameter", + "description": "Model name forwarded to the headroom /v1/compress endpoint.", "title": "Model" }, "monitor_mode": { @@ -10443,6 +11081,22 @@ "description": "Action to take when content is flagged: 'block' (raise exception) or 'monitor' (log only)", "title": "On Flagged Action" }, + "on_sensitive_data": { + "anyOf": [ + { + "enum": [ + "block", + "route" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Action to take when sensitive data is detected. 'block' raises an exception (default behavior). 'route' reroutes the request to the model specified in sensitive_data_route_to_model.", + "title": "On Sensitive Data" + }, "on_violation": { "anyOf": [ { @@ -10459,10 +11113,23 @@ "description": "For /v1/realtime sessions: 'warn' speaks the violation message and continues; 'end_session' speaks the message and closes the connection.", "title": "On Violation" }, + "only_scan_new_messages": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "description": "When True, the guardrail only scans messages that have not already been scanned earlier in the same session (identified by litellm_session_id / session_id). Message content is hashed per session and cached; only the diff (new or edited messages) is sent to the guardrail provider on follow-up calls. Falls back to a full scan when the request has no session id or the cache is unavailable. Intended for blocking/detection guardrails; not applied when mask_request_content is set.", + "title": "Only Scan New Messages" + }, "optional_params": { "anyOf": [ { - "$ref": "#/components/schemas/GraySwanGuardrailConfigModelOptionalParams" + "$ref": "#/components/schemas/CiscoAIDefenseGuardrailConfigModelOptionalParams" }, { "type": "null" @@ -10571,6 +11238,21 @@ "description": "Enable PII (Personally Identifiable Information) detection.", "title": "Pii Check" }, + "pii_confidence_threshold": { + "anyOf": [ + { + "maximum": 1.0, + "minimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": 0.5, + "description": "InvokeGuardrailChecks: block when any sensitiveInformation confidenceScore >= this value (scores are in [0,1]). Set to null to make PII detection detect-only.", + "title": "Pii Confidence Threshold" + }, "pii_entities_config": { "anyOf": [ { @@ -10634,6 +11316,30 @@ "title": "Policy Names", "ui_type": "multiselect" }, + "post_checkpoint_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Post-checkpoint ID for the Ovalix Tracker service.", + "title": "Post Checkpoint Id" + }, + "pre_checkpoint_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Pre-checkpoint ID for the Ovalix Tracker service.", + "title": "Pre Checkpoint Id" + }, "presidio_ad_hoc_recognizers": { "anyOf": [ { @@ -10766,6 +11472,21 @@ "description": "Project ID for the Lakera AI project", "title": "Project Id" }, + "prompt_attack_threshold": { + "anyOf": [ + { + "maximum": 1.0, + "minimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": 0.5, + "description": "InvokeGuardrailChecks: block when any promptAttack severityScore >= this value (scores are in [0,1]). Set to null to make prompt-attack detection detect-only.", + "title": "Prompt Attack Threshold" + }, "prompt_injections": { "anyOf": [ { @@ -10805,6 +11526,43 @@ "description": "Ordered allow/deny rules. Patterns use regex for tool names/types and optional regex constraints on tool arguments.", "title": "Rules" }, + "run_in_parallel": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "When True, this pre_call or post_call guardrail runs concurrently with other opted-in guardrails of the same hook, after the sequential guardrails have run. Use only for block-only guardrails that inspect and reject; do not enable it for guardrails that modify the request or response (e.g. PII masking or sensitive-data routing), since parallel runs share one snapshot and their mutations would race.", + "title": "Run In Parallel" + }, + "sanitize_error_detail": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "For guardrail='model_armor': omit the raw Model Armor response from caller-facing errors and logs by default. Set False to restore verbose output.", + "title": "Sanitize Error Detail" + }, + "scan_only_tool_results": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "When True, unified guardrails only evaluate tool results, the untrusted data an agent feeds back into the model, and skip system, user, and assistant content. Intended for agent harnesses whose own prompt scaffolding is trusted but often trips prompt-attack detectors.", + "title": "Scan Only Tool Results" + }, "send_user_api_key_alias": { "anyOf": [ { @@ -10844,6 +11602,18 @@ "description": "Whether to send user_API_key_user_id in headers", "title": "Send User Api Key User Id" }, + "sensitive_data_route_to_model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Model to route requests to when sensitive data is detected and on_sensitive_data='route'. This is typically an on-premise model for data privacy. The routing decision persists for the entire session.", + "title": "Sensitive Data Route To Model" + }, "severity_threshold": { "anyOf": [ { @@ -10856,6 +11626,54 @@ "description": "Minimum severity to block (high, medium, low)", "title": "Severity Threshold" }, + "singulr_api_base": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The Singulr API base URL. Get base URL from Singulr Platform.", + "title": "Singulr Api Base" + }, + "singulr_api_key": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The Singulr API key. Generate API key from Singulr Platform.", + "title": "Singulr Api Key" + }, + "singulr_application_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The Singulr application ID. Get application ID from Singulr Platform.", + "title": "Singulr Application Id" + }, + "singulr_guardrail_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The Singulr Guardrail ID. Get guardrail ID from Singulr Platform.", + "title": "Singulr Guardrail Id" + }, "skip_system_message_in_guardrail": { "anyOf": [ { @@ -10865,9 +11683,47 @@ "type": "null" } ], - "description": "When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting.", + "description": "When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting. For Anthropic /v1/messages, the flag applies only to the trusted top-level system prompt. In-sequence system entries are untrusted client input and remain in texts and structured_messages.", "title": "Skip System Message In Guardrail" }, + "skip_tool_message_in_guardrail": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "When True, unified guardrails skip tool-role messages when building evaluation inputs (texts and structured_messages). When False, tool messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_tool_message_in_guardrail setting.", + "title": "Skip Tool Message In Guardrail" + }, + "skip_unscannable_attachments": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "description": "Implemented by guardrail='model_armor'. When True, attachment references that carry no inline bytes (file_id, gs://, or http(s) URLs) pass through unscanned instead of blocking, while fail_on_error still governs real Model Armor API errors. Default False blocks them.", + "title": "Skip Unscannable Attachments" + }, + "sticky_session_routing": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "When True (default), after sensitive data is detected and routed, all subsequent requests in the same session will continue routing to the same model.", + "title": "Sticky Session Routing" + }, "template_id": { "anyOf": [ { @@ -10880,6 +11736,18 @@ "description": "The ID of your Model Armor template", "title": "Template Id" }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Per-request timeout for the guardrail provider API call (seconds). Accepts int, float, or numeric string; coerced to float on load. Each guardrail handler chooses its own default when unset.", + "title": "Timeout" + }, "tool_selection_quality_check": { "anyOf": [ { @@ -10892,9 +11760,33 @@ "description": "Enable tool selection quality check to evaluate quality of tool/function calls.", "title": "Tool Selection Quality Check" }, + "tracker_api_base": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Base URL for the Ovalix Tracker service.", + "title": "Tracker Api Base" + }, + "tracker_api_key": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "API key for the Ovalix Tracker service.", + "title": "Tracker Api Key" + }, "unreachable_fallback": { "default": "fail_closed", - "description": "What to do when Akto is unreachable. 'fail_open' = allow, 'fail_closed' = block.", + "description": "Behavior when the headroom compression service is unreachable or errors. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and forwards the request uncompressed instead of blocking it.", "enum": [ "fail_closed", "fail_open" @@ -11046,7 +11938,7 @@ "litellm_params": { "anyOf": [ { - "$ref": "#/components/schemas/BaseLitellmParams-Input" + "$ref": "#/components/schemas/BaseLitellmParams" }, { "type": "null" @@ -11086,6 +11978,9 @@ "US_SSN", "UK_NHS", "UK_NINO", + "UK_PASSPORT", + "UK_POSTCODE", + "UK_VEHICLE_REGISTRATION", "ES_NIF", "ES_NIE", "IT_FISCAL_CODE", @@ -11789,6 +12684,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -13309,6 +14211,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -13609,6 +14518,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -13860,6 +14776,17 @@ }, "MCPCredentials": { "properties": { + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_value": { "anyOf": [ { @@ -13948,6 +14875,17 @@ ], "title": "Aws Session Token" }, + "client_assertion_signing_alg": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Assertion Signing Alg" + }, "client_id": { "anyOf": [ { @@ -13959,6 +14897,28 @@ ], "title": "Client Id" }, + "client_private_key": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key" + }, + "client_private_key_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key Id" + }, "client_secret": { "anyOf": [ { @@ -13970,6 +14930,42 @@ ], "title": "Client Secret" }, + "id_jag_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource" + }, + "id_jag_resource_token_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource Token Endpoint" + }, + "redirect_uris": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Redirect Uris" + }, "scopes": { "anyOf": [ { @@ -13983,11 +14979,124 @@ } ], "title": "Scopes" + }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, + "token_endpoint_auth_method": { + "anyOf": [ + { + "enum": [ + "client_secret_basic", + "client_secret_post" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Endpoint Auth Method" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, + "upstream_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Resource" + }, + "upstream_token_header": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Token Header" } }, "title": "MCPCredentials", "type": "object" }, + "MCPEnvVar": { + "description": "One environment variable for an MCP server.\n\nVariables can be interpolated into ``static_headers`` using ``${NAME}``\nsyntax. ``scope=global`` values are stored on the server. ``scope=user``\nvalues are stored per-user in ``LiteLLM_MCPUserEnvVars`` and supplied by\neach user.", + "properties": { + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "name": { + "title": "Name", + "type": "string" + }, + "scope": { + "$ref": "#/components/schemas/MCPEnvVarScope", + "default": "global" + }, + "value": { + "default": "", + "title": "Value", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "MCPEnvVar", + "type": "object" + }, + "MCPEnvVarScope": { + "description": "Scope for an MCP server environment variable.\n\n- ``global``: value is provided by the admin and used for all users.\n- ``user``: each user must provide their own value via the per-user\n env-var endpoint. The admin-supplied ``value`` is treated as a\n placeholder/hint and is not used at request time.", + "enum": [ + "global", + "user" + ], + "title": "MCPEnvVarScope", + "type": "string" + }, "NewMCPServerRequest": { "properties": { "alias": { @@ -14039,6 +15148,17 @@ "title": "Args", "type": "array" }, + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_type": { "anyOf": [ { @@ -14050,7 +15170,11 @@ "authorization", "oauth2", "aws_sigv4", - "token" + "token", + "oauth2_token_exchange", + "oauth2_id_jag", + "true_passthrough", + "oauth_delegate" ], "type": "string" }, @@ -14115,6 +15239,22 @@ } ] }, + "dcr_bridge": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Dcr Bridge" + }, + "delegate_auth_to_upstream": { + "default": false, + "title": "Delegate Auth To Upstream", + "type": "boolean" + }, "description": { "anyOf": [ { @@ -14133,6 +15273,20 @@ "title": "Env", "type": "object" }, + "env_vars": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/MCPEnvVar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Env Vars" + }, "extra_headers": { "anyOf": [ { @@ -14163,6 +15317,28 @@ "title": "Is Byok", "type": "boolean" }, + "issuer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Issuer" + }, + "max_concurrent_requests": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Concurrent Requests" + }, "mcp_access_groups": { "items": { "type": "string" @@ -14197,6 +15373,11 @@ ], "title": "Oauth2 Flow" }, + "oauth_passthrough": { + "default": false, + "title": "Oauth Passthrough", + "type": "boolean" + }, "registration_url": { "anyOf": [ { @@ -14266,6 +15447,17 @@ ], "title": "Static Headers" }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, "submitted_at": { "anyOf": [ { @@ -14291,6 +15483,39 @@ "description": "Server-managed: set by the endpoint; caller values are overridden.", "title": "Submitted By" }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Timeout" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, "token_url": { "anyOf": [ { @@ -14357,6 +15582,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -14391,6 +15623,134 @@ } }, "paths": { + "/mcp": { + "delete": { + "description": "Serve the aggregate MCP endpoint on the bare ``/mcp`` spelling: the\n``/mcp`` mount cannot match its bare prefix, and the resulting 307 breaks\nMCP clients behind TLS-terminating proxies.", + "operationId": "aggregate_mcp_route_mcp_delete", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Aggregate Mcp Route", + "tags": [ + "mcp_app" + ] + }, + "get": { + "description": "Serve the aggregate MCP endpoint on the bare ``/mcp`` spelling: the\n``/mcp`` mount cannot match its bare prefix, and the resulting 307 breaks\nMCP clients behind TLS-terminating proxies.", + "operationId": "aggregate_mcp_route_mcp_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Aggregate Mcp Route", + "tags": [ + "mcp_app" + ] + }, + "head": { + "description": "Serve the aggregate MCP endpoint on the bare ``/mcp`` spelling: the\n``/mcp`` mount cannot match its bare prefix, and the resulting 307 breaks\nMCP clients behind TLS-terminating proxies.", + "operationId": "aggregate_mcp_route_mcp_head", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Aggregate Mcp Route", + "tags": [ + "mcp_app" + ] + }, + "options": { + "description": "Serve the aggregate MCP endpoint on the bare ``/mcp`` spelling: the\n``/mcp`` mount cannot match its bare prefix, and the resulting 307 breaks\nMCP clients behind TLS-terminating proxies.", + "operationId": "aggregate_mcp_route_mcp_options", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Aggregate Mcp Route", + "tags": [ + "mcp_app" + ] + }, + "patch": { + "description": "Serve the aggregate MCP endpoint on the bare ``/mcp`` spelling: the\n``/mcp`` mount cannot match its bare prefix, and the resulting 307 breaks\nMCP clients behind TLS-terminating proxies.", + "operationId": "aggregate_mcp_route_mcp_patch", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Aggregate Mcp Route", + "tags": [ + "mcp_app" + ] + }, + "post": { + "description": "Serve the aggregate MCP endpoint on the bare ``/mcp`` spelling: the\n``/mcp`` mount cannot match its bare prefix, and the resulting 307 breaks\nMCP clients behind TLS-terminating proxies.", + "operationId": "aggregate_mcp_route_mcp_post", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Aggregate Mcp Route", + "tags": [ + "mcp_app" + ] + }, + "put": { + "description": "Serve the aggregate MCP endpoint on the bare ``/mcp`` spelling: the\n``/mcp`` mount cannot match its bare prefix, and the resulting 307 breaks\nMCP clients behind TLS-terminating proxies.", + "operationId": "aggregate_mcp_route_mcp_put", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Aggregate Mcp Route", + "tags": [ + "mcp_app" + ] + } + }, "/mcp-rest/test/connection": { "post": { "description": "Test if we can connect to the provided MCP server before adding it", @@ -14508,7 +15868,7 @@ }, "/mcp-rest/tools/list": { "get": { - "description": "List all available tools with information about the server they belong to.\n\nExample response:\n{\n \"tools\": [\n {\n \"name\": \"create_zap\",\n \"description\": \"Create a new zap\",\n \"inputSchema\": \"tool_input_schema\",\n \"mcp_info\": {\n \"server_name\": \"zapier\",\n \"logo_url\": \"https://www.zapier.com/logo.png\",\n }\n }\n ],\n \"error\": null,\n \"message\": \"Successfully retrieved tools\"\n}", + "description": "List all available tools with information about the server they belong to.\n\nExample response:\n{\n \"tools\": [\n {\n \"name\": \"create_zap\",\n \"description\": \"Create a new zap\",\n \"inputSchema\": \"tool_input_schema\",\n \"mcp_info\": {\n \"server_name\": \"zapier\",\n \"logo_url\": \"https://www.zapier.com/logo.png\",\n \"server_id\": \"a1b2c3d4-...\",\n \"alias\": \"zapier_prod\",\n }\n }\n ],\n \"error\": null,\n \"message\": \"Successfully retrieved tools\"\n}", "operationId": "list_tool_rest_api_mcp_rest_tools_list_get_2", "parameters": [ { @@ -14528,6 +15888,54 @@ "description": "The server id to list tools for", "title": "Server Id" } + }, + { + "description": "Filter tools to a single MCP server by name or alias", + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Filter tools to a single MCP server by name or alias", + "title": "Mcp Server Name" + } + }, + { + "description": "Filter tools to a single toolset by name", + "in": "query", + "name": "toolset_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Filter tools to a single toolset by name", + "title": "Toolset Name" + } + }, + { + "description": "Admin only. Return the full server tool catalog without the allowed_tools filter or per-key tool permissions, so the MCP settings UI can configure the allowlist. Ignored for non-admins.", + "in": "query", + "name": "include_disabled_tools", + "required": false, + "schema": { + "default": false, + "description": "Admin only. Return the full server tool catalog without the allowed_tools filter or per-key tool permissions, so the MCP settings UI can configure the allowlist. Ignored for non-admins.", + "title": "Include Disabled Tools", + "type": "boolean" + } } ], "responses": { @@ -14569,13 +15977,635 @@ }, "mcp_byok_oauth": { "components": { - "schemas": {} + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "title": "Detail", + "type": "array" + } + }, + "title": "HTTPValidationError", + "type": "object" + }, + "ValidationError": { + "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, + "loc": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "title": "Location", + "type": "array" + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + }, + "required": [ + "loc", + "msg", + "type" + ], + "title": "ValidationError", + "type": "object" + } + } }, - "paths": {} + "paths": { + "/.well-known/oauth-authorization-server": { + "get": { + "description": "OAuth authorization server discovery endpoint.\n\nSupports both legacy pattern (/{server_name}) and root endpoint.", + "operationId": "oauth_authorization_server_mcp__well_known_oauth_authorization_server_get", + "parameters": [ + { + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Mcp", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-authorization-server/mcp": { + "get": { + "description": "OAuth authorization server discovery for the aggregate /mcp endpoint, the RFC 8414\npath-inserted form for a client that treats {base}/mcp as its authorization base URL.\n\nThe single-segment /mcp is reserved for the aggregate so the discovery chain stays\nconsistent: the aggregate protected-resource document advertises {base}/mcp as its\nauthorization server, so the document served here must have issuer {base}/mcp. A server\nliterally named ``mcp`` therefore does not take this route; it keeps its standard\ntwo-segment discovery at /.well-known/oauth-authorization-server/mcp/mcp. Letting the\nper-server row win here instead would serve an issuer of {base} against a resource that\nadvertised {base}/mcp, which fails the RFC 8414 issuer check and breaks the front door.", + "operationId": "oauth_authorization_server_aggregate__well_known_oauth_authorization_server_mcp_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Oauth Authorization Server Aggregate", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-authorization-server/mcp/{mcp_server_name}": { + "get": { + "description": "OAuth authorization server discovery endpoint using standard MCP URL pattern.\n\nStandard pattern: /mcp/{server_name}\nDiscovery path: /.well-known/oauth-authorization-server/mcp/{server_name}", + "operationId": "oauth_authorization_server_mcp_standard__well_known_oauth_authorization_server_mcp__mcp_server_name__get", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "title": "Mcp Server Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Mcp Standard", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-authorization-server/{mcp_server_name}": { + "get": { + "description": "OAuth authorization server discovery endpoint.\n\nSupports both legacy pattern (/{server_name}) and root endpoint.", + "operationId": "oauth_authorization_server_mcp__well_known_oauth_authorization_server__mcp_server_name__get", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Mcp", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-authorization-server/{mcp_server_name}/mcp": { + "get": { + "description": "OAuth authorization server discovery for legacy /{server_name}/mcp pattern.", + "operationId": "oauth_authorization_server_legacy__well_known_oauth_authorization_server__mcp_server_name__mcp_get", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "title": "Mcp Server Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Legacy", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-protected-resource": { + "get": { + "description": "OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern.\n\nLegacy pattern: /{server_name}/mcp\nDiscovery path: /.well-known/oauth-protected-resource/{server_name}/mcp\n\nThis endpoint is kept for backward compatibility. New integrations should\nuse the standard MCP pattern (/mcp/{server_name}) instead.", + "operationId": "oauth_protected_resource_mcp__well_known_oauth_protected_resource_get", + "parameters": [ + { + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Protected Resource Mcp", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-protected-resource/mcp": { + "get": { + "description": "OAuth protected resource discovery for the aggregate /mcp endpoint.\n\nThe single-segment ``/mcp`` path does not collide with any per-server PRM pattern\n(those are two-segment: ``/mcp/{server}`` or ``/{server}/mcp``), so this unambiguously\ndescribes the aggregate resource.", + "operationId": "oauth_protected_resource_aggregate__well_known_oauth_protected_resource_mcp_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Oauth Protected Resource Aggregate", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-protected-resource/mcp/{mcp_server_name}": { + "get": { + "description": "OAuth protected resource discovery endpoint using standard MCP URL pattern.\n\nStandard pattern: /mcp/{server_name}\nDiscovery path: /.well-known/oauth-protected-resource/mcp/{server_name}\n\nThis endpoint is compliant with MCP specification and works with standard\nMCP clients like mcp-inspector and VSCode Copilot.", + "operationId": "oauth_protected_resource_mcp_standard__well_known_oauth_protected_resource_mcp__mcp_server_name__get", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "title": "Mcp Server Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Protected Resource Mcp Standard", + "tags": [ + "mcp_byok_oauth" + ] + } + }, + "/.well-known/oauth-protected-resource/{mcp_server_name}/mcp": { + "get": { + "description": "OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern.\n\nLegacy pattern: /{server_name}/mcp\nDiscovery path: /.well-known/oauth-protected-resource/{server_name}/mcp\n\nThis endpoint is kept for backward compatibility. New integrations should\nuse the standard MCP pattern (/mcp/{server_name}) instead.", + "operationId": "oauth_protected_resource_mcp__well_known_oauth_protected_resource__mcp_server_name__mcp_get", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Protected Resource Mcp", + "tags": [ + "mcp_byok_oauth" + ] + } + } + } }, "mcp_discoverable": { "components": { "schemas": { + "Body_authorize_complete_authorize_complete_post": { + "properties": { + "decision": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Decision" + }, + "delivery": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Delivery" + }, + "flow": { + "title": "Flow", + "type": "string" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Team Id" + } + }, + "required": [ + "flow" + ], + "title": "Body_authorize_complete_authorize_complete_post", + "type": "object" + }, + "Body_revoke_endpoint_revoke_post": { + "properties": { + "client_id": { + "title": "Client Id", + "type": "string" + }, + "token": { + "title": "Token", + "type": "string" + } + }, + "required": [ + "token", + "client_id" + ], + "title": "Body_revoke_endpoint_revoke_post", + "type": "object" + }, + "Body_token_endpoint__mcp_server_name__token_post": { + "properties": { + "client_id": { + "title": "Client Id", + "type": "string" + }, + "client_secret": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Secret" + }, + "code": { + "title": "Code", + "type": "string" + }, + "code_verifier": { + "title": "Code Verifier", + "type": "string" + }, + "grant_type": { + "title": "Grant Type", + "type": "string" + }, + "redirect_uri": { + "title": "Redirect Uri", + "type": "string" + }, + "refresh_token": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Refresh Token" + }, + "resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Resource" + }, + "scope": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Scope" + } + }, + "required": [ + "grant_type", + "client_id" + ], + "title": "Body_token_endpoint__mcp_server_name__token_post", + "type": "object" + }, + "Body_token_endpoint_token_post": { + "properties": { + "client_id": { + "title": "Client Id", + "type": "string" + }, + "client_secret": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Secret" + }, + "code": { + "title": "Code", + "type": "string" + }, + "code_verifier": { + "title": "Code Verifier", + "type": "string" + }, + "grant_type": { + "title": "Grant Type", + "type": "string" + }, + "redirect_uri": { + "title": "Redirect Uri", + "type": "string" + }, + "refresh_token": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Refresh Token" + }, + "resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Resource" + }, + "scope": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Scope" + } + }, + "required": [ + "grant_type", + "client_id" + ], + "title": "Body_token_endpoint_token_post", + "type": "object" + }, "CallbacksByType": { "properties": { "failure": { @@ -14607,67 +16637,7 @@ ], "title": "CallbacksByType", "type": "object" - } - } - }, - "paths": { - "/callbacks/configs": { - "get": { - "description": "Get Available Callback Configurations\n\nReturns the configuration details for all available logging callbacks,\nincluding supported parameters, field types, and descriptions.", - "operationId": "get_callback_configs_callbacks_configs_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - } - }, - "security": [ - { - "APIKeyHeader": [] - } - ], - "summary": "Get Callback Configs", - "tags": [ - "mcp_discoverable" - ] - } - }, - "/callbacks/list": { - "get": { - "description": "View List of Active Logging Callbacks", - "operationId": "list_callbacks_callbacks_list_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CallbacksByType" - } - } - }, - "description": "Successful Response" - } - }, - "security": [ - { - "APIKeyHeader": [] - } - ], - "summary": "List Callbacks", - "tags": [ - "mcp_discoverable" - ] - } - } - } - }, - "mcp_management": { - "components": { - "schemas": { + }, "HTTPValidationError": { "properties": { "detail": { @@ -14727,6 +16697,17 @@ "title": "Args", "type": "array" }, + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_type": { "anyOf": [ { @@ -14738,7 +16719,11 @@ "authorization", "oauth2", "aws_sigv4", - "token" + "token", + "oauth2_token_exchange", + "oauth2_id_jag", + "true_passthrough", + "oauth_delegate" ], "type": "string" }, @@ -14793,6 +16778,17 @@ ], "title": "Command" }, + "connected_app_reachable": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Connected App Reachable" + }, "created_at": { "anyOf": [ { @@ -14826,6 +16822,22 @@ } ] }, + "dcr_bridge": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Dcr Bridge" + }, + "delegate_auth_to_upstream": { + "default": false, + "title": "Delegate Auth To Upstream", + "type": "boolean" + }, "description": { "anyOf": [ { @@ -14844,6 +16856,20 @@ "title": "Env", "type": "object" }, + "env_vars": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/MCPEnvVar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Env Vars" + }, "extra_headers": { "items": { "type": "string" @@ -14889,6 +16915,17 @@ "title": "Is Byok", "type": "boolean" }, + "issuer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Issuer" + }, "last_health_check": { "anyOf": [ { @@ -14901,6 +16938,17 @@ ], "title": "Last Health Check" }, + "max_concurrent_requests": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Concurrent Requests" + }, "mcp_access_groups": { "items": { "type": "string" @@ -14920,6 +16968,26 @@ ], "title": "Mcp Info" }, + "oauth2_flow": { + "anyOf": [ + { + "enum": [ + "client_credentials", + "authorization_code" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Oauth2 Flow" + }, + "oauth_passthrough": { + "default": false, + "title": "Oauth Passthrough", + "type": "boolean" + }, "registration_url": { "anyOf": [ { @@ -15023,6 +17091,17 @@ "description": "Health status: 'healthy', 'unhealthy', 'unknown'", "title": "Status" }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, "submitted_at": { "anyOf": [ { @@ -15063,6 +17142,39 @@ "title": "Teams", "type": "array" }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Timeout" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, "token_url": { "anyOf": [ { @@ -15155,6 +17267,17 @@ }, "MCPCredentials": { "properties": { + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_value": { "anyOf": [ { @@ -15243,6 +17366,17 @@ ], "title": "Aws Session Token" }, + "client_assertion_signing_alg": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Assertion Signing Alg" + }, "client_id": { "anyOf": [ { @@ -15254,6 +17388,28 @@ ], "title": "Client Id" }, + "client_private_key": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key" + }, + "client_private_key_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key Id" + }, "client_secret": { "anyOf": [ { @@ -15265,6 +17421,42 @@ ], "title": "Client Secret" }, + "id_jag_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource" + }, + "id_jag_resource_token_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource Token Endpoint" + }, + "redirect_uris": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Redirect Uris" + }, "scopes": { "anyOf": [ { @@ -15278,11 +17470,2969 @@ } ], "title": "Scopes" + }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, + "token_endpoint_auth_method": { + "anyOf": [ + { + "enum": [ + "client_secret_basic", + "client_secret_post" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Endpoint Auth Method" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, + "upstream_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Resource" + }, + "upstream_token_header": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Token Header" } }, "title": "MCPCredentials", "type": "object" }, + "MCPEnvVar": { + "description": "One environment variable for an MCP server.\n\nVariables can be interpolated into ``static_headers`` using ``${NAME}``\nsyntax. ``scope=global`` values are stored on the server. ``scope=user``\nvalues are stored per-user in ``LiteLLM_MCPUserEnvVars`` and supplied by\neach user.", + "properties": { + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "name": { + "title": "Name", + "type": "string" + }, + "scope": { + "$ref": "#/components/schemas/MCPEnvVarScope", + "default": "global" + }, + "value": { + "default": "", + "title": "Value", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "MCPEnvVar", + "type": "object" + }, + "MCPEnvVarScope": { + "description": "Scope for an MCP server environment variable.\n\n- ``global``: value is provided by the admin and used for all users.\n- ``user``: each user must provide their own value via the per-user\n env-var endpoint. The admin-supplied ``value`` is treated as a\n placeholder/hint and is not used at request time.", + "enum": [ + "global", + "user" + ], + "title": "MCPEnvVarScope", + "type": "string" + }, + "NewMCPServerRequest": { + "properties": { + "alias": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Alias" + }, + "allow_all_keys": { + "default": false, + "title": "Allow All Keys", + "type": "boolean" + }, + "allowed_tools": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Allowed Tools" + }, + "approval_status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Server-managed: set by the endpoint; caller values are overridden.", + "title": "Approval Status" + }, + "args": { + "items": { + "type": "string" + }, + "title": "Args", + "type": "array" + }, + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, + "auth_type": { + "anyOf": [ + { + "enum": [ + "none", + "api_key", + "bearer_token", + "basic", + "authorization", + "oauth2", + "aws_sigv4", + "token", + "oauth2_token_exchange", + "oauth2_id_jag", + "true_passthrough", + "oauth_delegate" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Auth Type" + }, + "authorization_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Authorization Url" + }, + "available_on_public_internet": { + "default": true, + "title": "Available On Public Internet", + "type": "boolean" + }, + "byok_api_key_help_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Byok Api Key Help Url" + }, + "byok_description": { + "items": { + "type": "string" + }, + "title": "Byok Description", + "type": "array" + }, + "command": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Command" + }, + "credentials": { + "anyOf": [ + { + "$ref": "#/components/schemas/MCPCredentials" + }, + { + "type": "null" + } + ] + }, + "dcr_bridge": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Dcr Bridge" + }, + "delegate_auth_to_upstream": { + "default": false, + "title": "Delegate Auth To Upstream", + "type": "boolean" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "env": { + "additionalProperties": { + "type": "string" + }, + "title": "Env", + "type": "object" + }, + "env_vars": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/MCPEnvVar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Env Vars" + }, + "extra_headers": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Extra Headers" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Instructions" + }, + "is_byok": { + "default": false, + "title": "Is Byok", + "type": "boolean" + }, + "issuer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Issuer" + }, + "max_concurrent_requests": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Concurrent Requests" + }, + "mcp_access_groups": { + "items": { + "type": "string" + }, + "title": "Mcp Access Groups", + "type": "array" + }, + "mcp_info": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Mcp Info" + }, + "oauth2_flow": { + "anyOf": [ + { + "enum": [ + "client_credentials", + "authorization_code" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Oauth2 Flow" + }, + "oauth_passthrough": { + "default": false, + "title": "Oauth Passthrough", + "type": "boolean" + }, + "registration_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Registration Url" + }, + "server_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Server Id" + }, + "server_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Server Name" + }, + "source_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Source Url" + }, + "spec_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Spec Path" + }, + "static_headers": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Static Headers" + }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, + "submitted_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Server-managed: set by the endpoint; caller values are overridden.", + "title": "Submitted At" + }, + "submitted_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Server-managed: set by the endpoint; caller values are overridden.", + "title": "Submitted By" + }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Timeout" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, + "token_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Url" + }, + "tool_name_to_description": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Tool Name To Description" + }, + "tool_name_to_display_name": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Tool Name To Display Name" + }, + "transport": { + "default": "sse", + "enum": [ + "sse", + "http", + "stdio" + ], + "title": "Transport", + "type": "string" + }, + "url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Url" + } + }, + "title": "NewMCPServerRequest", + "type": "object" + }, + "RegisterGuardrailRequest": { + "description": "Request body for POST /guardrails/register. Follows Generic Guardrail API config.", + "properties": { + "guardrail_info": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Guardrail Info" + }, + "guardrail_name": { + "title": "Guardrail Name", + "type": "string" + }, + "litellm_params": { + "additionalProperties": true, + "title": "Litellm Params", + "type": "object" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Team Id" + } + }, + "required": [ + "guardrail_name", + "litellm_params" + ], + "title": "RegisterGuardrailRequest", + "type": "object" + }, + "RegisterGuardrailResponse": { + "properties": { + "guardrail_id": { + "title": "Guardrail Id", + "type": "string" + }, + "guardrail_name": { + "title": "Guardrail Name", + "type": "string" + }, + "status": { + "title": "Status", + "type": "string" + }, + "submitted_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Submitted At" + } + }, + "required": [ + "guardrail_id", + "guardrail_name", + "status" + ], + "title": "RegisterGuardrailResponse", + "type": "object" + }, + "ValidationError": { + "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, + "loc": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "title": "Location", + "type": "array" + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + }, + "required": [ + "loc", + "msg", + "type" + ], + "title": "ValidationError", + "type": "object" + } + } + }, + "paths": { + "/.well-known/jwks.json": { + "get": { + "description": "JSON Web Key Set endpoint.\n\nReturns the RSA public key used by MCPJWTSigner to sign outbound MCP tokens.\nMCP servers and gateways use this endpoint to verify liteLLM-issued JWTs.\n\nReturns an empty key set if MCPJWTSigner is not configured.", + "operationId": "jwks_json__well_known_jwks_json_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Jwks Json", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/litellm-cli-auth": { + "get": { + "description": "The versioned contract a native client (``lite login --pkce``, or a CLI in any other\nlanguage) reads to sign a user in through the browser and obtain a proxy credential.", + "operationId": "native_client_auth_discovery__well_known_litellm_cli_auth_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Native Client Auth Discovery", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-authorization-server": { + "get": { + "description": "OAuth authorization server discovery endpoint.\n\nSupports both legacy pattern (/{server_name}) and root endpoint.", + "operationId": "oauth_authorization_server_mcp__well_known_oauth_authorization_server_get_2", + "parameters": [ + { + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Mcp", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-authorization-server/mcp": { + "get": { + "description": "OAuth authorization server discovery for the aggregate /mcp endpoint, the RFC 8414\npath-inserted form for a client that treats {base}/mcp as its authorization base URL.\n\nThe single-segment /mcp is reserved for the aggregate so the discovery chain stays\nconsistent: the aggregate protected-resource document advertises {base}/mcp as its\nauthorization server, so the document served here must have issuer {base}/mcp. A server\nliterally named ``mcp`` therefore does not take this route; it keeps its standard\ntwo-segment discovery at /.well-known/oauth-authorization-server/mcp/mcp. Letting the\nper-server row win here instead would serve an issuer of {base} against a resource that\nadvertised {base}/mcp, which fails the RFC 8414 issuer check and breaks the front door.", + "operationId": "oauth_authorization_server_aggregate__well_known_oauth_authorization_server_mcp_get_2", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Oauth Authorization Server Aggregate", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-authorization-server/mcp/{mcp_server_name}": { + "get": { + "description": "OAuth authorization server discovery endpoint using standard MCP URL pattern.\n\nStandard pattern: /mcp/{server_name}\nDiscovery path: /.well-known/oauth-authorization-server/mcp/{server_name}", + "operationId": "oauth_authorization_server_mcp_standard__well_known_oauth_authorization_server_mcp__mcp_server_name__get_2", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "title": "Mcp Server Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Mcp Standard", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-authorization-server/{mcp_server_name}": { + "get": { + "description": "OAuth authorization server discovery endpoint.\n\nSupports both legacy pattern (/{server_name}) and root endpoint.", + "operationId": "oauth_authorization_server_mcp__well_known_oauth_authorization_server__mcp_server_name__get_2", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Mcp", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-authorization-server/{mcp_server_name}/mcp": { + "get": { + "description": "OAuth authorization server discovery for legacy /{server_name}/mcp pattern.", + "operationId": "oauth_authorization_server_legacy__well_known_oauth_authorization_server__mcp_server_name__mcp_get_2", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "title": "Mcp Server Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Authorization Server Legacy", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-protected-resource": { + "get": { + "description": "OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern.\n\nLegacy pattern: /{server_name}/mcp\nDiscovery path: /.well-known/oauth-protected-resource/{server_name}/mcp\n\nThis endpoint is kept for backward compatibility. New integrations should\nuse the standard MCP pattern (/mcp/{server_name}) instead.", + "operationId": "oauth_protected_resource_mcp__well_known_oauth_protected_resource_get_2", + "parameters": [ + { + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Protected Resource Mcp", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-protected-resource/mcp": { + "get": { + "description": "OAuth protected resource discovery for the aggregate /mcp endpoint.\n\nThe single-segment ``/mcp`` path does not collide with any per-server PRM pattern\n(those are two-segment: ``/mcp/{server}`` or ``/{server}/mcp``), so this unambiguously\ndescribes the aggregate resource.", + "operationId": "oauth_protected_resource_aggregate__well_known_oauth_protected_resource_mcp_get_2", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Oauth Protected Resource Aggregate", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-protected-resource/mcp/{mcp_server_name}": { + "get": { + "description": "OAuth protected resource discovery endpoint using standard MCP URL pattern.\n\nStandard pattern: /mcp/{server_name}\nDiscovery path: /.well-known/oauth-protected-resource/mcp/{server_name}\n\nThis endpoint is compliant with MCP specification and works with standard\nMCP clients like mcp-inspector and VSCode Copilot.", + "operationId": "oauth_protected_resource_mcp_standard__well_known_oauth_protected_resource_mcp__mcp_server_name__get_2", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "title": "Mcp Server Name", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Protected Resource Mcp Standard", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/oauth-protected-resource/{mcp_server_name}/mcp": { + "get": { + "description": "OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern.\n\nLegacy pattern: /{server_name}/mcp\nDiscovery path: /.well-known/oauth-protected-resource/{server_name}/mcp\n\nThis endpoint is kept for backward compatibility. New integrations should\nuse the standard MCP pattern (/mcp/{server_name}) instead.", + "operationId": "oauth_protected_resource_mcp__well_known_oauth_protected_resource__mcp_server_name__mcp_get_2", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Oauth Protected Resource Mcp", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/.well-known/openid-configuration": { + "get": { + "operationId": "openid_configuration__well_known_openid_configuration_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "summary": "Openid Configuration", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/authorize": { + "get": { + "operationId": "authorize_authorize_get", + "parameters": [ + { + "in": "query", + "name": "redirect_uri", + "required": true, + "schema": { + "title": "Redirect Uri", + "type": "string" + } + }, + { + "in": "query", + "name": "client_id", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Id" + } + }, + { + "in": "query", + "name": "state", + "required": false, + "schema": { + "default": "", + "title": "State", + "type": "string" + } + }, + { + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + }, + { + "in": "query", + "name": "code_challenge", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Code Challenge" + } + }, + { + "in": "query", + "name": "code_challenge_method", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Code Challenge Method" + } + }, + { + "in": "query", + "name": "response_type", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Response Type" + } + }, + { + "in": "query", + "name": "scope", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Scope" + } + }, + { + "in": "query", + "name": "resource", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Resource" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Authorize", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/authorize/complete": { + "post": { + "description": "Finish an aggregate connect flow: mint the gateway authorization code for the\nsigned-in user and hand it back to the DCR client, by 303 redirect (default) or, for\na loopback client on a different machine, as a copyable callback URL\n(``delivery=manual``). POST plus the per-flow HttpOnly cookie set at /authorize; an\nanonymous or bad-flow request just 400s. The native-client consent page adds\n``decision`` (approve or deny) and the ``team_id`` the credential is attributed to.", + "operationId": "authorize_complete_authorize_complete_post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/Body_authorize_complete_authorize_complete_post" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Authorize Complete", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/callback": { + "get": { + "description": "OAuth 2.0 authorization response handler for MCP loopback clients.\n\nAccepts either:\n\n- A successful authorization response (``code`` + ``state``), which is\n forwarded back to the validated client ``redirect_uri`` with the\n original (un-wrapped) ``state``.\n- An error response (``error``[+``error_description``/``error_uri``]), per\n RFC 6749 \u00a74.1.2.1. When ``state`` is present and decodes to a trusted\n ``redirect_uri``, the error params are propagated back to the client so\n its OAuth library can surface them. Otherwise we render an HTML error\n page so the user is not left on an opaque 422 / blank screen.", + "operationId": "callback_callback_get", + "parameters": [ + { + "in": "query", + "name": "code", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Code" + } + }, + { + "in": "query", + "name": "state", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "State" + } + }, + { + "in": "query", + "name": "error", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error" + } + }, + { + "in": "query", + "name": "error_description", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error Description" + } + }, + { + "in": "query", + "name": "error_uri", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error Uri" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Callback", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/callbacks/configs": { + "get": { + "description": "Get Available Callback Configurations\n\nReturns the configuration details for all available logging callbacks,\nincluding supported parameters, field types, and descriptions.", + "operationId": "get_callback_configs_callbacks_configs_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Get Callback Configs", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/callbacks/list": { + "get": { + "description": "View List of Active Logging Callbacks", + "operationId": "list_callbacks_callbacks_list_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CallbacksByType" + } + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "List Callbacks", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/guardrails/register": { + "post": { + "description": "Register a guardrail for onboarding (team submission).\n\nAccepts a guardrail config in the\n[Generic Guardrail API](https://docs.litellm.ai/docs/adding_provider/generic_guardrail_api) format.\nThe submission is stored with status `pending_review` until an admin approves it.", + "operationId": "register_guardrail_guardrails_register_post_2", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RegisterGuardrailRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RegisterGuardrailResponse" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Register Guardrail", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/register": { + "post": { + "operationId": "register_client_register_post", + "parameters": [ + { + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Register Client", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/revoke": { + "post": { + "description": "RFC 7009 revocation for the gateway's refresh tokens (``lite logout``): 200 for a known\nclient whatever the token's state, 503 when the shared single-use record cannot be written;\naccess tokens expire on their own.", + "operationId": "revoke_endpoint_revoke_post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/Body_revoke_endpoint_revoke_post" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Revoke Endpoint", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/token": { + "post": { + "description": "Accept the authorization code from client and exchange it for OAuth token.\nSupports PKCE flow by forwarding code_verifier to upstream provider.\n\n1. Call the token endpoint with PKCE parameters\n2. Store the user's token in the db - and generate a LiteLLM virtual key\n3. Return the token\n4. Return a virtual key in this response", + "operationId": "token_endpoint_token_post", + "parameters": [ + { + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/Body_token_endpoint_token_post" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Token Endpoint", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/v1/mcp/server/register": { + "post": { + "description": "Submit a new MCP server for admin review (non-admin users). Mirrors POST /guardrails/register.", + "operationId": "register_mcp_server_v1_mcp_server_register_post_2", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewMCPServerRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LiteLLM_MCPServerTable" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Register Mcp Server", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/{mcp_server_name}/authorize": { + "get": { + "operationId": "authorize__mcp_server_name__authorize_get", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + }, + { + "in": "query", + "name": "redirect_uri", + "required": true, + "schema": { + "title": "Redirect Uri", + "type": "string" + } + }, + { + "in": "query", + "name": "client_id", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Id" + } + }, + { + "in": "query", + "name": "state", + "required": false, + "schema": { + "default": "", + "title": "State", + "type": "string" + } + }, + { + "in": "query", + "name": "code_challenge", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Code Challenge" + } + }, + { + "in": "query", + "name": "code_challenge_method", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Code Challenge Method" + } + }, + { + "in": "query", + "name": "response_type", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Response Type" + } + }, + { + "in": "query", + "name": "scope", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Scope" + } + }, + { + "in": "query", + "name": "resource", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Resource" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Authorize", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/{mcp_server_name}/register": { + "post": { + "operationId": "register_client__mcp_server_name__register_post", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Register Client", + "tags": [ + "mcp_discoverable" + ] + } + }, + "/{mcp_server_name}/token": { + "post": { + "description": "Accept the authorization code from client and exchange it for OAuth token.\nSupports PKCE flow by forwarding code_verifier to upstream provider.\n\n1. Call the token endpoint with PKCE parameters\n2. Store the user's token in the db - and generate a LiteLLM virtual key\n3. Return the token\n4. Return a virtual key in this response", + "operationId": "token_endpoint__mcp_server_name__token_post", + "parameters": [ + { + "in": "path", + "name": "mcp_server_name", + "required": true, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Server Name" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/Body_token_endpoint__mcp_server_name__token_post" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Token Endpoint", + "tags": [ + "mcp_discoverable" + ] + } + } + } + }, + "mcp_management": { + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "title": "Detail", + "type": "array" + } + }, + "title": "HTTPValidationError", + "type": "object" + }, + "LiteLLM_MCPServerTable": { + "description": "Represents a LiteLLM_MCPServerTable record", + "properties": { + "alias": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Alias" + }, + "allow_all_keys": { + "default": false, + "title": "Allow All Keys", + "type": "boolean" + }, + "allowed_tools": { + "items": { + "type": "string" + }, + "title": "Allowed Tools", + "type": "array" + }, + "approval_status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": "active", + "description": "Approval status: 'pending_review', 'active', 'rejected'", + "title": "Approval Status" + }, + "args": { + "items": { + "type": "string" + }, + "title": "Args", + "type": "array" + }, + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, + "auth_type": { + "anyOf": [ + { + "enum": [ + "none", + "api_key", + "bearer_token", + "basic", + "authorization", + "oauth2", + "aws_sigv4", + "token", + "oauth2_token_exchange", + "oauth2_id_jag", + "true_passthrough", + "oauth_delegate" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Auth Type" + }, + "authorization_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Authorization Url" + }, + "available_on_public_internet": { + "default": true, + "title": "Available On Public Internet", + "type": "boolean" + }, + "byok_api_key_help_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Byok Api Key Help Url" + }, + "byok_description": { + "items": { + "type": "string" + }, + "title": "Byok Description", + "type": "array" + }, + "command": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Command" + }, + "connected_app_reachable": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Connected App Reachable" + }, + "created_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created At" + }, + "created_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created By" + }, + "credentials": { + "anyOf": [ + { + "$ref": "#/components/schemas/MCPCredentials" + }, + { + "type": "null" + } + ] + }, + "dcr_bridge": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Dcr Bridge" + }, + "delegate_auth_to_upstream": { + "default": false, + "title": "Delegate Auth To Upstream", + "type": "boolean" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "env": { + "additionalProperties": { + "type": "string" + }, + "title": "Env", + "type": "object" + }, + "env_vars": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/MCPEnvVar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Env Vars" + }, + "extra_headers": { + "items": { + "type": "string" + }, + "title": "Extra Headers", + "type": "array" + }, + "has_user_credential": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Has User Credential" + }, + "health_check_error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Health Check Error" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Instructions" + }, + "is_byok": { + "default": false, + "title": "Is Byok", + "type": "boolean" + }, + "issuer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Issuer" + }, + "last_health_check": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Last Health Check" + }, + "max_concurrent_requests": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Concurrent Requests" + }, + "mcp_access_groups": { + "items": { + "type": "string" + }, + "title": "Mcp Access Groups", + "type": "array" + }, + "mcp_info": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Mcp Info" + }, + "oauth2_flow": { + "anyOf": [ + { + "enum": [ + "client_credentials", + "authorization_code" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Oauth2 Flow" + }, + "oauth_passthrough": { + "default": false, + "title": "Oauth Passthrough", + "type": "boolean" + }, + "registration_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Registration Url" + }, + "review_notes": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Review Notes" + }, + "reviewed_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Reviewed At" + }, + "server_id": { + "title": "Server Id", + "type": "string" + }, + "server_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Server Name" + }, + "source_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Source Url" + }, + "spec_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Spec Path" + }, + "static_headers": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Static Headers" + }, + "status": { + "anyOf": [ + { + "enum": [ + "healthy", + "unhealthy", + "unknown" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": "unknown", + "description": "Health status: 'healthy', 'unhealthy', 'unknown'", + "title": "Status" + }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, + "submitted_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Submitted At" + }, + "submitted_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Submitted By" + }, + "teams": { + "items": { + "additionalProperties": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "type": "object" + }, + "title": "Teams", + "type": "array" + }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Timeout" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, + "token_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Url" + }, + "tool_name_to_description": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Tool Name To Description" + }, + "tool_name_to_display_name": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Tool Name To Display Name" + }, + "transport": { + "enum": [ + "sse", + "http", + "stdio" + ], + "title": "Transport", + "type": "string" + }, + "updated_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Updated At" + }, + "updated_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Updated By" + }, + "url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Url" + } + }, + "required": [ + "server_id", + "transport" + ], + "title": "LiteLLM_MCPServerTable", + "type": "object" + }, + "MCPCredentials": { + "properties": { + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, + "auth_value": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Auth Value" + }, + "aws_access_key_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Aws Access Key Id" + }, + "aws_region_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Aws Region Name" + }, + "aws_role_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Aws Role Name" + }, + "aws_secret_access_key": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Aws Secret Access Key" + }, + "aws_service_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Aws Service Name" + }, + "aws_session_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Aws Session Name" + }, + "aws_session_token": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Aws Session Token" + }, + "client_assertion_signing_alg": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Assertion Signing Alg" + }, + "client_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Id" + }, + "client_private_key": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key" + }, + "client_private_key_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key Id" + }, + "client_secret": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Secret" + }, + "id_jag_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource" + }, + "id_jag_resource_token_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource Token Endpoint" + }, + "redirect_uris": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Redirect Uris" + }, + "scopes": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Scopes" + }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, + "token_endpoint_auth_method": { + "anyOf": [ + { + "enum": [ + "client_secret_basic", + "client_secret_post" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Endpoint Auth Method" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, + "upstream_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Resource" + }, + "upstream_token_header": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Token Header" + } + }, + "title": "MCPCredentials", + "type": "object" + }, + "MCPEnvVar": { + "description": "One environment variable for an MCP server.\n\nVariables can be interpolated into ``static_headers`` using ``${NAME}``\nsyntax. ``scope=global`` values are stored on the server. ``scope=user``\nvalues are stored per-user in ``LiteLLM_MCPUserEnvVars`` and supplied by\neach user.", + "properties": { + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "name": { + "title": "Name", + "type": "string" + }, + "scope": { + "$ref": "#/components/schemas/MCPEnvVarScope", + "default": "global" + }, + "value": { + "default": "", + "title": "Value", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "MCPEnvVar", + "type": "object" + }, + "MCPEnvVarScope": { + "description": "Scope for an MCP server environment variable.\n\n- ``global``: value is provided by the admin and used for all users.\n- ``user``: each user must provide their own value via the per-user\n env-var endpoint. The admin-supplied ``value`` is treated as a\n placeholder/hint and is not used at request time.", + "enum": [ + "global", + "user" + ], + "title": "MCPEnvVarScope", + "type": "string" + }, "MCPOAuthUserCredentialRequest": { "description": "Stores a user's OAuth2 token for an OpenAPI MCP server.", "properties": { @@ -15537,6 +20687,112 @@ "title": "MCPUserCredentialResponse", "type": "object" }, + "MCPUserEnvVarSpec": { + "description": "Describes one per-user env var slot for the calling user.\n\nStored values are write-only: the status only reports whether a value\n``is_set`` and never echoes the decrypted secret back to the client.", + "properties": { + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "is_set": { + "default": false, + "title": "Is Set", + "type": "boolean" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "MCPUserEnvVarSpec", + "type": "object" + }, + "MCPUserEnvVarsRequest": { + "description": "Payload for storing the calling user's per-user env var values.", + "properties": { + "values": { + "additionalProperties": { + "type": "string" + }, + "title": "Values", + "type": "object" + } + }, + "required": [ + "values" + ], + "title": "MCPUserEnvVarsRequest", + "type": "object" + }, + "MCPUserEnvVarsStatus": { + "description": "Per-user env var status for a single MCP server.", + "properties": { + "alias": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Alias" + }, + "missing_count": { + "default": 0, + "title": "Missing Count", + "type": "integer" + }, + "required": { + "items": { + "$ref": "#/components/schemas/MCPUserEnvVarSpec" + }, + "title": "Required", + "type": "array" + }, + "server_id": { + "title": "Server Id", + "type": "string" + }, + "server_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Server Name" + }, + "setup_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Setup Url" + } + }, + "required": [ + "server_id" + ], + "title": "MCPUserEnvVarsStatus", + "type": "object" + }, "MakeMCPServersPublicRequest": { "properties": { "mcp_server_ids": { @@ -15604,6 +20860,17 @@ "title": "Args", "type": "array" }, + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_type": { "anyOf": [ { @@ -15615,7 +20882,11 @@ "authorization", "oauth2", "aws_sigv4", - "token" + "token", + "oauth2_token_exchange", + "oauth2_id_jag", + "true_passthrough", + "oauth_delegate" ], "type": "string" }, @@ -15680,6 +20951,22 @@ } ] }, + "dcr_bridge": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Dcr Bridge" + }, + "delegate_auth_to_upstream": { + "default": false, + "title": "Delegate Auth To Upstream", + "type": "boolean" + }, "description": { "anyOf": [ { @@ -15698,6 +20985,20 @@ "title": "Env", "type": "object" }, + "env_vars": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/MCPEnvVar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Env Vars" + }, "extra_headers": { "anyOf": [ { @@ -15728,6 +21029,28 @@ "title": "Is Byok", "type": "boolean" }, + "issuer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Issuer" + }, + "max_concurrent_requests": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Concurrent Requests" + }, "mcp_access_groups": { "items": { "type": "string" @@ -15762,6 +21085,11 @@ ], "title": "Oauth2 Flow" }, + "oauth_passthrough": { + "default": false, + "title": "Oauth Passthrough", + "type": "boolean" + }, "registration_url": { "anyOf": [ { @@ -15831,6 +21159,17 @@ ], "title": "Static Headers" }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, "submitted_at": { "anyOf": [ { @@ -15856,6 +21195,39 @@ "description": "Server-managed: set by the endpoint; caller values are overridden.", "title": "Submitted By" }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Timeout" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, "token_url": { "anyOf": [ { @@ -16008,6 +21380,17 @@ "title": "Args", "type": "array" }, + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_type": { "anyOf": [ { @@ -16019,7 +21402,11 @@ "authorization", "oauth2", "aws_sigv4", - "token" + "token", + "oauth2_token_exchange", + "oauth2_id_jag", + "true_passthrough", + "oauth_delegate" ], "type": "string" }, @@ -16084,6 +21471,22 @@ } ] }, + "dcr_bridge": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Dcr Bridge" + }, + "delegate_auth_to_upstream": { + "default": false, + "title": "Delegate Auth To Upstream", + "type": "boolean" + }, "description": { "anyOf": [ { @@ -16102,6 +21505,20 @@ "title": "Env", "type": "object" }, + "env_vars": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/MCPEnvVar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Env Vars" + }, "extra_headers": { "anyOf": [ { @@ -16132,6 +21549,28 @@ "title": "Is Byok", "type": "boolean" }, + "issuer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Issuer" + }, + "max_concurrent_requests": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Concurrent Requests" + }, "mcp_access_groups": { "items": { "type": "string" @@ -16151,6 +21590,26 @@ ], "title": "Mcp Info" }, + "oauth2_flow": { + "anyOf": [ + { + "enum": [ + "client_credentials", + "authorization_code" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Oauth2 Flow" + }, + "oauth_passthrough": { + "default": false, + "title": "Oauth Passthrough", + "type": "boolean" + }, "registration_url": { "anyOf": [ { @@ -16213,6 +21672,50 @@ ], "title": "Static Headers" }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Timeout" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, "token_url": { "anyOf": [ { @@ -16331,6 +21834,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -16600,6 +22110,18 @@ "description": "Filter MCP servers by team scope. When provided, returns only servers the team has access to plus globally available (allow_all_keys) servers. Used by the Create Key UI to show team-scoped MCP servers.", "title": "Team Id" } + }, + { + "description": "Annotate each returned server with connected_app_reachable: whether a connected app authorized by the calling user (a gateway OAuth session) is served this server on the aggregate MCP endpoint.", + "in": "query", + "name": "connected_app_view", + "required": false, + "schema": { + "default": false, + "description": "Annotate each returned server with connected_app_reachable: whether a connected app authorized by the calling user (a gateway OAuth session) is served this server on the aggregate MCP endpoint.", + "title": "Connected App View", + "type": "boolean" + } } ], "responses": { @@ -17438,6 +22960,156 @@ ] } }, + "/v1/mcp/server/{server_id}/user-env-vars": { + "delete": { + "description": "Clear the calling user's per-user MCP env var values for this server.", + "operationId": "clear_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_delete", + "parameters": [ + { + "in": "path", + "name": "server_id", + "required": true, + "schema": { + "title": "Server Id", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MCPUserEnvVarsStatus" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Clear Mcp User Env Vars", + "tags": [ + "mcp_management" + ] + }, + "get": { + "description": "Return the calling user's per-user MCP env var status for this server.", + "operationId": "get_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_get", + "parameters": [ + { + "in": "path", + "name": "server_id", + "required": true, + "schema": { + "title": "Server Id", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MCPUserEnvVarsStatus" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Get Mcp User Env Vars", + "tags": [ + "mcp_management" + ] + }, + "post": { + "description": "Store the calling user's per-user MCP env var values for this server. Submitted values are merged over any previously stored values, so you only send the fields you want to set or change; a variable omitted (or sent empty) keeps its stored value. Use DELETE to clear all stored values.", + "operationId": "store_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_post", + "parameters": [ + { + "in": "path", + "name": "server_id", + "required": true, + "schema": { + "title": "Server Id", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MCPUserEnvVarsRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MCPUserEnvVarsStatus" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Store Mcp User Env Vars", + "tags": [ + "mcp_management" + ] + } + }, "/v1/mcp/tools": { "get": { "description": "Get all MCP tools available for the current key, including those from access groups", @@ -17746,6 +23418,37 @@ "mcp_management" ] } + }, + "/v1/mcp/user-env-vars/status": { + "get": { + "description": "Per-user MCP env var status across every server the user can access. Used by the dashboard to highlight servers with missing per-user vars.", + "operationId": "list_mcp_user_env_var_status_v1_mcp_user_env_vars_status_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/MCPUserEnvVarsStatus" + }, + "title": "Response List Mcp User Env Var Status V1 Mcp User Env Vars Status Get", + "type": "array" + } + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "List Mcp User Env Var Status", + "tags": [ + "mcp_management" + ] + } } } }, @@ -17767,6 +23470,17 @@ }, "MCPCredentials": { "properties": { + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_value": { "anyOf": [ { @@ -17855,6 +23569,17 @@ ], "title": "Aws Session Token" }, + "client_assertion_signing_alg": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Assertion Signing Alg" + }, "client_id": { "anyOf": [ { @@ -17866,6 +23591,28 @@ ], "title": "Client Id" }, + "client_private_key": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key" + }, + "client_private_key_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Client Private Key Id" + }, "client_secret": { "anyOf": [ { @@ -17877,6 +23624,42 @@ ], "title": "Client Secret" }, + "id_jag_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource" + }, + "id_jag_resource_token_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id Jag Resource Token Endpoint" + }, + "redirect_uris": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Redirect Uris" + }, "scopes": { "anyOf": [ { @@ -17890,11 +23673,124 @@ } ], "title": "Scopes" + }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, + "token_endpoint_auth_method": { + "anyOf": [ + { + "enum": [ + "client_secret_basic", + "client_secret_post" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Endpoint Auth Method" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, + "upstream_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Resource" + }, + "upstream_token_header": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Upstream Token Header" } }, "title": "MCPCredentials", "type": "object" }, + "MCPEnvVar": { + "description": "One environment variable for an MCP server.\n\nVariables can be interpolated into ``static_headers`` using ``${NAME}``\nsyntax. ``scope=global`` values are stored on the server. ``scope=user``\nvalues are stored per-user in ``LiteLLM_MCPUserEnvVars`` and supplied by\neach user.", + "properties": { + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "name": { + "title": "Name", + "type": "string" + }, + "scope": { + "$ref": "#/components/schemas/MCPEnvVarScope", + "default": "global" + }, + "value": { + "default": "", + "title": "Value", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "MCPEnvVar", + "type": "object" + }, + "MCPEnvVarScope": { + "description": "Scope for an MCP server environment variable.\n\n- ``global``: value is provided by the admin and used for all users.\n- ``user``: each user must provide their own value via the per-user\n env-var endpoint. The admin-supplied ``value`` is treated as a\n placeholder/hint and is not used at request time.", + "enum": [ + "global", + "user" + ], + "title": "MCPEnvVarScope", + "type": "string" + }, "NewMCPServerRequest": { "properties": { "alias": { @@ -17946,6 +23842,17 @@ "title": "Args", "type": "array" }, + "audience": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Audience" + }, "auth_type": { "anyOf": [ { @@ -17957,7 +23864,11 @@ "authorization", "oauth2", "aws_sigv4", - "token" + "token", + "oauth2_token_exchange", + "oauth2_id_jag", + "true_passthrough", + "oauth_delegate" ], "type": "string" }, @@ -18022,6 +23933,22 @@ } ] }, + "dcr_bridge": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Dcr Bridge" + }, + "delegate_auth_to_upstream": { + "default": false, + "title": "Delegate Auth To Upstream", + "type": "boolean" + }, "description": { "anyOf": [ { @@ -18040,6 +23967,20 @@ "title": "Env", "type": "object" }, + "env_vars": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/MCPEnvVar" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Env Vars" + }, "extra_headers": { "anyOf": [ { @@ -18070,6 +24011,28 @@ "title": "Is Byok", "type": "boolean" }, + "issuer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Issuer" + }, + "max_concurrent_requests": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Concurrent Requests" + }, "mcp_access_groups": { "items": { "type": "string" @@ -18104,6 +24067,11 @@ ], "title": "Oauth2 Flow" }, + "oauth_passthrough": { + "default": false, + "title": "Oauth Passthrough", + "type": "boolean" + }, "registration_url": { "anyOf": [ { @@ -18173,6 +24141,17 @@ ], "title": "Static Headers" }, + "subject_token_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Token Type" + }, "submitted_at": { "anyOf": [ { @@ -18198,6 +24177,39 @@ "description": "Server-managed: set by the endpoint; caller values are overridden.", "title": "Submitted By" }, + "timeout": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Timeout" + }, + "token_exchange_endpoint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Endpoint" + }, + "token_exchange_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Token Exchange Profile" + }, "token_url": { "anyOf": [ { @@ -18264,6 +24276,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -18415,7 +24434,7 @@ }, "/mcp-rest/tools/list": { "get": { - "description": "List all available tools with information about the server they belong to.\n\nExample response:\n{\n \"tools\": [\n {\n \"name\": \"create_zap\",\n \"description\": \"Create a new zap\",\n \"inputSchema\": \"tool_input_schema\",\n \"mcp_info\": {\n \"server_name\": \"zapier\",\n \"logo_url\": \"https://www.zapier.com/logo.png\",\n }\n }\n ],\n \"error\": null,\n \"message\": \"Successfully retrieved tools\"\n}", + "description": "List all available tools with information about the server they belong to.\n\nExample response:\n{\n \"tools\": [\n {\n \"name\": \"create_zap\",\n \"description\": \"Create a new zap\",\n \"inputSchema\": \"tool_input_schema\",\n \"mcp_info\": {\n \"server_name\": \"zapier\",\n \"logo_url\": \"https://www.zapier.com/logo.png\",\n \"server_id\": \"a1b2c3d4-...\",\n \"alias\": \"zapier_prod\",\n }\n }\n ],\n \"error\": null,\n \"message\": \"Successfully retrieved tools\"\n}", "operationId": "list_tool_rest_api_mcp_rest_tools_list_get", "parameters": [ { @@ -18435,6 +24454,54 @@ "description": "The server id to list tools for", "title": "Server Id" } + }, + { + "description": "Filter tools to a single MCP server by name or alias", + "in": "query", + "name": "mcp_server_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Filter tools to a single MCP server by name or alias", + "title": "Mcp Server Name" + } + }, + { + "description": "Filter tools to a single toolset by name", + "in": "query", + "name": "toolset_name", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Filter tools to a single toolset by name", + "title": "Toolset Name" + } + }, + { + "description": "Admin only. Return the full server tool catalog without the allowed_tools filter or per-key tool permissions, so the MCP settings UI can configure the allowlist. Ignored for non-admins.", + "in": "query", + "name": "include_disabled_tools", + "required": false, + "schema": { + "default": false, + "description": "Admin only. Return the full server tool catalog without the allowed_tools filter or per-key tool permissions, so the MCP settings UI can configure the allowlist. Ignored for non-admins.", + "title": "Include Disabled Tools", + "type": "boolean" + } } ], "responses": { @@ -18655,6 +24722,14 @@ }, "ChatCompletionCachedContent": { "properties": { + "ttl": { + "enum": [ + "5m", + "1h" + ], + "title": "Ttl", + "type": "string" + }, "type": { "const": "ephemeral", "title": "Type", @@ -19053,8 +25128,15 @@ "title": "Cache Control" }, "signature": { - "title": "Signature", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Signature" }, "thinking": { "title": "Thinking", @@ -19149,7 +25231,14 @@ }, { "items": { - "$ref": "#/components/schemas/ChatCompletionTextObject" + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionTextObject" + }, + { + "$ref": "#/components/schemas/ChatCompletionImageObject" + } + ] }, "type": "array" } @@ -19176,6 +25265,13 @@ }, "ChatCompletionToolParam": { "properties": { + "allowed_callers": { + "items": { + "type": "string" + }, + "title": "Allowed Callers", + "type": "array" + }, "cache_control": { "$ref": "#/components/schemas/ChatCompletionCachedContent" }, @@ -19437,6 +25533,13 @@ ], "title": "Model" }, + "stream_holdback_chars": { + "items": { + "type": "integer" + }, + "title": "Stream Holdback Chars", + "type": "array" + }, "structured_messages": { "items": { "anyOf": [ @@ -20096,6 +26199,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -22046,7 +28156,7 @@ }, "/policies/list": { "get": { - "description": "List all policies from the database and config.yaml. Optionally filter by version_status.\n\nConfig-defined policies are returned with definition_location \"config\" and are treated\nas production versions. On a name conflict with a DB policy, only the DB policy is returned.\n\nQuery params:\n- version_status: Optional. One of \"draft\", \"published\", \"production\".\n If omitted, all versions are returned.\n\nExample Request:\n```bash\ncurl -X GET \"http://localhost:4000/policies/list\" \\\n -H \"Authorization: Bearer \"\ncurl -X GET \"http://localhost:4000/policies/list?version_status=production\" \\\n -H \"Authorization: Bearer \"\n```\n\nExample Response:\n```json\n{\n \"policies\": [\n {\n \"policy_id\": \"123e4567-e89b-12d3-a456-426614174000\",\n \"policy_name\": \"global-baseline\",\n \"version_number\": 1,\n \"version_status\": \"production\",\n \"inherit\": null,\n \"description\": \"Base guardrails for all requests\",\n \"guardrails_add\": [\"pii_masking\"],\n \"guardrails_remove\": [],\n \"condition\": null,\n \"created_at\": \"2024-01-01T00:00:00Z\",\n \"updated_at\": \"2024-01-01T00:00:00Z\"\n }\n ],\n \"total_count\": 1\n}\n```", + "description": "List all policies from the database and config.yaml. Optionally filter by version_status.\n\nConfig-defined policies are returned with definition_location \"config\" and are treated\nas production versions. On a name conflict with a production DB policy, only the DB policy\nis returned, mirroring runtime resolution where only production DB versions override config.\nA draft or published DB version does not hide the config policy, since the config version\nis still the one being enforced.\n\nQuery params:\n- version_status: Optional. One of \"draft\", \"published\", \"production\".\n If omitted, all versions are returned.\n\nExample Request:\n```bash\ncurl -X GET \"http://localhost:4000/policies/list\" \\\n -H \"Authorization: Bearer \"\ncurl -X GET \"http://localhost:4000/policies/list?version_status=production\" \\\n -H \"Authorization: Bearer \"\n```\n\nExample Response:\n```json\n{\n \"policies\": [\n {\n \"policy_id\": \"123e4567-e89b-12d3-a456-426614174000\",\n \"policy_name\": \"global-baseline\",\n \"version_number\": 1,\n \"version_status\": \"production\",\n \"inherit\": null,\n \"description\": \"Base guardrails for all requests\",\n \"guardrails_add\": [\"pii_masking\"],\n \"guardrails_remove\": [],\n \"condition\": null,\n \"created_at\": \"2024-01-01T00:00:00Z\",\n \"updated_at\": \"2024-01-01T00:00:00Z\"\n }\n ],\n \"total_count\": 1\n}\n```", "operationId": "list_policies_policies_list_get", "parameters": [ { @@ -22946,6 +29056,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -23096,7 +29213,7 @@ "Body_convert_prompt_file_to_json_utils_dotprompt_json_converter_post": { "properties": { "file": { - "format": "binary", + "contentMediaType": "application/octet-stream", "title": "File", "type": "string" } @@ -23502,6 +29619,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -24147,6 +30271,26 @@ ], "title": "RealtimeClientSecretResponse", "type": "object" + }, + "RealtimeTranscriptionSessionResponse": { + "additionalProperties": true, + "description": "Response from POST /v1/realtime/transcription_sessions.\n\n`client_secret.value` contains the encrypted token instead of the raw\nephemeral key. Unknown fields pass through unchanged.", + "properties": { + "client_secret": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Client Secret" + } + }, + "title": "RealtimeTranscriptionSessionResponse", + "type": "object" } } }, @@ -24196,6 +30340,33 @@ ] } }, + "/openai/v1/realtime/transcription_sessions": { + "post": { + "description": "Create an ephemeral Realtime transcription session\n(POST /v1/realtime/transcription_sessions) for the WebRTC/WebSocket flow.\n\nMirrors the client_secrets route but targets the transcription_sessions\nendpoint and encrypts the ephemeral key returned under `client_secret.value`.", + "operationId": "create_realtime_transcription_session_openai_v1_realtime_transcription_sessions_post", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionResponse" + } + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Create Realtime Transcription Session", + "tags": [ + "realtime" + ] + } + }, "/realtime/calls": { "post": { "operationId": "proxy_realtime_calls_realtime_calls_post", @@ -24241,6 +30412,33 @@ ] } }, + "/realtime/transcription_sessions": { + "post": { + "description": "Create an ephemeral Realtime transcription session\n(POST /v1/realtime/transcription_sessions) for the WebRTC/WebSocket flow.\n\nMirrors the client_secrets route but targets the transcription_sessions\nendpoint and encrypts the ephemeral key returned under `client_secret.value`.", + "operationId": "create_realtime_transcription_session_realtime_transcription_sessions_post", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionResponse" + } + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Create Realtime Transcription Session", + "tags": [ + "realtime" + ] + } + }, "/v1/realtime/calls": { "post": { "operationId": "proxy_realtime_calls_v1_realtime_calls_post", @@ -24285,6 +30483,33 @@ "realtime" ] } + }, + "/v1/realtime/transcription_sessions": { + "post": { + "description": "Create an ephemeral Realtime transcription session\n(POST /v1/realtime/transcription_sessions) for the WebRTC/WebSocket flow.\n\nMirrors the client_secrets route but targets the transcription_sessions\nendpoint and encrypts the ephemeral key returned under `client_secret.value`.", + "operationId": "create_realtime_transcription_session_v1_realtime_transcription_sessions_post", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionResponse" + } + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Create Realtime Transcription Session", + "tags": [ + "realtime" + ] + } } } }, @@ -24304,6 +30529,77 @@ "title": "HTTPValidationError", "type": "object" }, + "SCIMEnterpriseUser": { + "properties": { + "costCenter": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Costcenter" + }, + "department": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Department" + }, + "division": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Division" + }, + "employeeNumber": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Employeenumber" + }, + "manager": { + "anyOf": [ + { + "$ref": "#/components/schemas/SCIMUserManager" + }, + { + "type": "null" + } + ] + }, + "organization": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Organization" + } + }, + "title": "SCIMEnterpriseUser", + "type": "object" + }, "SCIMFeature": { "properties": { "maxOperations": { @@ -24425,7 +30721,7 @@ "anyOf": [ { "items": { - "$ref": "#/components/schemas/SCIMUser" + "$ref": "#/components/schemas/SCIMUser-Output" }, "type": "array" }, @@ -24497,6 +30793,17 @@ ], "title": "Display" }, + "type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Type" + }, "value": { "title": "Value", "type": "string" @@ -24508,6 +30815,52 @@ "title": "SCIMMember", "type": "object" }, + "SCIMMultiValuedAttribute": { + "properties": { + "display": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Display" + }, + "primary": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Primary" + }, + "type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Type" + }, + "value": { + "title": "Value", + "type": "string" + } + }, + "required": [ + "value" + ], + "title": "SCIMMultiValuedAttribute", + "type": "object" + }, "SCIMPatchOp": { "properties": { "Operations": { @@ -24646,7 +30999,7 @@ "title": "SCIMServiceProviderConfig", "type": "object" }, - "SCIMUser": { + "SCIMUser-Input": { "properties": { "active": { "default": true, @@ -24678,6 +31031,20 @@ ], "title": "Emails" }, + "entitlements": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/SCIMMultiValuedAttribute" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Entitlements" + }, "externalId": { "anyOf": [ { @@ -24736,6 +31103,20 @@ } ] }, + "roles": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/SCIMMultiValuedAttribute" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Roles" + }, "schemas": { "items": { "type": "string" @@ -24743,6 +31124,16 @@ "title": "Schemas", "type": "array" }, + "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": { + "anyOf": [ + { + "$ref": "#/components/schemas/SCIMEnterpriseUser" + }, + { + "type": "null" + } + ] + }, "userName": { "anyOf": [ { @@ -24761,6 +31152,10 @@ "title": "SCIMUser", "type": "object" }, + "SCIMUser-Output": { + "additionalProperties": true, + "type": "object" + }, "SCIMUserEmail": { "properties": { "primary": { @@ -24833,6 +31228,45 @@ "title": "SCIMUserGroup", "type": "object" }, + "SCIMUserManager": { + "properties": { + "$ref": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "$Ref" + }, + "displayName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Displayname" + }, + "value": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Value" + } + }, + "title": "SCIMUserManager", + "type": "object" + }, "SCIMUserName": { "properties": { "familyName": { @@ -24907,6 +31341,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -25817,7 +32258,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SCIMUser" + "$ref": "#/components/schemas/SCIMUser-Input" } } }, @@ -25828,7 +32269,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SCIMUser" + "$ref": "#/components/schemas/SCIMUser-Output" } } }, @@ -25947,7 +32388,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SCIMUser" + "$ref": "#/components/schemas/SCIMUser-Output" } } }, @@ -26019,7 +32460,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SCIMUser" + "$ref": "#/components/schemas/SCIMUser-Output" } } }, @@ -26080,7 +32521,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SCIMUser" + "$ref": "#/components/schemas/SCIMUser-Input" } } }, @@ -26091,7 +32532,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SCIMUser" + "$ref": "#/components/schemas/SCIMUser-Output" } } }, @@ -26387,6 +32828,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -28290,6 +34738,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -28389,6 +34844,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -28937,6 +35399,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -30490,16 +36959,7 @@ }, "required": [ "vector_store_id", - "custom_llm_provider", - "vector_store_name", - "vector_store_description", - "vector_store_metadata", - "created_at", - "updated_at", - "litellm_credential_name", - "litellm_params", - "team_id", - "user_id" + "custom_llm_provider" ], "title": "LiteLLM_ManagedVectorStoresTable", "type": "object" @@ -30515,6 +36975,13 @@ }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -30998,8 +37465,118 @@ "title": "IndexCreateRequest", "type": "object" }, + "IndexListResponse": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/LiteLLM_ManagedVectorStoreIndex" + }, + "title": "Data", + "type": "array" + }, + "object": { + "const": "list", + "default": "list", + "title": "Object", + "type": "string" + } + }, + "required": [ + "data" + ], + "title": "IndexListResponse", + "type": "object" + }, + "LiteLLM_ManagedVectorStoreIndex": { + "description": "LiteLLM managed vector store index object - this is is the object stored in the database", + "properties": { + "created_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created At" + }, + "created_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created By" + }, + "id": { + "title": "Id", + "type": "string" + }, + "index_info": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Index Info" + }, + "index_name": { + "title": "Index Name", + "type": "string" + }, + "litellm_params": { + "$ref": "#/components/schemas/IndexCreateLiteLLMParams" + }, + "updated_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Updated At" + }, + "updated_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Updated By" + } + }, + "required": [ + "id", + "index_name", + "litellm_params" + ], + "title": "LiteLLM_ManagedVectorStoreIndex", + "type": "object" + }, "ValidationError": { "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, "loc": { "items": { "anyOf": [ @@ -31035,8 +37612,33 @@ }, "paths": { "/v1/indexes": { + "get": { + "description": "List all vector store indexes. Proxy admin only.\n\n```bash\ncurl -L -X GET 'http://0.0.0.0:4000/v1/indexes' -H 'Authorization: Bearer sk-1234'\n```", + "operationId": "index_list_v1_indexes_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IndexListResponse" + } + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Index List", + "tags": [ + "vector_stores" + ] + }, "post": { - "description": "Create an index. Just writes the index to the database.\n\n```bash\ncurl -L -X POST 'http://0.0.0.0:4000/indexes/create' -H 'Content-Type: application/json' -H 'Authorization: Bearer sk-1234' -H 'LiteLLM-Beta: indexes_beta=v1' -d '{ \n \"index_name\": \"dall-e-3\",\n \"vector_store_index\": \"real-index-name\",\n \"vector_store_name\": \"azure-ai-search\"\n }'\n```", + "description": "Create an index. Just writes the index to the database.\n\n```bash\ncurl -L -X POST 'http://0.0.0.0:4000/v1/indexes' -H 'Content-Type: application/json' -H 'Authorization: Bearer sk-1234' -d '{\n \"index_name\": \"dall-e-3\",\n \"litellm_params\": {\n \"vector_store_index\": \"real-index-name\",\n \"vector_store_name\": \"azure-ai-search\"\n }\n }'\n```", "operationId": "index_create_v1_indexes_post", "requestBody": { "content": { diff --git a/litellm/proxy/_lazy_openapi_snapshot.py b/litellm/proxy/_lazy_openapi_snapshot.py index 41359d44b27..49d277cd3d1 100644 --- a/litellm/proxy/_lazy_openapi_snapshot.py +++ b/litellm/proxy/_lazy_openapi_snapshot.py @@ -3,18 +3,27 @@ Per-feature OpenAPI snapshot for lazy-loaded routers. The committed JSON is generated by `python -m litellm.proxy._lazy_openapi_snapshot` and consumed at runtime so /openapi.json can show full route info for unloaded -features without importing them. No CI job regenerates this file; drift surfaces -only indirectly through check-ui-api-types.yml, which rebuilds schema.d.ts from -app.openapi() with the committed snapshot injected. After changing any lazily -loaded route or this generator, rerun the module and commit the JSON, then run -`npm run gen:api` in ui/litellm-dashboard and commit schema.d.ts. +features without importing them. check-ui-api-types.yml (mirrored locally by +`make check`) regenerates this file and fails when the committed copy differs, +then rebuilds schema.d.ts from app.openapi() with the snapshot injected. After +changing any lazily loaded route or this generator, rerun the module and commit +the JSON, then run `npm run gen:api` in ui/litellm-dashboard and commit schema.d.ts. """ import json import re import sys +from collections.abc import Callable, Mapping +from dataclasses import dataclass from pathlib import Path -from typing import Final +from typing import TYPE_CHECKING, Final + +from typing_extensions import ReadOnly, TypedDict + +if TYPE_CHECKING: + from fastapi import FastAPI + + from litellm.proxy._lazy_features import LazyFeature SNAPSHOT_FILE: Final = Path(__file__).parent / "_lazy_openapi_snapshot.json" HTTP_METHOD_SUFFIXES: Final = { @@ -83,51 +92,84 @@ def _normalize_operation_ids(paths: dict[str, dict]) -> None: break -def generate_snapshot() -> dict[str, dict]: +class SnapshotFragment(TypedDict): + paths: ReadOnly[Mapping[str, Mapping[str, object]]] + components: ReadOnly[Mapping[str, Mapping[str, object]]] + + +@dataclass(frozen=True, slots=True) +class SnapshotResult: + fragments: Mapping[str, SnapshotFragment] + skipped: tuple[str, ...] + + +def _register_feature(app: "FastAPI", feat: "LazyFeature") -> str | None: import importlib + try: + feat.register_fn(app, importlib.import_module(feat.module_path)) + except Exception as exc: + sys.stderr.write(f"warning: skip {feat.name}: {exc}\n") + return feat.name + return None + + +def _feature_fragment(app: "FastAPI", feat: "LazyFeature", used_operation_ids: set[str]) -> SnapshotFragment | None: from fastapi.openapi.utils import get_openapi + from litellm.proxy.proxy_server import ensure_unique_openapi_operation_ids + + feat_routes: Final = [r for r in app.routes if feat.matches(getattr(r, "path", ""))] + if not feat_routes: + return None + _stabilize_multi_method_route_ids(feat_routes) + full: Final = get_openapi(title=app.title, version=app.version, routes=feat_routes) + paths: Final = full.get("paths", {}) + _normalize_operation_ids(paths) + # Group all of a feature's routes under one tag. + for path_ops in paths.values(): + for method, op in path_ops.items(): + if isinstance(op, dict): + operation_id = op.get("operationId") + if isinstance(operation_id, str): + for suffix in HTTP_METHOD_SUFFIXES: + if operation_id.endswith(f"_{suffix}"): + op["operationId"] = operation_id[: -len(suffix)] + method + break + op["tags"] = [feat.name] + unique: Final = ensure_unique_openapi_operation_ids(full, used_operation_ids) + return { + "paths": paths, + "components": {"schemas": unique.get("components", {}).get("schemas", {})}, + } + + +def generate_snapshot() -> SnapshotResult: from litellm.proxy._lazy_features import LAZY_FEATURES - from litellm.proxy.proxy_server import app, ensure_unique_openapi_operation_ids + from litellm.proxy.proxy_server import app - for feat in LAZY_FEATURES: - try: - module = importlib.import_module(feat.module_path) - feat.register_fn(app, module) - except Exception as exc: - sys.stderr.write(f"warning: skip {feat.name}: {exc}\n") - - fragments: Final[dict[str, dict]] = {} + skipped: Final = tuple(name for feat in LAZY_FEATURES if (name := _register_feature(app, feat)) is not None) used_operation_ids: Final[set[str]] = set() - for feat in LAZY_FEATURES: - feat_routes = [r for r in app.routes if feat.matches(getattr(r, "path", ""))] - if not feat_routes: - continue - _stabilize_multi_method_route_ids(feat_routes) - full = get_openapi(title=app.title, version=app.version, routes=feat_routes) - paths = full.get("paths", {}) - _normalize_operation_ids(paths) - # Group all of a feature's routes under one tag. - for path_ops in full.get("paths", {}).values(): - for method, op in path_ops.items(): - if isinstance(op, dict): - operation_id = op.get("operationId") - if isinstance(operation_id, str): - for suffix in HTTP_METHOD_SUFFIXES: - if operation_id.endswith(f"_{suffix}"): - op["operationId"] = operation_id[: -len(suffix)] + method - break - op["tags"] = [feat.name] - full = ensure_unique_openapi_operation_ids(full, used_operation_ids) - fragments[feat.name] = { - "paths": paths, - "components": {"schemas": full.get("components", {}).get("schemas", {})}, - } - return fragments + fragments: Final = { + feat.name: fragment + for feat in LAZY_FEATURES + if (fragment := _feature_fragment(app, feat, used_operation_ids)) is not None + } + return SnapshotResult(fragments=fragments, skipped=skipped) + + +def main(snapshot_file: Path = SNAPSHOT_FILE, generate: Callable[[], SnapshotResult] = generate_snapshot) -> int: + result: Final = generate() + if result.skipped: + sys.stderr.write( + f"error: {len(result.skipped)} feature(s) failed to import, so their fragments would vanish from the " + f"snapshot: {', '.join(result.skipped)}\n" + ) + return 1 + snapshot_file.write_text(json.dumps(result.fragments, indent=2, sort_keys=True) + "\n") + sys.stdout.write(f"wrote {len(result.fragments)} feature fragments to {snapshot_file}\n") + return 0 if __name__ == "__main__": - fragments: Final = generate_snapshot() - SNAPSHOT_FILE.write_text(json.dumps(fragments, indent=2, sort_keys=True) + "\n") - sys.stdout.write(f"wrote {len(fragments)} feature fragments to {SNAPSHOT_FILE}\n") + sys.exit(main()) diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py index bb26350e1b1..ed49ca2caa9 100644 --- a/litellm/proxy/_types.py +++ b/litellm/proxy/_types.py @@ -2510,6 +2510,18 @@ class ConfigGeneralSettings(LiteLLMPydanticObjectBase): "are skipped for on-demand GET /health as well as the background health loop." ), ) + background_health_check_model_groups: tuple[str, ...] | None = Field( + None, + description=( + "Opt-in allowlist of model group names for background health checks and " + "health-check routing. When set, the background loop probes only deployments " + "whose model_name is listed, and enable_health_check_routing filters unhealthy " + "deployments only within the listed groups; every other group, including newly " + "added deployments, is skipped and keeps its configured routing strategy. " + "When unset, all deployments participate (opt out per deployment via " + "model_info.disable_background_health_check)." + ), + ) model_list_healthy_only: bool | None = Field( None, description=( diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py index 90a16052b71..e92d090a2fb 100644 --- a/litellm/proxy/auth/user_api_key_auth.py +++ b/litellm/proxy/auth/user_api_key_auth.py @@ -1769,7 +1769,12 @@ async def _user_api_key_auth_builder( return valid_token - if valid_token is not None and isinstance(valid_token, UserAPIKeyAuth) and valid_token.team_id is not None: + if ( + valid_token is not None + and isinstance(valid_token, UserAPIKeyAuth) + and valid_token.team_id is not None + and valid_token.team_id != UI_TEAM_ID + ): ## UPDATE TEAM VALUES BASED ON CACHED TEAM OBJECT - allows `/team/update` values to work for cached token try: team_obj: Final[LiteLLM_TeamTableCachedObj] = await get_team_object( @@ -2149,6 +2154,8 @@ async def _user_api_key_auth_builder( # Check 6: Additional Common Checks across jwt + key auth if valid_token.team_id is not None: try: + if valid_token.team_id == UI_TEAM_ID: + raise TeamNotFoundError(team_id=UI_TEAM_ID) with tracer.trace("litellm.proxy.auth.get_team_object"): _team_obj = await get_team_object( team_id=valid_token.team_id, @@ -2443,7 +2450,7 @@ async def _run_centralized_common_checks( ) fetch_coros: Final = [] - if user_api_key_auth_obj.team_id is not None: + if user_api_key_auth_obj.team_id is not None and user_api_key_auth_obj.team_id != UI_TEAM_ID: fetch_coros.append( _safe_fetch( "team", @@ -2567,7 +2574,9 @@ async def _run_centralized_common_checks( else: raise team_result else: - team_object = team_result + team_object = ( + _team_obj_from_token(user_api_key_auth_obj) if user_api_key_auth_obj.team_id == UI_TEAM_ID else team_result + ) user_object: LiteLLM_UserTable | None = None if isinstance(user_result, BaseException) else user_result project_object: Final[LiteLLM_ProjectTableCachedObj | None] = ( diff --git a/litellm/proxy/common_utils/reset_budget_job.py b/litellm/proxy/common_utils/reset_budget_job.py index 4ebcc549cdd..b8b9500ff63 100644 --- a/litellm/proxy/common_utils/reset_budget_job.py +++ b/litellm/proxy/common_utils/reset_budget_job.py @@ -1,5 +1,6 @@ import asyncio import json +import math import time from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from dataclasses import dataclass @@ -45,6 +46,7 @@ from litellm.repositories.table_repositories import ( ) from litellm.repositories.team_repository import TeamRepository from litellm.repositories.unit_of_work import ( + LinkedSpendResetWrites, budget_cascade_unit_of_work, spend_reset_unit_of_work, ) @@ -59,7 +61,15 @@ _LINKED_KEYS_WHERE: Final[Mapping[str, object]] = MappingProxyType({"budget_dura _SPENT_ROWS_WHERE: Final[Mapping[str, object]] = MappingProxyType({"spend": {"gt": 0}}) -class _TeamMembershipRow(Protocol): +class _BudgetLinkedRow(Protocol): + @property + def spend(self) -> float | None: ... + + @property + def budget_id(self) -> str | None: ... + + +class _TeamMembershipRow(_BudgetLinkedRow, Protocol): @property def user_id(self) -> str: ... @@ -67,26 +77,48 @@ class _TeamMembershipRow(Protocol): def team_id(self) -> str: ... -class _KeyRow(Protocol): +class _KeyRow(_BudgetLinkedRow, Protocol): @property def token(self) -> str: ... -class _OrgRow(Protocol): +class _OrgRow(_BudgetLinkedRow, Protocol): @property def organization_id(self) -> str: ... -class _TagRow(Protocol): +class _TagRow(_BudgetLinkedRow, Protocol): @property def tag_name(self) -> str: ... -class _EndUserRow(Protocol): +class _EndUserRow(_BudgetLinkedRow, Protocol): @property def user_id(self) -> str: ... +def _rollover_enabled() -> bool: + return litellm.budget_rollover is True + + +def _rollover_cap(max_budget: float | None) -> float | None: + if max_budget is None or not math.isfinite(max_budget): + return None + return max_budget + + +def _carried_spend(spend: float | None, cap: float | None) -> float: + if cap is None: + return 0.0 + return max(0.0, (spend or 0.0) - cap) + + +def _row_carried_spend(row: _BudgetLinkedRow, caps: Mapping[str, float]) -> float: + if not caps: + return 0.0 + return _carried_spend(row.spend, caps.get(row.budget_id) if row.budget_id is not None else None) + + def _team_membership_counter_key(row: _TeamMembershipRow) -> str: return f"spend:team_member:{row.user_id}:{row.team_id}" @@ -129,6 +161,59 @@ def _budget_link_where( return {"budget_id": {"in": list(budget_ids)}, **extra} +def _queue_budget_linked_resets( + writes: LinkedSpendResetWrites, + cascade: "_BudgetCascade", + extra: Mapping[str, object] = MappingProxyType({}), +) -> None: + """Reset one linked table's spend for every expiring tier: tiers with a + rollover cap keep spend beyond the cap (decrement preserves writes racing + the reset), everything else is zeroed as before. Zero the under-cap rows + BEFORE decrementing the over-cap ones: the statements run sequentially in + one transaction, so the reverse order lets the zero re-match a row the + decrement just moved into the (0, cap] range and erase its carried spend.""" + for budget_id, cap in cascade.rollover_caps.items(): + writes.queue_spend_zero( + where={"budget_id": budget_id, **extra, "spend": {"gt": 0, "lte": cap}} + ) # mutable-ok: prisma where filter must be a dict + writes.queue_spend_decrement( + where={"budget_id": budget_id, **extra, "spend": {"gt": cap}}, amount=cap + ) # mutable-ok: prisma where filter must be a dict + plain_ids: Final = tuple(bid for bid in cascade.budget_ids if bid not in cascade.rollover_caps) + if plain_ids: + writes.queue_spend_zero(where=_budget_link_where(plain_ids, extra)) + + +def _queue_enduser_resets(writes: LinkedSpendResetWrites, cascade: "_BudgetCascade") -> None: + """End users are matched by id rather than budget link: rows with no + budget_id ride the default budget tier (litellm.max_end_user_budget_id). + Zero-before-decrement ordering matters here too (see + _queue_budget_linked_resets).""" + if not cascade.rollover_caps: + if cascade.endusers: + writes.queue_spend_zero( + where={"user_id": {"in": [row.user_id for row in cascade.endusers]}} + ) # mutable-ok: prisma where filter must be a dict + return + tiered: Final = tuple((row.budget_id or litellm.max_end_user_budget_id, row.user_id) for row in cascade.endusers) + for budget_id, cap in cascade.rollover_caps.items(): + if not ( + user_ids := [uid for bid, uid in tiered if bid == budget_id] + ): # mutable-ok: prisma "in" filter takes a list + continue + writes.queue_spend_zero( + where={"user_id": {"in": user_ids}, "spend": {"lte": cap}} + ) # mutable-ok: prisma where filter must be a dict + writes.queue_spend_decrement( + where={"user_id": {"in": user_ids}, "spend": {"gt": cap}}, amount=cap + ) # mutable-ok: prisma where filter must be a dict + plain: Final = [ + uid for bid, uid in tiered if bid is None or bid not in cascade.rollover_caps + ] # mutable-ok: prisma "in" filter takes a list + if plain: + writes.queue_spend_zero(where={"user_id": {"in": plain}}) # mutable-ok: prisma where filter must be a dict + + @dataclass(frozen=True, slots=True) class _BudgetCascade: """Everything one budget-tier reset touches, resolved before any write.""" @@ -137,8 +222,9 @@ class _BudgetCascade: budget_ids: tuple[str, ...] = () budget_resets: tuple[tuple[str, datetime], ...] = () endusers: tuple[_EndUserRow, ...] = () - counter_keys: tuple[str, ...] = () + counter_resets: tuple[tuple[str, float], ...] = () cache_keys: tuple[str, ...] = () + rollover_caps: Mapping[str, float] = MappingProxyType({}) @dataclass(frozen=True, slots=True) @@ -404,8 +490,10 @@ class ResetBudgetJob: ) @staticmethod - async def _invalidate_spend_counter(counter_key: str) -> None: - """Zero a spend counter so a DB-row reset takes effect immediately. + async def _invalidate_spend_counter(counter_key: str, new_spend: float = 0.0) -> None: + """Overwrite a spend counter with the post-reset value (0, or the carried + overage when budget rollover is enabled) so a DB-row reset takes effect + immediately. Call AFTER the DB write commits. Clearing Redis before the DB commit opens a window where get_current_spend reads 0 from Redis @@ -414,10 +502,10 @@ class ResetBudgetJob: try: from litellm.proxy.proxy_server import spend_counter_cache - spend_counter_cache.in_memory_cache.set_cache(key=counter_key, value=0.0, ttl=60) + spend_counter_cache.in_memory_cache.set_cache(key=counter_key, value=new_spend, ttl=60) if spend_counter_cache.redis_cache is not None: try: - await spend_counter_cache.redis_cache.async_set_cache(key=counter_key, value=0.0, ttl=60) + await spend_counter_cache.redis_cache.async_set_cache(key=counter_key, value=new_spend, ttl=60) except Exception as redis_err: verbose_proxy_logger.warning( "Failed to reset spend counter %s in Redis: %s. " @@ -522,6 +610,15 @@ class ResetBudgetJob: where=_budget_link_where(budget_ids, _SPENT_ROWS_WHERE), log_subject="tags", ) + rollover_caps: Final[Mapping[str, float]] = MappingProxyType( + { # mutable-ok: MappingProxyType wraps a one-shot dict comprehension + b.budget_id: cap + for b in budgets_to_reset + if b.budget_id is not None and (cap := _rollover_cap(b.max_budget)) is not None + } + if _rollover_enabled() + else {} # mutable-ok: empty sentinel immediately frozen by MappingProxyType + ) return _BudgetCascade( budgets=tuple(budgets_to_reset), budget_ids=budget_ids, @@ -534,12 +631,16 @@ class ResetBudgetJob: if b.budget_id is not None and b.budget_duration is not None ), endusers=await self._collect_endusers_to_reset(budget_ids), - counter_keys=( - *(_team_membership_counter_key(row) for row in team_memberships), - *(_key_counter_key(row) for row in keys), - *(_org_counter_key(row) for row in orgs), - *(_tag_counter_key(row) for row in tags), + counter_resets=( + *( + (_team_membership_counter_key(row), _row_carried_spend(row, rollover_caps)) + for row in team_memberships + ), + *((_key_counter_key(row), _row_carried_spend(row, rollover_caps)) for row in keys), + *((_org_counter_key(row), _row_carried_spend(row, rollover_caps)) for row in orgs), + *((_tag_counter_key(row), _row_carried_spend(row, rollover_caps)) for row in tags), ), + rollover_caps=rollover_caps, cache_keys=( *(key for row in team_memberships for key in _team_membership_cache_keys(row)), *(key for row in keys for key in _key_cache_keys(row)), @@ -565,20 +666,18 @@ class ResetBudgetJob: ) async def _commit_budget_cascade_once(self, cascade: _BudgetCascade) -> None: - enduser_ids: Final = tuple(row.user_id for row in cascade.endusers) async with budget_cascade_unit_of_work(self.prisma_client.db.batch_) as uow: - uow.team_memberships.queue_spend_zero(where=_budget_link_where(cascade.budget_ids)) - uow.keys.queue_spend_zero(where=_budget_link_where(cascade.budget_ids, _LINKED_KEYS_WHERE)) - uow.organizations.queue_spend_zero(where=_budget_link_where(cascade.budget_ids, _SPENT_ROWS_WHERE)) - uow.tags.queue_spend_zero(where=_budget_link_where(cascade.budget_ids, _SPENT_ROWS_WHERE)) - if enduser_ids: - uow.endusers.queue_spend_zero(where={"user_id": {"in": list(enduser_ids)}}) + _queue_budget_linked_resets(uow.team_memberships, cascade) + _queue_budget_linked_resets(uow.keys, cascade, extra=_LINKED_KEYS_WHERE) + _queue_budget_linked_resets(uow.organizations, cascade, extra=_SPENT_ROWS_WHERE) + _queue_budget_linked_resets(uow.tags, cascade, extra=_SPENT_ROWS_WHERE) + _queue_enduser_resets(uow.endusers, cascade) for budget_id, budget_reset_at in cascade.budget_resets: uow.budgets.queue_window_advance(budget_id=budget_id, budget_reset_at=budget_reset_at) async def _invalidate_budget_cascade_caches(self, cascade: _BudgetCascade) -> None: - for counter_key in cascade.counter_keys: - await self._invalidate_spend_counter(counter_key) + for counter_key, new_spend in cascade.counter_resets: + await self._invalidate_spend_counter(counter_key, new_spend=new_spend) for cache_key in cascade.cache_keys: await self._invalidate_user_api_key_cache_entry(cache_key) @@ -708,7 +807,11 @@ class ResetBudgetJob: for k in updated_keys: if k.token is None: continue - uow.keys.queue_spend_reset(token=k.token, budget_reset_at=k.budget_reset_at) + uow.keys.queue_spend_reset( + token=k.token, + budget_reset_at=k.budget_reset_at, + spend_decrement=k.max_budget if (k.spend or 0.0) > 0.0 else None, + ) async def _write_user_reset_updates(self, updated_users: list[LiteLLM_UserTable]) -> None: """ @@ -726,7 +829,11 @@ class ResetBudgetJob: async def _write_user_reset_updates_once(self, updated_users: list[LiteLLM_UserTable]) -> None: async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow: for u in updated_users: - uow.users.queue_spend_reset(user_id=u.user_id, budget_reset_at=u.budget_reset_at) + uow.users.queue_spend_reset( + user_id=u.user_id, + budget_reset_at=u.budget_reset_at, + spend_decrement=u.max_budget if (u.spend or 0.0) > 0.0 else None, + ) async def _write_team_reset_updates(self, updated_teams: list[LiteLLM_TeamTable]) -> None: """ @@ -744,7 +851,11 @@ class ResetBudgetJob: async def _write_team_reset_updates_once(self, updated_teams: list[LiteLLM_TeamTable]) -> None: async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow: for t in updated_teams: - uow.teams.queue_spend_reset(team_id=t.team_id, budget_reset_at=t.budget_reset_at) + uow.teams.queue_spend_reset( + team_id=t.team_id, + budget_reset_at=t.budget_reset_at, + spend_decrement=t.max_budget if (t.spend or 0.0) > 0.0 else None, + ) def _emit_phase_failure( self, @@ -820,7 +931,7 @@ class ResetBudgetJob: for k in updated_keys: token = getattr(k, "token", None) if token: - await self._invalidate_spend_counter(f"spend:key:{token}") + await self._invalidate_spend_counter(f"spend:key:{token}", new_spend=k.spend or 0.0) end_time = time.time() outcome: Final = _ChunkOutcome( @@ -925,7 +1036,7 @@ class ResetBudgetJob: for u in updated_users: user_id = getattr(u, "user_id", None) if user_id: - await self._invalidate_spend_counter(f"spend:user:{user_id}") + await self._invalidate_spend_counter(f"spend:user:{user_id}", new_spend=u.spend or 0.0) if user_id == LITELLM_PROXY_BUDGET_NAME: await self._invalidate_global_proxy_spend_cache() @@ -1034,7 +1145,7 @@ class ResetBudgetJob: for t in updated_teams: team_id = getattr(t, "team_id", None) if team_id: - await self._invalidate_spend_counter(f"spend:team:{team_id}") + await self._invalidate_spend_counter(f"spend:team:{team_id}", new_spend=t.spend or 0.0) end_time = time.time() outcome: Final = _ChunkOutcome( @@ -1107,10 +1218,11 @@ class ResetBudgetJob: reset_at: Final = datetime.fromisoformat(reset_at_str.replace("Z", "+00:00")).replace(tzinfo=None) if reset_at > now: return False - spend_counter_cache.in_memory_cache.set_cache(key=counter_key, value=0.0) + new_value: Final = await ResetBudgetJob._window_carried_spend(window, counter_key, spend_counter_cache) + spend_counter_cache.in_memory_cache.set_cache(key=counter_key, value=new_value) if spend_counter_cache.redis_cache is not None: try: - await spend_counter_cache.redis_cache.async_set_cache(key=counter_key, value=0.0) + await spend_counter_cache.redis_cache.async_set_cache(key=counter_key, value=new_value) except Exception as redis_err: verbose_proxy_logger.warning("Failed to reset Redis counter %s: %s", counter_key, redis_err) window["reset_at"] = compute_budget_reset_at( @@ -1118,6 +1230,27 @@ class ResetBudgetJob: ).isoformat() return True + @staticmethod + async def _window_carried_spend( + window: Mapping[str, object], counter_key: str, spend_counter_cache: DualCache + ) -> float: + """Per-window spend lives only in the counter, so the carried overage is + read from it before the reset overwrites it.""" + if not _rollover_enabled(): + return 0.0 + window_max: Final = window.get("max_budget") + cap: Final = _rollover_cap(window_max) if isinstance(window_max, (int, float)) else None + if cap is None: + return 0.0 + try: + current: Final = await spend_counter_cache.async_get_cache(key=counter_key) + except Exception as e: # noqa: BLE001 # an unreadable counter falls back to a plain zero reset + verbose_proxy_logger.warning("Failed to read spend counter %s for rollover: %s", counter_key, e) + return 0.0 + if not isinstance(current, (int, float)): + return 0.0 + return _carried_spend(float(current), cap) + async def reset_budget_windows(self) -> None: """ For keys and teams with budget_limits, reset any individual windows where @@ -1222,7 +1355,7 @@ class ResetBudgetJob: still holds the pre-reset value, admitting requests past the cap. """ try: - item.spend = 0.0 + item.spend = _carried_spend(item.spend, _rollover_cap(item.max_budget)) if _rollover_enabled() else 0.0 if hasattr(item, "budget_duration") and item.budget_duration is not None: item.budget_reset_at = compute_budget_reset_at( budget_duration=item.budget_duration, settings=reset_settings diff --git a/litellm/proxy/db/prisma_client.py b/litellm/proxy/db/prisma_client.py index fc761fc1831..4bd007769b8 100644 --- a/litellm/proxy/db/prisma_client.py +++ b/litellm/proxy/db/prisma_client.py @@ -887,6 +887,22 @@ class PrismaManager: return ProxyExtrasDBManager.apply_replica_identity_full_if_requested() + @staticmethod + def _raise_if_partitioned_spend_logs() -> None: + """`prisma db push` rewrites a doc-partitioned LiteLLM_SpendLogs + primary key back to ("request_id"), which Postgres rejects. Fail fast + with guidance instead of retrying into that raw error. No-op when + litellm-proxy-extras is absent.""" + try: + from litellm_proxy_extras.utils import ( + PARTITIONED_SPEND_LOGS_PUSH_ERROR, + ProxyExtrasDBManager, + ) + except ImportError: + return + if ProxyExtrasDBManager.spend_logs_is_partitioned(): + raise RuntimeError(PARTITIONED_SPEND_LOGS_PUSH_ERROR) + @staticmethod def setup_database(use_migrate: bool = False, use_v2_resolver: bool = False) -> bool: """ @@ -921,6 +937,7 @@ class PrismaManager: use_v2_resolver=use_v2_resolver, ) else: + PrismaManager._raise_if_partitioned_spend_logs() # Use prisma db push with increased timeout subprocess.run( [ diff --git a/litellm/proxy/health_check.py b/litellm/proxy/health_check.py index 9b60595838d..219f6f270ed 100644 --- a/litellm/proxy/health_check.py +++ b/litellm/proxy/health_check.py @@ -7,8 +7,11 @@ import sys import threading import time from collections.abc import Mapping, Sequence +from collections.abc import Set as AbstractSet from types import MappingProxyType -from typing import TYPE_CHECKING, Final +from typing import TYPE_CHECKING, Final, TypeVar + +from pydantic import TypeAdapter, ValidationError import litellm @@ -16,6 +19,7 @@ if TYPE_CHECKING: from litellm.router import Router logger: Final = logging.getLogger(__name__) +_DeploymentT: Final = TypeVar("_DeploymentT", bound=Mapping[str, object]) from litellm.constants import ( BACKGROUND_HEALTH_CHECK_MAX_TOKENS, BACKGROUND_HEALTH_CHECK_MAX_TOKENS_REASONING, @@ -167,6 +171,38 @@ def health_check_filter_kwargs_from_general_settings( } +def parse_background_health_check_model_groups( + general_settings: Mapping[str, object] | None, +) -> frozenset[str] | None: + """ + Read ``general_settings.background_health_check_model_groups``. + + ``None`` means the allowlist is unset and every deployment participates + (legacy behavior). A list scopes background health checks and health-check + routing to deployments whose ``model_name`` is listed. A malformed value + raises so the proxy fails at startup instead of silently probing everything. + """ + raw: Final = (general_settings or {}).get("background_health_check_model_groups") + if raw is None: + return None + try: + return frozenset(TypeAdapter(list[str]).validate_python(raw)) + except ValidationError as e: + raise ValueError( + "general_settings.background_health_check_model_groups must be a list of model group names" + ) from e + + +def filter_deployments_to_model_groups( + model_list: Sequence[_DeploymentT], + model_groups: AbstractSet[str] | None, +) -> tuple[_DeploymentT, ...]: + """Deployments whose ``model_name`` is in ``model_groups``; all of them when unset.""" + if model_groups is None: + return tuple(model_list) + return tuple(x for x in model_list if x.get("model_name") in model_groups) + + def filter_deployments_by_id( model_list: Sequence[Mapping[str, object]], ) -> list: diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py index 064b53e07b7..f3df7c6580a 100644 --- a/litellm/proxy/litellm_pre_call_utils.py +++ b/litellm/proxy/litellm_pre_call_utils.py @@ -19,6 +19,7 @@ from litellm.constants import ( CONSUMED_REQUEST_TAGS_METADATA_KEY, INTERNAL_CALL_ORIGIN_METADATA_KEY, LITELLM_PROXY_MASTER_KEY_ALIAS, + OTEL_SERVICE_NAME_METADATA_KEYS, PRE_CALL_EXECUTED_GUARDRAILS_KEY, SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY, ) @@ -2003,6 +2004,19 @@ async def add_litellm_data_to_request( _metadata_variable_name=_metadata_variable_name, ) + # A key's OTel service name outranks its team's, so the key's values are + # re-applied after the last-writer-wins team metadata merge above + _key_otel_service_names: Final = { + field: value + for field, value in (key_metadata or {}).items() + if field in OTEL_SERVICE_NAME_METADATA_KEYS and isinstance(value, str) and value.strip() + } + data = LiteLLMProxyRequestSetup.add_management_endpoint_metadata_to_request_metadata( + data=data, + management_endpoint_metadata=_key_otel_service_names, + _metadata_variable_name=_metadata_variable_name, + ) + # Team spend, budget - used by prometheus.py data[_metadata_variable_name]["user_api_key_team_max_budget"] = user_api_key_dict.team_max_budget data[_metadata_variable_name]["user_api_key_team_spend"] = user_api_key_dict.team_spend diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index d1c08352919..97999cbb6d7 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -2190,7 +2190,7 @@ async def _get_and_validate_existing_key( existing_key_row: Final[LiteLLM_VerificationToken | None] = await _prisma_table( VerificationTokenRepository(prisma_client) - ).find_unique(where={"token": hashed_token}) + ).find_unique(where={"token": hashed_token}, include={"object_permission": True}) if existing_key_row is None: raise ProxyException( @@ -2442,11 +2442,13 @@ async def _validate_mcp_servers_for_key_update( check_db_only=True, ) object_permission_dict: Final = _object_permission_to_dict(data.object_permission) + team_unchanged: Final = data.team_id is None or data.team_id == existing_key_row.team_id normalized_object_permission: Final = await validate_key_mcp_servers_against_team( object_permission=object_permission_dict, team_obj=effective_team_obj, prisma_client=prisma_client, is_proxy_admin=is_proxy_admin, + existing_key_object_permission=existing_key_row.object_permission if team_unchanged else None, ) await validate_key_search_tools_against_team( object_permission=object_permission_dict, diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.py index 54a591a5e1a..556a30d0b29 100644 --- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py +++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py @@ -204,6 +204,7 @@ if MCP_AVAILABLE: MCP_ADMIN_CONFIG_CREDENTIAL_KEYS, MCPAuth, MCPCredentials, + normalize_upstream_header_name, ) from litellm.types.mcp_server.mcp_server_manager import MCPServer @@ -239,9 +240,26 @@ if MCP_AVAILABLE: detail={"error": error_messages_text}, ) + def _validate_upstream_token_header(payload: McpServerPayloadLike) -> None: + credentials: Final = getattr(payload, "credentials", None) + raw: Final = credentials.get("upstream_token_header") if isinstance(credentials, dict) else None + if not isinstance(raw, str) or raw == "": + return + if normalize_upstream_header_name(raw) is None: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={ + "error": ( + f"Invalid upstream_token_header {raw!r}: must be a valid HTTP header name " + "(RFC 7230 token, e.g. 'esb-oauth')" + ) + }, + ) + def validate_and_normalize_mcp_server_payload(payload: McpServerPayloadLike) -> None: _base_validate_and_normalize_mcp_server_payload(payload) _validate_mcp_server_name_fields(payload) + _validate_upstream_token_header(payload) def stamp_omitted_oauth2_flow(payload: NewMCPServerRequest) -> None: """Fallback only: fill in oauth2_flow when an oauth2 create omits it. @@ -739,6 +757,7 @@ if MCP_AVAILABLE: ("aws_region_name", "aws_region_name"), ("aws_service_name", "aws_service_name"), ("upstream_resource", "upstream_resource"), + ("upstream_token_header", "upstream_token_header"), ) def _has_non_admin_config_credentials(credentials: "MCPCredentials | None") -> bool: diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py index 0c8240b3298..613508da22b 100644 --- a/litellm/proxy/management_endpoints/ui_sso.py +++ b/litellm/proxy/management_endpoints/ui_sso.py @@ -808,6 +808,15 @@ def normalize_email(email: str | None) -> str | None: return email.lower() if isinstance(email, str) else email +# Ordered highest to lowest privilege +LITELLM_USER_ROLE_HIERARCHY: Final = ( + LitellmUserRoles.PROXY_ADMIN, + LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, + LitellmUserRoles.INTERNAL_USER, + LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, +) + + def determine_role_from_groups( user_groups: list[str], role_mappings: "RoleMappings", @@ -832,19 +841,11 @@ def determine_role_from_groups( # No role mappings configured, return default_role return role_mappings.default_role - # Role hierarchy (highest to lowest) - role_hierarchy: Final = [ - LitellmUserRoles.PROXY_ADMIN, - LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, - LitellmUserRoles.INTERNAL_USER, - LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, - ] - # Convert user_groups to a set for efficient lookup user_groups_set: Final = set(user_groups) if isinstance(user_groups, list) else set() # Find the highest privilege role the user belongs to - for role in role_hierarchy: + for role in LITELLM_USER_ROLE_HIERARCHY: if role in role_mappings.roles: role_groups = role_mappings.roles[role] if isinstance(role_groups, list) and user_groups_set.intersection(set(role_groups)): @@ -4236,15 +4237,7 @@ class MicrosoftSSOHandler: verbose_proxy_logger.debug("Extracted app roles from id_token: %s", app_roles) # Combine groups and app roles - user_role: LitellmUserRoles | None = None - if app_roles: - # Check if any app role is a valid LitellmUserRoles - for role_str in app_roles: - role = get_litellm_user_role(role_str) - if role is not None: - user_role = role - verbose_proxy_logger.debug("Found valid LitellmUserRoles '%s' in app_roles", role.value) - break + user_role: Final = MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) verbose_proxy_logger.debug("Combined team_ids (groups + app roles): %s", user_team_ids) @@ -4282,6 +4275,27 @@ class MicrosoftSSOHandler: verbose_proxy_logger.debug("Microsoft SSO OpenID Response: %s", openid_response) return openid_response + @staticmethod + def get_user_role_from_app_roles( + app_roles: Sequence[str] | None, + ) -> LitellmUserRoles | None: + """ + Resolve the one role LiteLLM stores for a user from their Entra app roles. + + Entra does not guarantee `roles` claim ordering, so a user holding several app + roles resolves to the highest privilege one rather than whichever the claim + listed first. Roles the hierarchy does not rank (org_admin, team, customer) + resolve by name to stay deterministic + """ + resolved: Final = frozenset( + role for role in (get_litellm_user_role(role_str) for role_str in app_roles or ()) if role is not None + ) + if not resolved: + return None + + ranked: Final = next((role for role in LITELLM_USER_ROLE_HIERARCHY if role in resolved), None) + return ranked if ranked is not None else min(resolved, key=lambda role: role.value) + @staticmethod def get_app_roles_from_id_token(id_token: str | None) -> list[str]: """ diff --git a/litellm/proxy/management_helpers/object_permission_utils.py b/litellm/proxy/management_helpers/object_permission_utils.py index fb64914f6f5..13080a6cf83 100644 --- a/litellm/proxy/management_helpers/object_permission_utils.py +++ b/litellm/proxy/management_helpers/object_permission_utils.py @@ -447,6 +447,36 @@ async def enforce_all_proxy_mcp_servers_grant_is_admin_only( ) +async def _get_grandfathered_key_mcp_server_ids( + existing_object_permission: Optional["LiteLLM_ObjectPermissionTable"], + prisma_client: PrismaClient | None, +) -> frozenset[str]: + """ + Resolve the canonical MCP server IDs a key's stored object_permission already + grants. Updates that keep or shrink those grants stay valid even when the + team allowlist has since changed; sentinels are excluded so they cannot + grandfather anything. + """ + if existing_object_permission is None or prisma_client is None: + return frozenset() + raw_tool_perms: Final = existing_object_permission.mcp_tool_permissions or {} + tool_perm_keys: Final[frozenset[str]] = frozenset( + json.loads(raw_tool_perms).keys() if isinstance(raw_tool_perms, str) else raw_tool_perms.keys() + ) + identifiers: Final = (frozenset(existing_object_permission.mcp_servers or []) | tool_perm_keys) - { + SpecialMCPServerNames.no_mcp_servers.value, + SpecialMCPServerName.all_proxy_servers.value, + } + return frozenset( + _flatten_resolved_mcp_server_ids( + await _resolve_mcp_server_identifiers_to_ids( + identifiers=set(identifiers), + prisma_client=prisma_client, + ) + ) + ) + + async def _get_team_allowed_mcp_servers( team_obj: Optional["LiteLLM_TeamTableCachedObj"], prisma_client: PrismaClient | None = None, @@ -527,10 +557,16 @@ async def validate_key_mcp_servers_against_team( team_obj: Optional["LiteLLM_TeamTableCachedObj"], prisma_client: PrismaClient | None = None, is_proxy_admin: bool = False, + existing_key_object_permission: Optional["LiteLLM_ObjectPermissionTable"] = None, ) -> ObjectPermissionDict | None: """ Validate that MCP servers requested on a key are within the allowed scope. + When ``existing_key_object_permission`` is provided (key updates), servers + the key already holds are grandfathered: keeping or removing them stays valid + even if the team allowlist has since shrunk, while adding new servers outside + the allowlist is still rejected. + Rules: - If key is in a team: key's mcp_servers must be a subset of (team's allowed servers + allow_all_keys servers) @@ -589,7 +625,11 @@ async def validate_key_mcp_servers_against_team( if teamless_admin_assignment: allowed_servers = all_allowed_servers | active_requested_servers - disallowed_servers: Final = active_requested_servers - allowed_servers + grandfathered_servers: Final = await _get_grandfathered_key_mcp_server_ids( + existing_object_permission=existing_key_object_permission, + prisma_client=prisma_client, + ) + disallowed_servers: Final = active_requested_servers - allowed_servers - grandfathered_servers if disallowed_servers: if team_obj is not None: team_id = team_obj.team_id diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.py index 0449802abae..8ac63ba25c9 100644 --- a/litellm/proxy/proxy_cli.py +++ b/litellm/proxy/proxy_cli.py @@ -1321,10 +1321,10 @@ def run_server( use_v2_resolver=use_v2_migration_resolver, ) except RuntimeError as e: - # v2 resolver raises on unrecoverable migration errors - # (e.g. non-idempotent failures, permission issues). - # v1 never raises here, so this only fires when the - # operator opted into v2. + # Raised on unrecoverable migration errors: the v2 + # resolver's non-idempotent failures and permission + # issues, and any `prisma db push` against a + # partitioned LiteLLM_SpendLogs. print( f"\033[1;31mLiteLLM Proxy: Database migration cannot proceed. {e}\033[0m", file=sys.stderr, diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index 990682f10a5..af26a9f669e 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -411,7 +411,9 @@ from litellm.proxy.guardrails.init_guardrails import ( initialize_guardrails, ) from litellm.proxy.health_check import ( + filter_deployments_to_model_groups, health_check_filter_kwargs_from_general_settings, + parse_background_health_check_model_groups, perform_health_check, ) from litellm.proxy.health_endpoints._health_endpoints import router as health_router @@ -3660,6 +3662,13 @@ async def _run_background_health_check(): _llm_model_list = [ m for m in _llm_model_list if not m.get("model_info", {}).get("disable_background_health_check", False) ] + scoped_model_groups = llm_router.background_health_check_model_groups if llm_router is not None else None + _llm_model_list = list(filter_deployments_to_model_groups(_llm_model_list, scoped_model_groups)) + if scoped_model_groups is not None and not _llm_model_list: + verbose_proxy_logger.warning( + "background_health_check_model_groups matched no deployments; groups=%s", + sorted(scoped_model_groups), + ) model_count_enabled = len(_llm_model_list) expected_peak_in_flight = model_count_enabled if isinstance(health_check_concurrency, int) and health_check_concurrency > 0 and model_count_enabled > 0: @@ -5239,6 +5248,7 @@ class ProxyConfig: general_settings = config.get("general_settings", {}) if general_settings is None: general_settings = {} + _bg_hc_model_groups: Final = parse_background_health_check_model_groups(general_settings) _enable_hc_routing = False _hc_staleness = None _hc_ignore_transient = False @@ -5434,13 +5444,14 @@ class ProxyConfig: _hc_staleness = general_settings.get("health_check_staleness_threshold", None) _hc_ignore_transient = general_settings.get("health_check_ignore_transient_errors", False) verbose_proxy_logger.info( - "background_health_check_config enabled=%s shared=%s interval_seconds=%s max_concurrency=%s details=%s health_check_routing=%s", + "background_health_check_config enabled=%s shared=%s interval_seconds=%s max_concurrency=%s details=%s health_check_routing=%s model_groups=%s", use_background_health_checks, use_shared_health_check, health_check_interval, health_check_concurrency, health_check_details, _enable_hc_routing, + sorted(_bg_hc_model_groups) if _bg_hc_model_groups is not None else None, ) ### RBAC ### @@ -5472,6 +5483,8 @@ class ProxyConfig: router_params["health_check_staleness_threshold"] = _hc_staleness if _hc_ignore_transient: router_params["health_check_ignore_transient_errors"] = True + if _bg_hc_model_groups is not None: + router_params["background_health_check_model_groups"] = sorted(_bg_hc_model_groups) ## MODEL LIST model_list: Final = config.get("model_list", None) if model_list: @@ -9240,6 +9253,7 @@ class ProxyStartupEvent: prisma_client, pod_lock_manager=proxy_logging_obj.db_spend_update_writer.pod_lock_manager, alert=_alert_ptu_rollup_failure, + router=llm_router, ) scheduler.add_job( @@ -16402,6 +16416,13 @@ _GENERAL_SETTINGS_UI_LITELLM_FIELDS: Final[dict[str, GeneralSettingsUILiteLLMFie "tab": "prompt_caching", "description": "Empty uses Anthropic's 5m default. 1h suits long sessions but doubles the cache write cost.", }, + "budget_rollover": { # mutable-ok: registry literal, frozen with its siblings below + "type": "Boolean", + "description": ( + "Carry spend beyond max_budget into the next window when budgets reset, instead of " + "forgiving it. Applies to key, user, team, team member, org, tag and end-user budgets." + ), + }, "max_ui_session_budget": { "type": "Dollar", "default": 1.0, diff --git a/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py b/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py index 6f1bbaa722b..0e6412a2c64 100644 --- a/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py +++ b/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py @@ -14,7 +14,6 @@ and share the existing unique constraint. import asyncio import json -import sys from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass from datetime import date, datetime, time, timedelta, timezone @@ -326,16 +325,6 @@ class _LoadedDeployments: scanned_ids: frozenset[str] -def _running_router() -> object | None: - """The proxy's router, or None outside a running proxy. - - Read out of ``sys.modules`` rather than imported, so a rollup driven from a test or a - script does not pull the whole proxy server in behind it. - """ - proxy_server: Final = sys.modules.get("litellm.proxy.proxy_server") - return getattr(proxy_server, "llm_router", None) if proxy_server is not None else None - - def _config_deployments(router: object | None, *, owned_by_db: frozenset[str]) -> tuple[_PTUDeployment, ...]: """Deployments the router holds that no ``LiteLLM_ProxyModelTable`` row owns. @@ -356,15 +345,17 @@ def _config_deployments(router: object | None, *, owned_by_db: frozenset[str]) - ) -async def _load_ptu_models(prisma_client: "PrismaClient") -> _LoadedDeployments: +async def _load_ptu_models(prisma_client: "PrismaClient", *, router: object | None) -> _LoadedDeployments: """Every deployment carrying valid manual PTU config, and every id the scan saw. Reserved capacity is billed by the provider whichever file declared it, so a deployment the proxy only knows from config.yaml accrues alongside the stored ones. + The router is handed in rather than read off the proxy module, so a run prices exactly + the deployments its caller declares and nothing a co-resident process left behind. """ rows: Final = await prisma_client.db.litellm_proxymodeltable.find_many() db_ids: Final = frozenset(model_id for row in rows if (model_id := str(getattr(row, "model_id", "") or ""))) - config_records: Final = _config_deployments(_running_router(), owned_by_db=db_ids) + config_records: Final = _config_deployments(router, owned_by_db=db_ids) models: Final = tuple( parsed for parsed in (_parse_ptu_model(row) for row in (*rows, *config_records)) if parsed is not None ) @@ -380,6 +371,7 @@ async def run_ptu_flat_cost_rollup( prisma_client: "PrismaClient", target_date: date | None = None, may_prune: bool = True, + router: object | None = None, ) -> RollupResult: """Rollup one UTC day of flat PTU cost across all PTU-configured model deployments. @@ -406,7 +398,7 @@ async def run_ptu_flat_cost_rollup( date_str: Final = day.isoformat() run_started: Final = datetime.now(timezone.utc) - loaded: Final = await _load_ptu_models(prisma_client) + loaded: Final = await _load_ptu_models(prisma_client, router=router) ptu_models: Final = loaded.models charges: Final = _aggregate_charges(ptu_models, day) @@ -527,6 +519,7 @@ async def _existing_sentinel_keys( async def run_ptu_flat_cost_backfill( prisma_client: "PrismaClient", today: date | None = None, + router: object | None = None, ) -> BackfillResult: """Price the elapsed days of every PTU window that carry no sentinel row yet. @@ -546,7 +539,7 @@ async def run_ptu_flat_cost_backfill( verbose_proxy_logger.warning("PTU backfill: prisma_client is None, skipping") return BackfillResult(start=end, end=end, days_scanned=0, rows_written=0) - ptu_models: Final = (await _load_ptu_models(prisma_client)).models + ptu_models: Final = (await _load_ptu_models(prisma_client, router=router)).models days: Final = _backfill_window(ptu_models, end) if not days: @@ -591,6 +584,7 @@ async def run_scheduled_ptu_rollup( pod_lock_manager: "PodLockManager | None" = None, target_date: date | None = None, alert: Callable[[str], Awaitable[None]] | None = None, + router: object | None = None, ) -> RollupResult | None: """Run the daily rollup under a cross-pod lock so only one proxy reconciles a day. @@ -615,7 +609,7 @@ async def run_scheduled_ptu_rollup( return None if pod_lock_manager is None or pod_lock_manager.redis_cache is None: - return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=False) + return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=False, router=router) if not await pod_lock_manager.acquire_lock(cronjob_id=PTU_ROLLUP_JOB_ID, ttl=PTU_ROLLUP_LOCK_TTL_SECONDS): if await _lock_is_held(pod_lock_manager): @@ -629,10 +623,10 @@ async def run_scheduled_ptu_rollup( "PTU rollup: could not take the rollup lock and no other pod holds it, " "running unguarded rather than skipping the day" ) - return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=False) + return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=False, router=router) try: - return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=True) + return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=True, router=router) finally: await pod_lock_manager.release_lock(cronjob_id=PTU_ROLLUP_JOB_ID) @@ -657,6 +651,7 @@ async def _run_and_alert( target_date: date | None, alert: "Callable[[str], Awaitable[None]] | None", may_prune: bool = True, + router: object | None = None, ) -> RollupResult: """Reconcile the day, catch up any days left unpriced, and alert on charges that did not land. @@ -669,7 +664,9 @@ async def _run_and_alert( explicit date means reconcile exactly that day, so it stays a single-day operation. Its failure is contained: the day's own result is returned either way. """ - result: Final = await run_ptu_flat_cost_rollup(prisma_client, target_date=target_date, may_prune=may_prune) + result: Final = await run_ptu_flat_cost_rollup( + prisma_client, target_date=target_date, may_prune=may_prune, router=router + ) if result.rows_failed: await _deliver_alert( alert, @@ -686,7 +683,7 @@ async def _run_and_alert( "by the provider with nothing attributing it here. Extend the window, or retire the deployment.", ) if target_date is None: - await _backfill_and_alert(prisma_client, alert=alert) + await _backfill_and_alert(prisma_client, alert=alert, router=router) return result @@ -694,6 +691,7 @@ async def _backfill_and_alert( prisma_client: "PrismaClient", *, alert: "Callable[[str], Awaitable[None]] | None", + router: object | None = None, ) -> None: """Catch up unpriced PTU days, alerting on charges that did not land. @@ -701,7 +699,7 @@ async def _backfill_and_alert( caller whatever the catch-up pass does. """ try: - backfill: Final = await run_ptu_flat_cost_backfill(prisma_client) + backfill: Final = await run_ptu_flat_cost_backfill(prisma_client, router=router) except Exception as exc: # noqa: BLE001 # the catch-up pass must not fail the day's rollup verbose_proxy_logger.error("PTU backfill: catch-up pass failed, the day's rollup still stands: %s", exc) return diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.py index 9deb52895f5..1c49ad51beb 100644 --- a/litellm/proxy/spend_tracking/spend_management_endpoints.py +++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py @@ -23,6 +23,7 @@ from typing_extensions import ReadOnly import litellm from litellm._logging import verbose_proxy_logger +from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME from litellm.proxy._types import * from litellm.proxy._types import ProviderBudgetResponse, ProviderBudgetResponseObject from litellm.proxy.auth.user_api_key_auth import user_api_key_auth @@ -54,6 +55,11 @@ router: Final = APIRouter() SPEND_LOGS_PAGINATION_COUNT_CAP: Final = 10000 +_INTERNAL_HEALTH_CHECK_API_KEYS: Final = ( + LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, + hash_token(token=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME), +) + _RowT = TypeVar("_RowT") @@ -2248,6 +2254,10 @@ async def ui_view_spend_logs( status_filter: str | None = fastapi.Query( default=None, description="Filter logs by status (e.g., success, failure)" ), + cache_hit_filter: str | None = fastapi.Query( + default=None, + description="Filter logs by cache state: 'hit' or 'miss'. Miss includes legacy rows with a null/unknown cache state", + ), model: str | None = fastapi.Query(default=None, description="Filter logs by model"), model_id: str | None = fastapi.Query( default=None, @@ -2268,6 +2278,10 @@ async def ui_view_spend_logs( default="desc", description="Sort order: asc or desc", ), + exclude_internal_health_checks: bool = fastapi.Query( + default=False, + description="Exclude LiteLLM internal health check requests from results", + ), ): """ View spend logs with pagination support. @@ -2320,6 +2334,13 @@ async def ui_view_spend_logs( param="sort_order", code=status.HTTP_400_BAD_REQUEST, ) + if isinstance(cache_hit_filter, str) and cache_hit_filter not in {"hit", "miss"}: + raise ProxyException( + message=f"Invalid cache_hit_filter: {cache_hit_filter}. Must be one of: hit, miss", + type="bad_request", + param="cache_hit_filter", + code=status.HTTP_400_BAD_REQUEST, + ) try: is_admin_view: Final = _is_admin_view_safe(user_api_key_dict=user_api_key_dict) @@ -2560,6 +2581,16 @@ async def ui_view_spend_logs( sql_params.append(status_filter) p += 1 + if cache_hit_filter == "hit": + sql_conditions.append("LOWER(cache_hit) = 'true'") + elif cache_hit_filter == "miss": + sql_conditions.append("(cache_hit IS NULL OR LOWER(cache_hit) != 'true')") + + if exclude_internal_health_checks: + sql_conditions.append(f"api_key NOT IN (${p}, ${p + 1})") + sql_params.extend(_INTERNAL_HEALTH_CHECK_API_KEYS) + p += 2 # rebind-ok: advances the file's shared $N placeholder counter + # Spend range if min_spend is not None: sql_conditions.append(f"spend >= ${p}") diff --git a/litellm/repositories/unit_of_work.py b/litellm/repositories/unit_of_work.py index e504baceb9f..eb11ebe3b9c 100644 --- a/litellm/repositories/unit_of_work.py +++ b/litellm/repositories/unit_of_work.py @@ -19,32 +19,57 @@ from collections.abc import AsyncGenerator, Callable, Mapping from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import datetime +from typing import Final from litellm.repositories.prisma_protocols import BatchTable, PrismaBatch +def _spend_reset_data(budget_reset_at: datetime | None, spend_decrement: float | None) -> Mapping[str, object]: + spend: Final[object] = ( + {"decrement": spend_decrement} # mutable-ok: prisma update payload must be a dict + if spend_decrement is not None + else 0 + ) + return {"spend": spend, "budget_reset_at": budget_reset_at} # mutable-ok: prisma update payload must be a dict + + @dataclass(frozen=True, slots=True) class KeySpendResetWrites: table: BatchTable - def queue_spend_reset(self, token: str, budget_reset_at: datetime | None) -> None: - self.table.update(where={"token": token}, data={"spend": 0, "budget_reset_at": budget_reset_at}) + def queue_spend_reset( + self, token: str, budget_reset_at: datetime | None, spend_decrement: float | None = None + ) -> None: + self.table.update( + where={"token": token}, # mutable-ok: prisma where filter must be a dict + data=_spend_reset_data(budget_reset_at, spend_decrement), + ) @dataclass(frozen=True, slots=True) class UserSpendResetWrites: table: BatchTable - def queue_spend_reset(self, user_id: str, budget_reset_at: datetime | None) -> None: - self.table.update(where={"user_id": user_id}, data={"spend": 0, "budget_reset_at": budget_reset_at}) + def queue_spend_reset( + self, user_id: str, budget_reset_at: datetime | None, spend_decrement: float | None = None + ) -> None: + self.table.update( + where={"user_id": user_id}, # mutable-ok: prisma where filter must be a dict + data=_spend_reset_data(budget_reset_at, spend_decrement), + ) @dataclass(frozen=True, slots=True) class TeamSpendResetWrites: table: BatchTable - def queue_spend_reset(self, team_id: str, budget_reset_at: datetime | None) -> None: - self.table.update(where={"team_id": team_id}, data={"spend": 0, "budget_reset_at": budget_reset_at}) + def queue_spend_reset( + self, team_id: str, budget_reset_at: datetime | None, spend_decrement: float | None = None + ) -> None: + self.table.update( + where={"team_id": team_id}, # mutable-ok: prisma where filter must be a dict + data=_spend_reset_data(budget_reset_at, spend_decrement), + ) @dataclass(frozen=True, slots=True) @@ -54,6 +79,14 @@ class LinkedSpendResetWrites: def queue_spend_zero(self, where: Mapping[str, object]) -> None: self.table.update_many(where=where, data={"spend": 0}) + def queue_spend_decrement(self, where: Mapping[str, object], amount: float) -> None: + """``decrement`` rather than a read-then-set, so spend written between the + cascade's read and its commit survives the reset instead of being erased.""" + self.table.update_many( + where=where, + data={"spend": {"decrement": amount}}, # mutable-ok: prisma update payload must be a dict + ) + @dataclass(frozen=True, slots=True) class BudgetWindowWrites: diff --git a/litellm/router.py b/litellm/router.py index f0ebb539bb7..021dafa9791 100644 --- a/litellm/router.py +++ b/litellm/router.py @@ -602,6 +602,7 @@ class Router: enable_health_check_routing: bool = False, health_check_staleness_threshold: int | None = None, health_check_ignore_transient_errors: bool = False, + background_health_check_model_groups: Sequence[str] | None = None, enable_weighted_failover: bool = False, ) -> None: """ @@ -811,6 +812,11 @@ class Router: self.enable_health_check_routing = enable_health_check_routing self.enable_weighted_failover = enable_weighted_failover self.health_check_ignore_transient_errors = health_check_ignore_transient_errors + self.background_health_check_model_groups: frozenset[str] | None = ( + frozenset(background_health_check_model_groups) + if background_health_check_model_groups is not None + else None + ) _staleness: Final = health_check_staleness_threshold or ( DEFAULT_HEALTH_CHECK_INTERVAL * DEFAULT_HEALTH_CHECK_STALENESS_MULTIPLIER ) @@ -9210,7 +9216,11 @@ class Router: } if model_id is not None: - litellm.register_model(model_cost={model_id: model_info}, persist_across_reloads=False) + litellm.register_model( + model_cost={model_id: model_info}, + persist_across_reloads=False, + warning_display_name=model, + ) ## OLD MODEL REGISTRATION ## Kept to prevent breaking changes backend_keys: Final = Router._backend_cost_map_keys(model=model, custom_llm_provider=custom_llm_provider) @@ -12719,6 +12729,10 @@ class Router: """ Filter out deployments marked unhealthy by background health checks. No-op when enable_health_check_routing is False. + When background_health_check_model_groups is set, only deployments in the + listed model groups are filtered; every other group keeps its configured + routing strategy untouched, and a router-level allowed_fails_policy no + longer disables the filter for the listed groups. Returns all deployments if health state is unavailable, stale, or would exclude every candidate (safety net). """ @@ -12727,8 +12741,10 @@ class Router: # When allowed_fails_policy is set, cooldown is the sole routing exclusion # mechanism -- skip the binary health check filter so the policy threshold - # is respected before any deployment is excluded. - if self.allowed_fails_policy is not None: + # is respected before any deployment is excluded. With a model-group + # allowlist the filter is already scoped, so listed groups keep it. + scoped_groups: Final = self.background_health_check_model_groups + if self.allowed_fails_policy is not None and scoped_groups is None: return healthy_deployments unhealthy_ids: Final = await self.health_state_cache.async_get_unhealthy_deployment_ids( @@ -12737,7 +12753,12 @@ class Router: if not unhealthy_ids: return healthy_deployments - filtered: Final = [d for d in healthy_deployments if d["model_info"]["id"] not in unhealthy_ids] + filtered: Final = [ + d + for d in healthy_deployments + if d["model_info"]["id"] not in unhealthy_ids + or (scoped_groups is not None and d["model_name"] not in scoped_groups) + ] if not filtered: verbose_router_logger.warning("All deployments marked unhealthy by health checks, bypassing health filter") @@ -12754,14 +12775,20 @@ class Router: if not self.enable_health_check_routing: return healthy_deployments - if self.allowed_fails_policy is not None: + scoped_groups: Final = self.background_health_check_model_groups + if self.allowed_fails_policy is not None and scoped_groups is None: return healthy_deployments unhealthy_ids: Final = self.health_state_cache.get_unhealthy_deployment_ids(parent_otel_span=parent_otel_span) if not unhealthy_ids: return healthy_deployments - filtered: Final = [d for d in healthy_deployments if d["model_info"]["id"] not in unhealthy_ids] + filtered: Final = [ + d + for d in healthy_deployments + if d["model_info"]["id"] not in unhealthy_ids + or (scoped_groups is not None and d["model_name"] not in scoped_groups) + ] if not filtered: verbose_router_logger.warning("All deployments marked unhealthy by health checks, bypassing health filter") diff --git a/litellm/router_utils/health_state_cache.py b/litellm/router_utils/health_state_cache.py index 95094f7abfa..22d816e13e9 100644 --- a/litellm/router_utils/health_state_cache.py +++ b/litellm/router_utils/health_state_cache.py @@ -43,12 +43,33 @@ class DeploymentHealthCache: self.staleness_threshold = staleness_threshold def set_deployment_health_states(self, states: dict[str, DeploymentHealthStateValue]) -> None: - """Bulk-write all deployment health states as a single cache entry.""" + """Merge the given states into the shared cache entry, pruning expired ones. + + Merging instead of replacing lets writers probing different deployment + scopes (e.g. pods with different background health check allowlists) + coexist on the one shared entry without erasing each other's results. + The snapshot is read from Redis when available, since a pod-local read + would only ever see this writer's own previous merge. When the Redis + read comes back empty (a miss, or a swallowed connection error), the + pod-local copy of the last merge is used so peers are not erased. + """ try: + redis_raw: Final = ( + self.cache.redis_cache.get_cache(self.CACHE_KEY) if self.cache.redis_cache is not None else None + ) + raw: Final = redis_raw if isinstance(redis_raw, dict) else self.cache.get_cache(key=self.CACHE_KEY) + existing: Final = raw if isinstance(raw, dict) else {} + expiry_seconds: Final = self.staleness_threshold * 1.5 + now: Final = time.time() + merged: Final = { + model_id: state + for model_id, state in {**existing, **states}.items() + if isinstance(state, dict) and (now - state.get("timestamp", 0)) < expiry_seconds + } self.cache.set_cache( key=self.CACHE_KEY, - value=states, - ttl=int(self.staleness_threshold * 1.5), + value=merged, + ttl=int(expiry_seconds), ) except Exception as e: verbose_logger.error( diff --git a/litellm/types/llms/gemini_audio_transcription.py b/litellm/types/llms/gemini_audio_transcription.py new file mode 100644 index 00000000000..cb12e0f45b8 --- /dev/null +++ b/litellm/types/llms/gemini_audio_transcription.py @@ -0,0 +1,81 @@ +from typing import Literal, Required + +from pydantic import BaseModel, ConfigDict +from typing_extensions import ReadOnly, TypedDict + + +class GeminiTranscriptionAudioInput(TypedDict): + type: ReadOnly[Literal["audio"]] + data: ReadOnly[str] + mime_type: ReadOnly[str] + + +class GeminiTranscriptionVerbatimMode(TypedDict, total=False): + type: ReadOnly[Required[Literal["verbatim"]]] + timestamp_granularities: ReadOnly[tuple[Literal["word"], ...]] + diarization_mode: ReadOnly[Literal["speaker"]] + + +class GeminiTranscriptionConfig(TypedDict, total=False): + language_codes: ReadOnly[tuple[str, ...]] + mode: ReadOnly[GeminiTranscriptionVerbatimMode] + + +class GeminiTranscriptionGenerationConfig(TypedDict): + transcription_config: ReadOnly[GeminiTranscriptionConfig] + + +class GeminiTranscriptionInteractionRequest(TypedDict, total=False): + model: ReadOnly[Required[str]] + input: ReadOnly[Required[tuple[GeminiTranscriptionAudioInput, ...]]] + generation_config: ReadOnly[GeminiTranscriptionGenerationConfig] + + +class GeminiTranscriptionWordAnnotation(BaseModel): + model_config = ConfigDict(extra="ignore") + + type: str | None = None + text: str | None = None + speaker: str | None = None + start_offset: str | None = None + end_offset: str | None = None + + +class GeminiTranscriptionContent(BaseModel): + model_config = ConfigDict(extra="ignore") + + type: str | None = None + text: str | None = None + annotations: tuple[GeminiTranscriptionWordAnnotation, ...] = () + + +class GeminiTranscriptionStep(BaseModel): + model_config = ConfigDict(extra="ignore") + + type: str | None = None + content: tuple[GeminiTranscriptionContent, ...] = () + + +class GeminiTranscriptionModalityTokens(BaseModel): + model_config = ConfigDict(extra="ignore") + + modality: str | None = None + tokens: int = 0 + + +class GeminiTranscriptionUsage(BaseModel): + model_config = ConfigDict(extra="ignore") + + total_tokens: int = 0 + total_input_tokens: int = 0 + total_output_tokens: int = 0 + input_tokens_by_modality: tuple[GeminiTranscriptionModalityTokens, ...] = () + + +class GeminiTranscriptionInteractionResponse(BaseModel): + model_config = ConfigDict(extra="ignore") + + id: str | None = None + status: str | None = None + usage: GeminiTranscriptionUsage | None = None + steps: tuple[GeminiTranscriptionStep, ...] = () diff --git a/litellm/types/mcp.py b/litellm/types/mcp.py index 57437ea7e54..1b8baf2da09 100644 --- a/litellm/types/mcp.py +++ b/litellm/types/mcp.py @@ -1,6 +1,11 @@ import enum +import re +from collections.abc import Awaitable, Callable, Mapping +from types import MappingProxyType from typing import TYPE_CHECKING, Any, Final, Literal +from urllib.parse import urlsplit +import httpx from pydantic import BaseModel from typing_extensions import TypedDict @@ -181,6 +186,15 @@ class MCPCredentials(TypedDict, total=False): ``audience``, which is the RFC 8693 token-exchange parameter. """ + upstream_token_header: str | None # writable-ok: pydantic warns it cannot honour ReadOnly here + """ + Which upstream header carries the credential LiteLLM resolves for this server. Omitted when + unset, which keeps RFC 6750's default of ``Authorization``. Set it when the upstream expects the + gateway's token somewhere else (an ESB terminating its own credential on e.g. ``esb-oauth``), so + a separate operator-configured ``Authorization`` reaches the origin untouched. Non-secret, so it + is stored in plaintext and returned on admin reads. + """ + client_private_key: str | None """ PEM private key used to sign the private-key-JWT client_assertion (RFC 7523) @@ -223,7 +237,92 @@ class MCPCredentials(TypedDict, total=False): """ -MCP_ADMIN_CONFIG_CREDENTIAL_KEYS: Final[tuple[str, ...]] = ("upstream_resource",) +DEFAULT_CREDENTIAL_HEADER: Final = "Authorization" + +_HEADER_NAME_TOKEN: Final = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$") + + +def normalize_upstream_header_name(raw: str) -> str | None: + """The trimmed header name if it is a usable RFC 7230 ``token``, else None. + + One owner for the grammar; each caller picks its own failure shape (a config-load raise, an + API 400, a typed CredError). An operator-supplied name reaches egress verbatim, so a value + carrying CR/LF, spaces or separators must never get that far. + """ + stripped: Final = raw.strip() + return stripped if stripped and _HEADER_NAME_TOKEN.match(stripped) else None + + +def same_header(name: str, other: str) -> bool: + """Whether two HTTP header names are the same one. They are case-insensitive (RFC 7230 3.2).""" + return name.lower() == other.lower() + + +def has_header(headers: Mapping[str, str] | None, name: str) -> bool: + """Whether ``headers`` carries ``name`` under any casing.""" + return bool(headers) and any(same_header(key, name) for key in headers or {}) + + +def without_header(headers: Mapping[str, str] | None, name: str) -> dict[str, str] | None: + """A copy of ``headers`` with every casing of ``name`` removed, or None if nothing remains. + + The one owner of "drop this credential's header". Both MCP stacks and the upstream-credential + resolver share it so a slot can never be dropped case-sensitively in one place and + case-insensitively in another, which is how an injected header came to shadow a resolved + credential on the v1 path. + """ + if not headers: + return None + filtered: Final = {key: value for key, value in headers.items() if not same_header(key, name)} + return filtered or None + + +_DEFAULT_PORTS: Final[Mapping[str, int]] = MappingProxyType({"http": 80, "https": 443}) + + +def crosses_origin(configured: str, target: str) -> bool: + """Whether ``target`` leaves ``configured``'s origin, by the rule HTTP clients use. + + Origin is scheme, host and port, not host alone, so a same-host HTTPS downgrade or a port change + counts as crossing it. A plain http -> https upgrade of the same host is exempt, matching what + httpx exempts when it decides whether to keep ``Authorization`` across a redirect. + """ + a: Final = urlsplit(configured) + b: Final = urlsplit(target) + port_a: Final = a.port or _DEFAULT_PORTS.get(a.scheme) + port_b: Final = b.port or _DEFAULT_PORTS.get(b.scheme) + if a.scheme == b.scheme and a.hostname == b.hostname and port_a == port_b: + return False + return not ( + a.hostname == b.hostname and a.scheme == "http" and port_a == 80 and b.scheme == "https" and port_b == 443 + ) + + +def custom_credential_slot(headers: Mapping[str, str] | None) -> str | None: + """The first header carrying a credential somewhere other than ``Authorization``, if any.""" + return next((name for name in headers or {} if not same_header(name, DEFAULT_CREDENTIAL_HEADER)), None) + + +def credential_redirect_hook( + configured_url: str, slot: str | None +) -> Callable[[httpx.Request], Awaitable[None]] | None: + """An httpx request hook dropping ``slot`` once a redirect leaves ``configured_url``'s origin. + + None when no guard is needed, so callers do not each repeat the exemption: HTTP clients already + strip ``Authorization`` across origins, but forward every other header, so only a credential an + operator moved to its own slot can be replayed to whatever host the upstream redirects to. + """ + if not configured_url or not slot or same_header(slot, DEFAULT_CREDENTIAL_HEADER): + return None + + async def guard(request: httpx.Request) -> None: + if slot in request.headers and crosses_origin(configured_url, str(request.url)): + del request.headers[slot] + + return guard + + +MCP_ADMIN_CONFIG_CREDENTIAL_KEYS: Final[tuple[str, ...]] = ("upstream_resource", "upstream_token_header") """Non-secret credential keys returned on read so the admin form can show and clear them. Mirrors ``ADMIN_CONFIG_CREDENTIAL_KEYS`` in ``ui/litellm-dashboard/src/components/mcp_tools/types.tsx``.""" diff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.py index 401793a79e4..9bf3acc601c 100644 --- a/litellm/types/mcp_server/mcp_server_manager.py +++ b/litellm/types/mcp_server/mcp_server_manager.py @@ -1,7 +1,7 @@ from datetime import datetime from typing import Any, Final, Literal -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, field_validator from litellm.types.mcp import ( DEFAULT_SUBJECT_TOKEN_TYPE, @@ -9,6 +9,7 @@ from litellm.types.mcp import ( MCPAuthType, MCPTokenEndpointAuthMethod, MCPTransportType, + normalize_upstream_header_name, ) # MCPInfo now allows arbitrary additional fields for custom metadata @@ -86,6 +87,22 @@ class MCPServer(BaseModel): # today's behavior; "auto" derives the canonical URI from ``url``; any other value is sent # verbatim. Resolved by ``oauth_utils.resolve_upstream_resource``. upstream_resource: str | None = None + # Which upstream header carries the credential LiteLLM resolves for this server (the minted + # OAuth token, or the static key). None keeps RFC 6750's default, ``Authorization``. An ESB or + # API gateway that terminates its own credential in a private header needs this so a second, + # operator-configured ``Authorization`` can pass through to the origin untouched. + upstream_token_header: str | None = None + + @field_validator("upstream_token_header") + @classmethod + def _check_upstream_token_header(cls, value: str | None) -> str | None: + if value is None or not value.strip(): + return None + normalized: Final = normalize_upstream_header_name(value) + if normalized is None: + raise ValueError(f"upstream_token_header must be a valid HTTP header name (RFC 7230 token), got {value!r}") + return normalized + # AWS SigV4 fields aws_access_key_id: str | None = None aws_secret_access_key: str | None = None diff --git a/litellm/types/realtime.py b/litellm/types/realtime.py index cbd7a8b7ecb..17dc70126f3 100644 --- a/litellm/types/realtime.py +++ b/litellm/types/realtime.py @@ -162,3 +162,16 @@ class RealtimeErrorDetail(TypedDict): class RealtimeErrorEvent(TypedDict): type: ReadOnly[Literal["error"]] error: ReadOnly[RealtimeErrorDetail] + + +class RealtimeInputAudioTranscriptionUsageInputTokenDetails(TypedDict): + text_tokens: ReadOnly[int] + audio_tokens: ReadOnly[int] + + +class RealtimeInputAudioTranscriptionUsage(TypedDict): + type: ReadOnly[Literal["tokens"]] + input_tokens: ReadOnly[int] + output_tokens: ReadOnly[int] + total_tokens: ReadOnly[int] + input_token_details: ReadOnly[RealtimeInputAudioTranscriptionUsageInputTokenDetails] diff --git a/litellm/utils.py b/litellm/utils.py index 54f97ccae54..b75d0161cb4 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -2948,7 +2948,12 @@ def reapply_runtime_model_cost_registrations() -> None: register_model(model_cost=dict(_runtime_registered_model_cost)) # mutable-ok: snapshot, replay rewrites it -def register_model(model_cost: str | dict, *, persist_across_reloads: bool = True): +def register_model( + model_cost: str | dict, + *, + persist_across_reloads: bool = True, + warning_display_name: str | None = None, +): """ Register new / Override existing models (and their pricing) to specific providers. Provide EITHER a model cost dictionary or a url to a hosted json blob @@ -2968,6 +2973,10 @@ def register_model(model_cost: str | dict, *, persist_across_reloads: bool = Tru registering a model is declaring durable intent. Pass False for a registration that only describes one request, so it is dropped rather than re-asserted over every future catalog. + + ``warning_display_name`` names the model in the missing-cache-pricing + warning instead of the registered key, for callers that register under an + opaque key (e.g. the router's hashed deployment ids). """ loaded_model_cost = {} @@ -3014,10 +3023,14 @@ def register_model(model_cost: str | dict, *, persist_across_reloads: bool = Tru elif ( value.get("cache_creation_input_token_cost") is None and value.get("cache_read_input_token_cost") is None + and value.get("tiered_pricing") is None + and ( + value.get("input_cost_per_token") is not None or value.get("output_cost_per_token") is not None + ) ): verbose_logger.warning( - "register_model: model=%s not in built-in cost map and no prefix/region variant matched; cache cost fields will default to 0. To track cache cost, add cache_creation_input_token_cost and cache_read_input_token_cost to model_info", - key, + "register_model: model=%s has custom pricing but not in built-in cost map and no prefix/region variant matched; cache_creation_input_token_cost and cache_read_input_token_cost will default to 0 for this model (input/output cost tracking is unaffected). To track cache cost, add them to model_info", + warning_display_name or key, ) # ``get_model_info`` returns ``litellm_provider: None`` when the # provider is unknown (e.g. custom deployments registered via @@ -8503,6 +8516,12 @@ class ProviderConfigManager: ) return VertexAIAudioTranscriptionConfig() + elif litellm.LlmProviders.GEMINI == provider: + from litellm.llms.gemini.audio_transcription.transformation import ( + GeminiAudioTranscriptionConfig, + ) + + return GeminiAudioTranscriptionConfig() return None @staticmethod diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index 7f8c464f5b9..82e45337b1f 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -4691,7 +4691,7 @@ "supports_web_search": false }, "azure/gpt-4.1-nano": { - "deprecation_date": "2026-10-14", + "deprecation_date": "2027-04-14", "cache_read_input_token_cost": 2.5e-08, "input_cost_per_token": 1e-07, "input_cost_per_token_batches": 5e-08, @@ -4724,7 +4724,7 @@ "supports_vision": true }, "azure/gpt-4.1-nano-2025-04-14": { - "deprecation_date": "2026-10-14", + "deprecation_date": "2027-04-14", "cache_read_input_token_cost": 2.5e-08, "input_cost_per_token": 1e-07, "input_cost_per_token_batches": 5e-08, @@ -15167,6 +15167,34 @@ "output_dbu_cost_per_token": 7.143e-06, "source": "https://www.databricks.com/product/pricing/foundation-model-serving" }, + "databricks/databricks-glm-5-2": { + "cache_creation_input_token_cost": 1.4e-06, + "cache_read_input_token_cost": 2.5998e-07, + "input_cost_per_token": 1.4e-06, + "input_dbu_cost_per_token": 2e-05, + "litellm_provider": "databricks", + "max_input_tokens": 1000000, + "max_output_tokens": 131072, + "max_tokens": 131072, + "metadata": { + "notes": "Input/output cost per token is dbu cost * $0.070. Billing reads the per-token dollar fields; the '*_dbu_cost_per_token' fields are the published Databricks rates, kept for reference." + }, + "mode": "chat", + "output_cost_per_token": 4.39999e-06, + "output_dbu_cost_per_token": 6.2857e-05, + "source": "https://www.databricks.com/product/pricing/foundation-model-serving", + "supported_modalities": [ + "text" + ], + "supported_output_modalities": [ + "text" + ], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, "databricks/databricks-gpt-5": { "cache_creation_input_token_cost": 1.24999e-06, "cache_read_input_token_cost": 1.2502e-07, @@ -15434,6 +15462,35 @@ "output_vector_size": 1024, "source": "https://www.databricks.com/product/pricing/foundation-model-serving" }, + "databricks/databricks-kimi-k3": { + "cache_creation_input_token_cost": 2.99999e-06, + "cache_read_input_token_cost": 3.0002e-07, + "input_cost_per_token": 2.99999e-06, + "input_dbu_cost_per_token": 4.2857e-05, + "litellm_provider": "databricks", + "max_input_tokens": 1000000, + "max_output_tokens": 1048576, + "max_tokens": 1048576, + "metadata": { + "notes": "Input/output cost per token is dbu cost * $0.070. Billing reads the per-token dollar fields; the '*_dbu_cost_per_token' fields are the published Databricks rates, kept for reference." + }, + "mode": "chat", + "output_cost_per_token": 1.500002e-05, + "output_dbu_cost_per_token": 0.000214286, + "source": "https://www.databricks.com/product/pricing/foundation-model-serving", + "supported_modalities": [ + "text", + "image" + ], + "supported_output_modalities": [ + "text" + ], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": true + }, "databricks/databricks-llama-2-70b-chat": { "cache_creation_input_token_cost": 5.0001e-07, "cache_read_input_token_cost": 5.0001e-07, @@ -16112,12 +16169,13 @@ "max_tokens": 4096, "max_input_tokens": 4096, "max_output_tokens": 4096, - "input_cost_per_token": 8e-08, - "output_cost_per_token": 9e-08, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/NousResearch/Hermes-3-Llama-3.1-405B": { "max_tokens": 131072, @@ -16134,11 +16192,12 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 3e-07, - "output_cost_per_token": 3e-07, + "input_cost_per_token": 7e-07, + "output_cost_per_token": 7e-07, "litellm_provider": "deepinfra", "mode": "chat", - "supports_tool_choice": false + "supports_tool_choice": false, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/QwQ-32B": { "max_tokens": 131072, @@ -16155,12 +16214,13 @@ "max_tokens": 32768, "max_input_tokens": 32768, "max_output_tokens": 32768, - "input_cost_per_token": 1.2e-07, - "output_cost_per_token": 3.9e-07, + "input_cost_per_token": 3.6e-07, + "output_cost_per_token": 4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen2.5-7B-Instruct": { "max_tokens": 32768, @@ -16188,12 +16248,13 @@ "max_tokens": 40960, "max_input_tokens": 40960, "max_output_tokens": 40960, - "input_cost_per_token": 6e-08, + "input_cost_per_token": 1.2e-07, "output_cost_per_token": 2.4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-235B-A22B": { "max_tokens": 40960, @@ -16211,11 +16272,12 @@ "max_input_tokens": 262144, "max_output_tokens": 262144, "input_cost_per_token": 9e-08, - "output_cost_per_token": 6e-07, + "output_cost_per_token": 5.5e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-235B-A22B-Thinking-2507": { "max_tokens": 262144, @@ -16232,23 +16294,25 @@ "max_tokens": 40960, "max_input_tokens": 40960, "max_output_tokens": 40960, - "input_cost_per_token": 8e-08, - "output_cost_per_token": 2.9e-07, + "input_cost_per_token": 1.2e-07, + "output_cost_per_token": 5e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-32B": { "max_tokens": 40960, "max_input_tokens": 40960, "max_output_tokens": 40960, - "input_cost_per_token": 1e-07, + "input_cost_per_token": 8e-08, "output_cost_per_token": 2.8e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-Coder-480B-A35B-Instruct": { "max_tokens": 262144, @@ -16265,23 +16329,27 @@ "max_tokens": 262144, "max_input_tokens": 262144, "max_output_tokens": 262144, - "input_cost_per_token": 2.9e-07, - "output_cost_per_token": 1.2e-06, + "input_cost_per_token": 3e-07, + "output_cost_per_token": 1e-06, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-Next-80B-A3B-Instruct": { "max_tokens": 262144, "max_input_tokens": 262144, "max_output_tokens": 262144, - "input_cost_per_token": 1.4e-07, - "output_cost_per_token": 1.4e-06, + "input_cost_per_token": 9e-08, + "output_cost_per_token": 1.1e-06, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Qwen/Qwen3-Next-80B-A3B-Thinking": { "max_tokens": 262144, @@ -16308,11 +16376,12 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 6.5e-07, - "output_cost_per_token": 7.5e-07, + "input_cost_per_token": 8.5e-07, + "output_cost_per_token": 8.5e-07, "litellm_provider": "deepinfra", "mode": "chat", - "supports_tool_choice": false + "supports_tool_choice": false, + "source": "https://deepinfra.com/pricing" }, "deepinfra/Sao10K/L3.3-70B-Euryale-v2.3": { "max_tokens": 131072, @@ -16438,36 +16507,41 @@ "max_tokens": 163840, "max_input_tokens": 163840, "max_output_tokens": 163840, - "input_cost_per_token": 3.8e-07, + "input_cost_per_token": 3.2e-07, "output_cost_per_token": 8.9e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/deepseek-ai/DeepSeek-V3-0324": { "max_tokens": 163840, "max_input_tokens": 163840, "max_output_tokens": 163840, - "input_cost_per_token": 2.5e-07, - "output_cost_per_token": 8.8e-07, + "input_cost_per_token": 2.4e-07, + "output_cost_per_token": 9e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "cache_read_input_token_cost": 1.35e-07, + "supports_prompt_caching": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/deepseek-ai/DeepSeek-V3.1": { "max_tokens": 163840, "max_input_tokens": 163840, "max_output_tokens": 163840, - "input_cost_per_token": 2.7e-07, - "output_cost_per_token": 1e-06, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 9.5e-07, "cache_read_input_token_cost": 2.16e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, "supports_reasoning": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/deepseek-ai/DeepSeek-V3.1-Terminus": { "max_tokens": 163840, @@ -16521,33 +16595,36 @@ "max_input_tokens": 131072, "max_output_tokens": 131072, "input_cost_per_token": 5e-08, - "output_cost_per_token": 1e-07, + "output_cost_per_token": 1.5e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/google/gemma-3-27b-it": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 9e-08, + "input_cost_per_token": 8e-08, "output_cost_per_token": 1.6e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/google/gemma-3-4b-it": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 4e-08, - "output_cost_per_token": 8e-08, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 1e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-3.2-11B-Vision-Instruct": { "max_tokens": 131072, @@ -16585,34 +16662,37 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 1.3e-07, - "output_cost_per_token": 3.9e-07, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 3.2e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_function_calling": true, - "supports_tool_choice": true + "supports_tool_choice": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8": { "max_tokens": 1048576, "max_input_tokens": 1048576, "max_output_tokens": 1048576, - "input_cost_per_token": 1.5e-07, - "output_cost_per_token": 6e-07, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 8e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-4-Scout-17B-16E-Instruct": { "max_tokens": 327680, "max_input_tokens": 327680, "max_output_tokens": 327680, - "input_cost_per_token": 8e-08, + "input_cost_per_token": 1e-07, "output_cost_per_token": 3e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Llama-Guard-3-8B": { "max_tokens": 131072, @@ -16660,12 +16740,13 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 1e-07, - "output_cost_per_token": 2.8e-07, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/meta-llama/Meta-Llama-3.1-8B-Instruct": { "max_tokens": 131072, @@ -16683,11 +16764,12 @@ "max_input_tokens": 131072, "max_output_tokens": 131072, "input_cost_per_token": 2e-08, - "output_cost_per_token": 3e-08, + "output_cost_per_token": 4e-08, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/microsoft/WizardLM-2-8x22B": { "max_tokens": 65536, @@ -16714,12 +16796,13 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 2e-08, - "output_cost_per_token": 4e-08, + "input_cost_per_token": 1.9e-08, + "output_cost_per_token": 3e-08, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/mistralai/Mistral-Small-24B-Instruct-2501": { "max_tokens": 32768, @@ -16801,14 +16884,16 @@ }, "deepinfra/nvidia/NVIDIA-Nemotron-3.5-Lightning": { "max_input_tokens": 262144, - "input_cost_per_token": 5e-08, + "input_cost_per_token": 8e-08, "output_cost_per_token": 2e-07, "litellm_provider": "deepinfra", "mode": "chat", - "source": "https://deepinfra.com/nvidia/NVIDIA-Nemotron-3.5-Lightning", + "source": "https://deepinfra.com/pricing", "supports_tool_choice": true, "supports_function_calling": true, - "supports_reasoning": true + "supports_reasoning": true, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true }, "deepinfra/nvidia/NVIDIA-Nemotron-Nano-9B-v2": { "max_tokens": 131072, @@ -16825,23 +16910,25 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 5e-08, - "output_cost_per_token": 4.5e-07, + "input_cost_per_token": 3.7e-08, + "output_cost_per_token": 1.7e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/openai/gpt-oss-20b": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 4e-08, - "output_cost_per_token": 1.5e-07, + "input_cost_per_token": 3e-08, + "output_cost_per_token": 1.4e-07, "litellm_provider": "deepinfra", "mode": "chat", "supports_tool_choice": true, - "supports_function_calling": true + "supports_function_calling": true, + "source": "https://deepinfra.com/pricing" }, "deepinfra/zai-org/GLM-4.5": { "max_tokens": 131072, @@ -18636,6 +18723,22 @@ "supports_tool_choice": true, "supports_vision": false }, + "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813": { + "cache_read_input_token_cost": 4.4e-08, + "input_cost_per_token": 1.32e-06, + "litellm_provider": "fireworks_ai", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 3.96e-06, + "source": "https://docs.fireworks.ai/serverless/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, "fireworks_ai/accounts/fireworks/models/firefunction-v2": { "input_cost_per_token": 9e-07, "litellm_provider": "fireworks_ai", @@ -20342,7 +20445,7 @@ "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -20522,7 +20625,7 @@ "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, - "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-preview", + "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22114,7 +22217,7 @@ "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, "rpm": 15, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22162,7 +22265,7 @@ "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, "rpm": 15, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22209,7 +22312,7 @@ "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, "rpm": 15, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -22257,7 +22360,7 @@ "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, "rpm": 15, - "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-lite", + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -30839,6 +30942,152 @@ "supports_response_schema": true, "supports_tool_choice": true }, + "mistral/ministral-14b-2512": { + "input_cost_per_token": 2e-07, + "litellm_provider": "mistral", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 2e-07, + "source": "https://docs.mistral.ai/models/ministral-3-14b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/ministral-14b-latest": { + "input_cost_per_token": 2e-07, + "litellm_provider": "mistral", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 2e-07, + "source": "https://docs.mistral.ai/models/ministral-3-14b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/ministral-3b-2512": { + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 131072, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1e-07, + "source": "https://docs.mistral.ai/models/ministral-3-3b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/ministral-3b-latest": { + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 131072, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1e-07, + "source": "https://docs.mistral.ai/models/ministral-3-3b-25-12", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/mistral-embed-2312": { + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 8192, + "max_tokens": 8192, + "mode": "embedding", + "source": "https://docs.mistral.ai/models/mistral-embed-23-12" + }, + "mistral/mistral-medium-3": { + "input_cost_per_token": 1.5e-06, + "litellm_provider": "mistral", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 7.5e-06, + "source": "https://docs.mistral.ai/models/model-cards/mistral-medium-3-5-26-04", + "supports_assistant_prefill": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "mistral/voxtral-mini-transcribe-realtime-latest": { + "input_cost_per_second": 0.0001, + "litellm_provider": "mistral", + "mode": "audio_transcription", + "source": "https://docs.mistral.ai/models/model-cards/voxtral-mini-transcribe-realtime-26-02", + "supported_endpoints": [ + "/v1/audio/transcriptions" + ], + "supported_modalities": [ + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true + }, + "mistral/voxtral-mini-tts-latest": { + "litellm_provider": "mistral", + "mode": "audio_speech", + "output_cost_per_character": 1.6e-05, + "source": "https://docs.mistral.ai/models/model-cards/voxtral-tts-26-03", + "supported_endpoints": [ + "/v1/audio/speech" + ], + "supported_modalities": [ + "text" + ], + "supported_output_modalities": [ + "audio" + ], + "supports_audio_output": true + }, + "mistral/voxtral-small-2507": { + "input_cost_per_second": 6.666666666666667e-05, + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 32768, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 4e-07, + "source": "https://docs.mistral.ai/models/voxtral-small-25-07", + "supports_audio_input": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true + }, + "mistral/voxtral-small-latest": { + "input_cost_per_second": 6.666666666666667e-05, + "input_cost_per_token": 1e-07, + "litellm_provider": "mistral", + "max_input_tokens": 32768, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 4e-07, + "source": "https://docs.mistral.ai/models/voxtral-small-25-07", + "supports_audio_input": true, + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true + }, "mistral/zai-glm-5-2": { "cache_read_input_token_cost": 1.4e-07, "input_cost_per_token": 1.4e-06, @@ -38137,7 +38386,7 @@ "max_output_tokens": 20480, "max_tokens": 20480, "metadata": { - "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro" + "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813" }, "mode": "chat", "output_cost_per_token": 7e-06, @@ -38166,7 +38415,7 @@ "max_output_tokens": 8192, "max_tokens": 8192, "metadata": { - "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro" + "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813" }, "mode": "chat", "output_cost_per_token": 1.25e-06, @@ -38181,7 +38430,7 @@ "litellm_provider": "together_ai", "max_tokens": 16384, "metadata": { - "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro" + "successor": "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813" }, "mode": "chat", "output_cost_per_token": 1.7e-06, @@ -38472,6 +38721,7 @@ "supports_tool_choice": true }, "together_ai/Qwen/Qwen3.5-397B-A17B": { + "cache_read_input_token_cost": 3.5e-07, "deprecation_date": "2026-06-29", "input_cost_per_token": 6e-07, "litellm_provider": "together_ai", @@ -38481,10 +38731,12 @@ "source": "https://www.together.ai/models/Qwen/Qwen3.5-397B-A17B", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/MiniMaxAI/MiniMax-M3": { + "cache_read_input_token_cost": 6e-08, "input_cost_per_token": 3e-07, "litellm_provider": "together_ai", "max_input_tokens": 524288, @@ -38495,6 +38747,7 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, @@ -38538,6 +38791,7 @@ "supports_reasoning": true }, "together_ai/Qwen/Qwen3.7-Max": { + "cache_read_input_token_cost": 1.3e-07, "input_cost_per_token": 1.25e-06, "litellm_provider": "together_ai", "max_input_tokens": 1000000, @@ -38545,7 +38799,8 @@ "max_tokens": 1000000, "mode": "chat", "output_cost_per_token": 3.75e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/Qwen/Qwen3.7-Plus": { "input_cost_per_token": 3.2e-07, @@ -38558,6 +38813,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/Qwen/Qwen3.8-2.4T-A95B": { + "cache_read_input_token_cost": 5e-07, "input_cost_per_token": 2.5e-06, "litellm_provider": "together_ai", "max_input_tokens": 1010000, @@ -38565,7 +38821,8 @@ "max_tokens": 1010000, "mode": "chat", "output_cost_per_token": 6.25e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/arize-ai/qwen-2-1.5b-instruct": { "input_cost_per_token": 1e-07, @@ -38578,6 +38835,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/deepseek-ai/DeepSeek-V4-Flash-0731": { + "cache_read_input_token_cost": 3e-08, "input_cost_per_token": 1.4e-07, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38588,10 +38846,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/deepseek-ai/DeepSeek-V4-Pro": { + "deprecation_date": "2026-08-27", + "cache_read_input_token_cost": 2e-07, "input_cost_per_token": 1.74e-06, "litellm_provider": "together_ai", "max_input_tokens": 512000, @@ -38602,11 +38863,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813": { + "cache_read_input_token_cost": 1.3e-07, "input_cost_per_token": 1.32e-06, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38617,10 +38880,12 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/google/gemma-3n-E4B-it": { + "deprecation_date": "2026-08-25", "input_cost_per_token": 6e-08, "litellm_provider": "together_ai", "max_input_tokens": 32768, @@ -38656,6 +38921,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/meta-llama/Llama-Guard-4-12B": { + "deprecation_date": "2026-08-25", "input_cost_per_token": 2e-07, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38666,6 +38932,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/meta-models/Muse-Glimmer-30B": { + "cache_read_input_token_cost": 4e-08, "input_cost_per_token": 3.5e-07, "litellm_provider": "together_ai", "max_input_tokens": 131072, @@ -38673,9 +38940,12 @@ "max_tokens": 131072, "mode": "chat", "output_cost_per_token": 1.5e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/moonshotai/Kimi-K2.7-Code": { + "deprecation_date": "2026-08-27", + "cache_read_input_token_cost": 1.9e-07, "input_cost_per_token": 9.5e-07, "litellm_provider": "together_ai", "max_input_tokens": 262144, @@ -38686,11 +38956,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true }, "together_ai/moonshotai/Kimi-K3": { + "cache_read_input_token_cost": 3e-07, "input_cost_per_token": 3e-06, "litellm_provider": "together_ai", "max_input_tokens": 1048576, @@ -38701,12 +38973,15 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true }, "together_ai/nvidia/nemotron-3-ultra-550b-a55b": { + "deprecation_date": "2026-08-27", + "cache_read_input_token_cost": 2e-07, "input_cost_per_token": 6e-07, "litellm_provider": "together_ai", "max_input_tokens": 512288, @@ -38717,11 +38992,13 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/pearl-ai/gemma-4-31b-it": { + "deprecation_date": "2026-08-27", "input_cost_per_token": 2.8e-07, "litellm_provider": "together_ai", "max_input_tokens": 262144, @@ -38732,6 +39009,7 @@ "source": "https://docs.together.ai/docs/serverless-models" }, "together_ai/thinkingmachines/Inkling": { + "cache_read_input_token_cost": 1.7e-07, "input_cost_per_token": 1e-06, "litellm_provider": "together_ai", "max_input_tokens": 524288, @@ -38742,10 +39020,12 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true }, "together_ai/thinkingmachines/Inkling-Small": { + "cache_read_input_token_cost": 1e-07, "input_cost_per_token": 5e-07, "litellm_provider": "together_ai", "max_input_tokens": 524288, @@ -38753,9 +39033,11 @@ "max_tokens": 524288, "mode": "chat", "output_cost_per_token": 1.2e-06, - "source": "https://docs.together.ai/docs/serverless-models" + "source": "https://docs.together.ai/docs/serverless-models", + "supports_prompt_caching": true }, "together_ai/zai-org/GLM-5.2": { + "cache_read_input_token_cost": 2.6e-07, "input_cost_per_token": 1.4e-06, "litellm_provider": "together_ai", "max_input_tokens": 1048575, @@ -38766,6 +39048,7 @@ "source": "https://docs.together.ai/docs/serverless-models", "supports_function_calling": true, "supports_parallel_function_calling": true, + "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true @@ -43061,19 +43344,21 @@ "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 0.015, - "output_cost_per_token": 0.06, + "input_cost_per_token": 3e-08, + "output_cost_per_token": 1.7e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/openai/gpt-oss-20b": { "max_tokens": 131072, "max_input_tokens": 131072, "max_output_tokens": 131072, - "input_cost_per_token": 0.005, - "output_cost_per_token": 0.02, + "input_cost_per_token": 3e-08, + "output_cost_per_token": 1.3e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/zai-org/GLM-4.5": { "max_tokens": 131072, @@ -43097,10 +43382,11 @@ "max_tokens": 262144, "max_input_tokens": 262144, "max_output_tokens": 262144, - "input_cost_per_token": 0.1, - "output_cost_per_token": 0.15, + "input_cost_per_token": 1e-06, + "output_cost_per_token": 1.5e-06, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/Qwen/Qwen3-235B-A22B-Thinking-2507": { "max_tokens": 262144, @@ -43152,19 +43438,21 @@ "max_tokens": 128000, "max_input_tokens": 128000, "max_output_tokens": 128000, - "input_cost_per_token": 0.022, - "output_cost_per_token": 0.022, + "input_cost_per_token": 2.2e-07, + "output_cost_per_token": 2.2e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/deepseek-ai/DeepSeek-V3.1": { "max_tokens": 128000, - "max_input_tokens": 128000, + "max_input_tokens": 161000, "max_output_tokens": 128000, - "input_cost_per_token": 0.055, - "output_cost_per_token": 0.165, + "input_cost_per_token": 5.5e-07, + "output_cost_per_token": 1.65e-06, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/deepseek-ai/DeepSeek-R1-0528": { "max_tokens": 161000, @@ -43188,10 +43476,11 @@ "max_tokens": 128000, "max_input_tokens": 128000, "max_output_tokens": 128000, - "input_cost_per_token": 0.071, - "output_cost_per_token": 0.071, + "input_cost_per_token": 7.1e-07, + "output_cost_per_token": 7.1e-07, "litellm_provider": "wandb", - "mode": "chat" + "mode": "chat", + "source": "https://wandb.ai/site/pricing/tokens/" }, "wandb/meta-llama/Llama-4-Scout-17B-16E-Instruct": { "max_tokens": 64000, @@ -43577,85 +43866,6 @@ "/v1/audio/transcriptions" ] }, - "xai/grok-2": { - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_web_search": true - }, - "xai/grok-2-1212": { - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_web_search": true - }, - "xai/grok-2-latest": { - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_web_search": true - }, - "xai/grok-2-vision": { - "input_cost_per_image": 2e-06, - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 32768, - "max_output_tokens": 32768, - "max_tokens": 32768, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, - "xai/grok-2-vision-1212": { - "deprecation_date": "2026-02-28", - "input_cost_per_image": 2e-06, - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 32768, - "max_output_tokens": 32768, - "max_tokens": 32768, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, - "xai/grok-2-vision-latest": { - "input_cost_per_image": 2e-06, - "input_cost_per_token": 2e-06, - "litellm_provider": "xai", - "max_input_tokens": 32768, - "max_output_tokens": 32768, - "max_tokens": 32768, - "mode": "chat", - "output_cost_per_token": 1e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, "xai/grok-3": { "cache_read_input_token_cost": 7.5e-07, "input_cost_per_token": 3e-06, @@ -44041,7 +44251,7 @@ "max_input_tokens": 1000000, "max_output_tokens": 1000000, "max_tokens": 1000000, - "mode": "chat", + "mode": "responses", "output_cost_per_token": 2.5e-06, "source": "https://docs.x.ai/docs/models", "supports_function_calling": true, @@ -44053,7 +44263,10 @@ "input_cost_per_token_above_200k_tokens": 2.5e-06, "output_cost_per_token_above_200k_tokens": 5e-06, "cache_read_input_token_cost_above_200k_tokens": 4e-07, - "supports_response_schema": true + "supports_response_schema": true, + "supported_endpoints": [ + "/v1/responses" + ] }, "xai/grok-4.20-beta-0309-reasoning": { "cache_read_input_token_cost": 2e-07, @@ -44222,19 +44435,6 @@ "supports_vision": true, "supports_web_search": true }, - "xai/grok-beta": { - "input_cost_per_token": 5e-06, - "litellm_provider": "xai", - "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, - "mode": "chat", - "output_cost_per_token": 1.5e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, "xai/grok-code-fast": { "cache_read_input_token_cost": 2e-07, "input_cost_per_token": 1e-06, @@ -44298,20 +44498,6 @@ "supports_vision": true, "deprecation_date": "2026-05-15" }, - "xai/grok-vision-beta": { - "input_cost_per_image": 5e-06, - "input_cost_per_token": 5e-06, - "litellm_provider": "xai", - "max_input_tokens": 8192, - "max_output_tokens": 8192, - "max_tokens": 8192, - "mode": "chat", - "output_cost_per_token": 1.5e-05, - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_vision": true, - "supports_web_search": true - }, "zai.glm-4.7": { "input_cost_per_token": 6e-07, "litellm_provider": "bedrock_converse", @@ -44370,6 +44556,21 @@ "supports_tool_choice": true, "source": "https://docs.z.ai/guides/overview/pricing" }, + "zai/glm-5.3": { + "cache_creation_input_token_cost": 0, + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.4e-06, + "litellm_provider": "zai", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://docs.z.ai/guides/overview/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true + }, "zai/glm-5.1": { "cache_creation_input_token_cost": 0, "cache_read_input_token_cost": 2.6e-07, @@ -44575,6 +44776,7 @@ ] }, "azure/sora-2": { + "deprecation_date": "2026-10-15", "litellm_provider": "azure", "mode": "video_generation", "output_cost_per_video_per_second": 0.1, @@ -47158,8 +47360,8 @@ "novita/xiaomimimo/mimo-v2-flash": { "litellm_provider": "novita", "mode": "chat", - "input_cost_per_token": 1e-07, - "output_cost_per_token": 3e-07, + "input_cost_per_token": 1.1e-07, + "output_cost_per_token": 3.3e-07, "max_input_tokens": 262144, "max_output_tokens": 32000, "max_tokens": 32000, @@ -47168,8 +47370,8 @@ "supports_tool_choice": true, "supports_system_messages": true, "supports_response_schema": true, - "cache_read_input_token_cost": 2e-08, - "input_cost_per_token_cache_hit": 2e-08, + "cache_read_input_token_cost": 2.4e-08, + "input_cost_per_token_cache_hit": 2.4e-08, "supports_reasoning": true }, "novita/zai-org/autoglm-phone-9b-multilingual": { @@ -47189,14 +47391,16 @@ "input_cost_per_token": 6e-07, "output_cost_per_token": 2.5e-06, "max_input_tokens": 262144, - "max_output_tokens": 262144, - "max_tokens": 262144, + "max_output_tokens": 100352, + "max_tokens": 100352, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, "supports_response_schema": true, - "supports_reasoning": true + "supports_reasoning": true, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true }, "novita/minimax/minimax-m2": { "litellm_provider": "novita", @@ -47212,7 +47416,8 @@ "supports_system_messages": true, "cache_read_input_token_cost": 3e-08, "input_cost_per_token_cache_hit": 3e-08, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/paddlepaddle/paddleocr-vl": { "litellm_provider": "novita", @@ -47250,7 +47455,9 @@ "max_tokens": 32768, "supports_vision": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "novita/zai-org/glm-4.6v": { "litellm_provider": "novita", @@ -47315,7 +47522,8 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_response_schema": true + "supports_response_schema": true, + "supports_reasoning": true }, "novita/qwen/qwen3-next-80b-a3b-thinking": { "litellm_provider": "novita", @@ -47427,8 +47635,8 @@ "input_cost_per_token": 6e-07, "output_cost_per_token": 2.5e-06, "max_input_tokens": 262144, - "max_output_tokens": 262144, - "max_tokens": 262144, + "max_output_tokens": 100352, + "max_tokens": 100352, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -47438,8 +47646,8 @@ "novita/qwen/qwen3-coder-480b-a35b-instruct": { "litellm_provider": "novita", "mode": "chat", - "input_cost_per_token": 3e-07, - "output_cost_per_token": 1.3e-06, + "input_cost_per_token": 3.8e-07, + "output_cost_per_token": 1.55e-06, "max_input_tokens": 262144, "max_output_tokens": 65536, "max_tokens": 65536, @@ -47485,8 +47693,8 @@ "input_cost_per_token": 5.7e-07, "output_cost_per_token": 2.3e-06, "max_input_tokens": 131072, - "max_output_tokens": 131072, - "max_tokens": 131072, + "max_output_tokens": 100352, + "max_tokens": 100352, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -47499,8 +47707,8 @@ "input_cost_per_token": 2.7e-07, "output_cost_per_token": 1.12e-06, "max_input_tokens": 163840, - "max_output_tokens": 163840, - "max_tokens": 163840, + "max_output_tokens": 65536, + "max_tokens": 65536, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -47547,7 +47755,8 @@ "max_input_tokens": 16384, "max_output_tokens": 16384, "max_tokens": 16384, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/google/gemma-3-12b-it": { "litellm_provider": "novita", @@ -47626,13 +47835,14 @@ "mode": "chat", "input_cost_per_token": 1.35e-07, "output_cost_per_token": 4e-07, - "max_input_tokens": 131072, - "max_output_tokens": 120000, - "max_tokens": 120000, + "max_input_tokens": 12288, + "max_output_tokens": 12288, + "max_tokens": 12288, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/qwen/qwen-2.5-72b-instruct": { "litellm_provider": "novita", @@ -47672,7 +47882,8 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/deepseek/deepseek-r1-0528": { "litellm_provider": "novita", @@ -47712,7 +47923,8 @@ "max_input_tokens": 8192, "max_output_tokens": 8192, "max_tokens": 8192, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/microsoft/wizardlm-2-8x22b": { "litellm_provider": "novita", @@ -47722,7 +47934,8 @@ "max_input_tokens": 65535, "max_output_tokens": 8000, "max_tokens": 8000, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/deepseek/deepseek-r1-0528-qwen3-8b": { "litellm_provider": "novita", @@ -47769,7 +47982,8 @@ "max_output_tokens": 20000, "max_tokens": 20000, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/meta-llama/llama-4-maverick-17b-128e-instruct-fp8": { "litellm_provider": "novita", @@ -47780,7 +47994,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "supports_vision": true, - "supports_system_messages": true + "supports_system_messages": true, + "supports_response_schema": true }, "novita/meta-llama/llama-4-scout-17b-16e-instruct": { "litellm_provider": "novita", @@ -47916,7 +48131,9 @@ "max_output_tokens": 20000, "max_tokens": 20000, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "novita/google/gemma-3-27b-it": { "litellm_provider": "novita", @@ -47954,7 +48171,8 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_response_schema": true }, "novita/Sao10K/L3-8B-Stheno-v3.2": { "litellm_provider": "novita", @@ -48022,7 +48240,9 @@ "supports_parallel_function_calling": true, "supports_tool_choice": true, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "cache_read_input_token_cost": 2.5e-08, + "supports_prompt_caching": true }, "novita/qwen/qwen3-vl-30b-a3b-instruct": { "litellm_provider": "novita", @@ -48143,10 +48363,12 @@ "input_cost_per_token": 3e-08, "output_cost_per_token": 3e-08, "max_input_tokens": 128000, - "max_output_tokens": 20000, - "max_tokens": 20000, + "max_output_tokens": 8192, + "max_tokens": 8192, "supports_system_messages": true, - "supports_reasoning": true + "supports_reasoning": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "novita/qwen/qwen2.5-7b-instruct": { "litellm_provider": "novita", @@ -48154,8 +48376,8 @@ "input_cost_per_token": 7e-08, "output_cost_per_token": 7e-08, "max_input_tokens": 32000, - "max_output_tokens": 32000, - "max_tokens": 32000, + "max_output_tokens": 8192, + "max_tokens": 8192, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_tool_choice": true, @@ -49567,14 +49789,14 @@ "supports_tool_choice": true }, "bedrock_mantle/openai.gpt-5.6-sol": { - "input_cost_per_token": 5.5e-06, - "input_cost_per_token_above_272k_tokens": 1.1e-05, - "cache_creation_input_token_cost": 6.875e-06, - "cache_creation_input_token_cost_above_272k_tokens": 1.375e-05, - "cache_read_input_token_cost": 5.5e-07, - "cache_read_input_token_cost_above_272k_tokens": 1.1e-06, - "output_cost_per_token": 3.3e-05, - "output_cost_per_token_above_272k_tokens": 4.95e-05, + "input_cost_per_token": 4.4e-06, + "input_cost_per_token_above_272k_tokens": 8.8e-06, + "cache_creation_input_token_cost": 5.5e-06, + "cache_creation_input_token_cost_above_272k_tokens": 1.1e-05, + "cache_read_input_token_cost": 4.4e-07, + "cache_read_input_token_cost_above_272k_tokens": 8.8e-07, + "output_cost_per_token": 2.2e-05, + "output_cost_per_token_above_272k_tokens": 3.3e-05, "litellm_provider": "bedrock_mantle", "max_input_tokens": 1050000, "max_output_tokens": 128000, @@ -49632,6 +49854,34 @@ "supports_tool_choice": true, "supports_vision": true }, + "bedrock_mantle/openai.gpt-5.6-cyber": { + "input_cost_per_token": 1.375e-05, + "cache_creation_input_token_cost": 1.71875e-05, + "cache_read_input_token_cost": 1.375e-06, + "output_cost_per_token": 8.25e-05, + "litellm_provider": "bedrock_mantle", + "max_input_tokens": 272000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "responses", + "use_openai_responses_path": true, + "supported_endpoints": [ + "/v1/responses" + ], + "supported_modalities": [ + "text", + "image" + ], + "supported_output_modalities": [ + "text" + ], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, "bedrock_mantle/openai.gpt-5.6-luna": { "input_cost_per_token": 2.2e-07, "input_cost_per_token_above_272k_tokens": 4.4e-07, @@ -49666,14 +49916,14 @@ "supports_vision": true }, "us.openai.gpt-5.6-sol": { - "input_cost_per_token": 5.5e-06, - "input_cost_per_token_above_272k_tokens": 1.1e-05, - "cache_creation_input_token_cost": 6.875e-06, - "cache_creation_input_token_cost_above_272k_tokens": 1.375e-05, - "cache_read_input_token_cost": 5.5e-07, - "cache_read_input_token_cost_above_272k_tokens": 1.1e-06, - "output_cost_per_token": 3.3e-05, - "output_cost_per_token_above_272k_tokens": 4.95e-05, + "input_cost_per_token": 4.4e-06, + "input_cost_per_token_above_272k_tokens": 8.8e-06, + "cache_creation_input_token_cost": 5.5e-06, + "cache_creation_input_token_cost_above_272k_tokens": 1.1e-05, + "cache_read_input_token_cost": 4.4e-07, + "cache_read_input_token_cost_above_272k_tokens": 8.8e-07, + "output_cost_per_token": 2.2e-05, + "output_cost_per_token_above_272k_tokens": 3.3e-05, "litellm_provider": "bedrock_converse", "max_input_tokens": 1000000, "max_output_tokens": 128000, @@ -49692,14 +49942,14 @@ "supports_vision": true }, "global.openai.gpt-5.6-sol": { - "input_cost_per_token": 5e-06, - "input_cost_per_token_above_272k_tokens": 1e-05, - "cache_creation_input_token_cost": 6.25e-06, - "cache_creation_input_token_cost_above_272k_tokens": 1.25e-05, - "cache_read_input_token_cost": 5e-07, - "cache_read_input_token_cost_above_272k_tokens": 1e-06, - "output_cost_per_token": 3e-05, - "output_cost_per_token_above_272k_tokens": 4.5e-05, + "input_cost_per_token": 4e-06, + "input_cost_per_token_above_272k_tokens": 8e-06, + "cache_creation_input_token_cost": 5e-06, + "cache_creation_input_token_cost_above_272k_tokens": 1e-05, + "cache_read_input_token_cost": 4e-07, + "cache_read_input_token_cost_above_272k_tokens": 8e-07, + "output_cost_per_token": 2e-05, + "output_cost_per_token_above_272k_tokens": 3e-05, "litellm_provider": "bedrock_converse", "max_input_tokens": 1000000, "max_output_tokens": 128000, @@ -50981,7 +51231,7 @@ "max_input_tokens": 1000000, "max_output_tokens": 1000000, "max_tokens": 1000000, - "mode": "chat", + "mode": "responses", "output_cost_per_token": 2.5e-06, "source": "https://docs.x.ai/docs/models", "supports_function_calling": true, @@ -50993,7 +51243,10 @@ "input_cost_per_token_above_200k_tokens": 2.5e-06, "output_cost_per_token_above_200k_tokens": 5e-06, "cache_read_input_token_cost_above_200k_tokens": 4e-07, - "supports_response_schema": true + "supports_response_schema": true, + "supported_endpoints": [ + "/v1/responses" + ] }, "xai/grok-build-0.1": { "cache_read_input_token_cost": 2e-07, @@ -51357,6 +51610,47 @@ "supports_audio_output": true, "tpm": 250000 }, + "gemini/gemini-3.5-transcribe": { + "input_cost_per_audio_token": 2e-06, + "input_cost_per_token": 2e-06, + "litellm_provider": "gemini", + "mode": "audio_transcription", + "output_cost_per_token": 1.2e-05, + "source": "https://ai.google.dev/gemini-api/docs/pricing", + "supported_endpoints": [ + "/v1/audio/transcriptions" + ], + "supported_modalities": [ + "text", + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true, + "tpm": 800000, + "rpm": 2000 + }, + "gemini/gemini-3.5-transcribe-live": { + "input_cost_per_audio_token": 3.5e-06, + "input_cost_per_token": 3.5e-06, + "litellm_provider": "gemini", + "mode": "audio_transcription", + "output_cost_per_token": 2.1e-05, + "source": "https://ai.google.dev/gemini-api/docs/pricing", + "supported_endpoints": [ + "/v1/realtime" + ], + "supported_modalities": [ + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true, + "tpm": 250000, + "rpm": 10 + }, "perplexity/pplx-embed-context-v1-0.6b": { "input_cost_per_token": 8e-09, "litellm_provider": "perplexity", @@ -51439,14 +51733,14 @@ "supports_embedding_image_input": true }, "fireworks_ai/accounts/fireworks/models/deepseek-v4-flash-0731": { - "cache_read_input_token_cost": 2.8e-08, - "input_cost_per_token": 1.4e-07, + "cache_read_input_token_cost": 7e-09, + "input_cost_per_token": 2.2e-07, "litellm_provider": "fireworks_ai", "max_input_tokens": 1048576, "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 2.8e-07, + "output_cost_per_token": 6.6e-07, "source": "https://docs.fireworks.ai/serverless/pricing", "supports_function_calling": true, "supports_reasoning": true, @@ -51753,5 +52047,2034 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true + }, + "novita/zai-org/glm-5.3": { + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.4e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-v4-pro-0813": { + "cache_read_input_token_cost": 1.3200000000000002e-07, + "input_cost_per_token": 1.32e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 3.96e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/moonshotai/kimi-k3": { + "cache_read_input_token_cost": 3e-07, + "input_cost_per_token": 3e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 1048576, + "max_tokens": 1048576, + "mode": "chat", + "output_cost_per_token": 1.5e-05, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/tencent/hy3": { + "cache_read_input_token_cost": 3.5e-08, + "input_cost_per_token": 1.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 5.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-5.2": { + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.4e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/moonshotai/kimi-k2.7-code": { + "cache_read_input_token_cost": 1.9e-07, + "input_cost_per_token": 9.499999999999999e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek-v4-flash-vision-exp": { + "cache_read_input_token_cost": 2.8e-08, + "input_cost_per_token": 4.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 1.32e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek-v4-flash-0731": { + "cache_read_input_token_cost": 2.8e-08, + "input_cost_per_token": 4.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 1.32e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/mindai/macaron-v1-venti": { + "cache_read_input_token_cost": 3e-07, + "input_cost_per_token": 1.5e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.5e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m3": { + "cache_read_input_token_cost": 6e-08, + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 1000000, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1.2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek-v4-flash": { + "cache_read_input_token_cost": 2.8e-08, + "input_cost_per_token": 1.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 2.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-v4-pro": { + "cache_read_input_token_cost": 1.35e-07, + "input_cost_per_token": 1.6000000000000001e-06, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 393216, + "max_tokens": 393216, + "mode": "chat", + "output_cost_per_token": 3.2000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/inclusionai/ling-3.0-flash-fast": { + "cache_read_input_token_cost": 1.2e-08, + "input_cost_per_token": 6e-08, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 1.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.8-max": { + "cache_read_input_token_cost": 2.5e-07, + "input_cost_per_token": 2e-06, + "litellm_provider": "novita", + "max_input_tokens": 1000000, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 6e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/inclusionai/ling-3.0-flash": { + "cache_read_input_token_cost": 1.2e-08, + "input_cost_per_token": 6e-08, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 1.8e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/mindai/macaron-v1-tall": { + "cache_read_input_token_cost": 8e-08, + "input_cost_per_token": 4.5000000000000003e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 2.6e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/stepfun/step-3.7-flash": { + "cache_read_input_token_cost": 4e-08, + "input_cost_per_token": 2.0000000000000002e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 256000, + "max_tokens": 256000, + "mode": "chat", + "output_cost_per_token": 1.15e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/nvidia/nemotron-3-nano-30b-a3b": { + "input_cost_per_token": 5.0000000000000004e-08, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "chat", + "output_cost_per_token": 2.0000000000000002e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/baidu/cobuddy": { + "cache_read_input_token_cost": 7e-08, + "input_cost_per_token": 2.8e-07, + "litellm_provider": "novita", + "max_input_tokens": 131072, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 1.13e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/xiaomimimo/mimo-v2.5": { + "cache_read_input_token_cost": 3.4e-09, + "input_cost_per_token": 1.6800000000000002e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 3.3600000000000004e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.7-max": { + "cache_read_input_token_cost": 2.5e-07, + "input_cost_per_token": 1.25e-06, + "litellm_provider": "novita", + "max_input_tokens": 1000000, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.75e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/xiaomimimo/mimo-v2.5-pro": { + "cache_read_input_token_cost": 4.3e-09, + "input_cost_per_token": 5.22e-07, + "litellm_provider": "novita", + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1.044e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.6-27b": { + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.6000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/moonshotai/kimi-k2.6": { + "cache_read_input_token_cost": 1.6e-07, + "input_cost_per_token": 8.000000000000001e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 3.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/zai-org/glm-5.1": { + "cache_read_input_token_cost": 2.6e-07, + "input_cost_per_token": 1.38e-06, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m2.7-highspeed": { + "cache_read_input_token_cost": 6e-08, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 2.4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-5v-turbo": { + "cache_read_input_token_cost": 2.4e-07, + "input_cost_per_token": 1.2e-06, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/google/gemma-4-26b-a4b-it": { + "input_cost_per_token": 1.3e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.0000000000000003e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/google/gemma-4-31b-it": { + "input_cost_per_token": 1.4e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.0000000000000003e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/zai-org/glm-5-turbo": { + "cache_read_input_token_cost": 2.4e-07, + "input_cost_per_token": 1.2e-06, + "litellm_provider": "novita", + "max_input_tokens": 202800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m2.7": { + "cache_read_input_token_cost": 6e-08, + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 1.2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/minimax/minimax-m2.5-highspeed": { + "cache_read_input_token_cost": 3e-08, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131100, + "max_tokens": 131100, + "mode": "chat", + "output_cost_per_token": 2.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.5-27b": { + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 2.4e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.5-122b-a10b": { + "input_cost_per_token": 4.0000000000000003e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.2000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.5-35b-a3b": { + "input_cost_per_token": 2.5e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/qwen/qwen3.5-397b-a17b": { + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 3.6000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/minimax/minimax-m2.5": { + "cache_read_input_token_cost": 3e-08, + "input_cost_per_token": 3e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131100, + "max_tokens": 131100, + "mode": "chat", + "output_cost_per_token": 1.2e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-5": { + "cache_read_input_token_cost": 2.0000000000000002e-07, + "input_cost_per_token": 1e-06, + "litellm_provider": "novita", + "max_input_tokens": 202800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 3.2000000000000003e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3-coder-next": { + "input_cost_per_token": 2.0000000000000002e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 1.5e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-ocr-2": { + "input_cost_per_token": 3e-08, + "litellm_provider": "novita", + "max_input_tokens": 8192, + "max_output_tokens": 8192, + "max_tokens": 8192, + "mode": "chat", + "output_cost_per_token": 3e-08, + "source": "https://novita.ai/pricing", + "supports_vision": true + }, + "novita/moonshotai/kimi-k2.5": { + "cache_read_input_token_cost": 1.0000000000000001e-07, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 3e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/zai-org/glm-4.7-h": { + "cache_read_input_token_cost": 1.1e-07, + "input_cost_per_token": 6e-07, + "litellm_provider": "novita", + "max_input_tokens": 204800, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 2.2e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/zai-org/glm-4.7-flash": { + "cache_read_input_token_cost": 1e-08, + "input_cost_per_token": 7e-08, + "litellm_provider": "novita", + "max_input_tokens": 200000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 4.0000000000000003e-07, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/qwen/qwen3.6-35b-a3b": { + "input_cost_per_token": 2.48e-07, + "litellm_provider": "novita", + "max_input_tokens": 262144, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 1.4850000000000002e-06, + "source": "https://novita.ai/pricing", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "novita/deepseek/deepseek_v3": { + "input_cost_per_token": 8.900000000000001e-07, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 16000, + "max_tokens": 16000, + "mode": "chat", + "output_cost_per_token": 8.900000000000001e-07, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-r1": { + "input_cost_per_token": 4e-06, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 16000, + "max_tokens": 16000, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-v3/community": { + "input_cost_per_token": 8.900000000000001e-07, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 8000, + "max_tokens": 8000, + "mode": "chat", + "output_cost_per_token": 8.900000000000001e-07, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/deepseek/deepseek-r1/community": { + "input_cost_per_token": 4e-06, + "litellm_provider": "novita", + "max_input_tokens": 64000, + "max_output_tokens": 8000, + "max_tokens": 8000, + "mode": "chat", + "output_cost_per_token": 4e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/thudm/glm-4-32b-0414": { + "input_cost_per_token": 5.5e-07, + "litellm_provider": "novita", + "max_input_tokens": 32000, + "max_output_tokens": 32000, + "max_tokens": 32000, + "mode": "chat", + "output_cost_per_token": 1.66e-06, + "source": "https://api.novita.ai/v3/openai/models", + "supports_function_calling": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": false + }, + "novita/meta-llama/llama-3.2-1b-instruct": { + "input_cost_per_token": 2e-08, + "litellm_provider": "novita", + "max_input_tokens": 131000, + "max_output_tokens": 32000, + "max_tokens": 32000, + "mode": "chat", + "output_cost_per_token": 2e-08, + "source": "https://api.novita.ai/v3/openai/models", + "supports_response_schema": true, + "supports_vision": false + }, + "wandb/deepseek-ai/DeepSeek-V4-Flash": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 2.8e-07, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/deepseek-ai/DeepSeek-V4-Flash-0731": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.3e-07, + "output_cost_per_token": 2.8e-07, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/deepseek-ai/DeepSeek-V4-Pro": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.15e-06, + "output_cost_per_token": 2.55e-06, + "cache_read_input_token_cost": 2e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/google/gemma-4-31B-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 3.4e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/ibm-granite/granite-4.1-8b": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 1e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/JetBrains/Mellum2-12B-A2.5B-Instruct": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 1e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/meta-llama/Llama-3.1-70B-Instruct": { + "max_tokens": 128000, + "max_input_tokens": 128000, + "input_cost_per_token": 8e-07, + "output_cost_per_token": 8e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/MiniMaxAI/MiniMax-M3": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.3e-07, + "output_cost_per_token": 9.6e-07, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/moonshotai/Kimi-K2.7-Code": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.1e-07, + "output_cost_per_token": 3.5e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/moonshotai/Kimi-K2.6": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 6.5e-07, + "output_cost_per_token": 3.41e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 2.5e-07, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 2.75e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/OpenPipe/Qwen3-14B-Instruct": { + "max_tokens": 32768, + "max_input_tokens": 32768, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 2.2e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.8-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.6-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.25e-06, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.6-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 6e-07, + "output_cost_per_token": 3.6e-06, + "cache_read_input_token_cost": 1.2e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3.5-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.25e-06, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": true, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/Qwen/Qwen3-30B-A3B-Instruct-2507": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 3e-07, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "wandb/zai-org/GLM-5.2": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.6e-07, + "output_cost_per_token": 2.42e-06, + "cache_read_input_token_cost": 1.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "wandb", + "mode": "chat", + "supports_vision": false, + "source": "https://wandb.ai/site/pricing/tokens/" + }, + "deepinfra/openai/gpt-oss-120b-Turbo": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 6e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/MiniMaxAI/MiniMax-M2.7": { + "max_tokens": 196608, + "max_input_tokens": 196608, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1e-06, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.8-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-31B-it-Ultra": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2.7e-07, + "output_cost_per_token": 7.6e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K2.5": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4.5e-07, + "output_cost_per_token": 2.25e-06, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-4.7-Flash": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 6e-08, + "output_cost_per_token": 4e-07, + "cache_read_input_token_cost": 1e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-4.6": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 2e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-opus-4-8": { + "input_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "prompt_cache_min_tokens": 1024, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/anthropic/claude-sonnet-4-6": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 3e-06, + "output_cost_per_token": 1.5e-05, + "litellm_provider": "deepinfra", + "mode": "chat", + "prompt_cache_min_tokens": 1024, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_adaptive_thinking": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.5-flash": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 1.5e-06, + "output_cost_per_token": 9e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/XiaomiMiMo/MiMo-V2.5": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 2e-06, + "cache_read_input_token_cost": 8e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-Max": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1.2e-06, + "output_cost_per_token": 6e-06, + "cache_read_input_token_cost": 2.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-31B-it-turbo": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 9e-08, + "output_cost_per_token": 3.4e-07, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/thinkingmachines/Inkling-Small": { + "max_tokens": 524288, + "max_input_tokens": 524288, + "input_cost_per_token": 4.5e-07, + "output_cost_per_token": 1.2e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/meta-models/Muse-Glimmer-30B": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 3e-07, + "output_cost_per_token": 1.2e-06, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-Max-Thinking": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1.2e-06, + "output_cost_per_token": 6e-06, + "cache_read_input_token_cost": 2.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-VL-235B-A22B-Instruct": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 8.8e-07, + "cache_read_input_token_cost": 1.1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3-VL-30B-A3B-Instruct": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 6e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.6e-07, + "output_cost_per_token": 2.6e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.6-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 9.5e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/nvidia/Nemotron-Content-Safety-3.5": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 2e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-opus-5": { + "input_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "prompt_cache_min_tokens": 512, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/thinkingmachines/Inkling": { + "max_tokens": 524288, + "max_input_tokens": 524288, + "input_cost_per_token": 9.5e-07, + "output_cost_per_token": 4.05e-06, + "cache_read_input_token_cost": 1.6e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K2.6": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 3.5e-06, + "cache_read_input_token_cost": 1.5e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Pro-0813": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.3e-06, + "output_cost_per_token": 2.6e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.7-Max": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 2.5e-06, + "output_cost_per_token": 7.5e-06, + "cache_read_input_token_cost": 5e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-2.0-mini": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 4e-07, + "cache_read_input_token_cost": 2e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.8-2.4T-A95B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2e-06, + "output_cost_per_token": 6e-06, + "cache_read_input_token_cost": 2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/MiniMaxAI/MiniMax-M3": { + "max_tokens": 524288, + "max_input_tokens": 524288, + "input_cost_per_token": 2.8e-07, + "output_cost_per_token": 1.1e-06, + "cache_read_input_token_cost": 5.6e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.1-flash-lite": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.5e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.7-flash": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 3.75e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/inclusionAI/Ling-3.0-flash": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 6e-08, + "output_cost_per_token": 1.8e-07, + "cache_read_input_token_cost": 1.2e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/stepfun-ai/Step-3.7-Flash": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 1.15e-06, + "cache_read_input_token_cost": 4e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-35B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 1e-06, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-1.8": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 2e-06, + "cache_read_input_token_cost": 5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/tencent/Hy3": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 5.8e-07, + "cache_read_input_token_cost": 3.5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-2.0-code": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/ByteDance/Seed-2.0-pro": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-5": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 6e-07, + "output_cost_per_token": 2.08e-06, + "cache_read_input_token_cost": 1.2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/nvidia/Nemotron-3-Nano-30B-A3B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 5e-08, + "output_cost_per_token": 2e-07, + "cache_read_input_token_cost": 2.5e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K2.7-Code": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 6.8e-07, + "output_cost_per_token": 3.4e-06, + "cache_read_input_token_cost": 1.36e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-sonnet-5": { + "input_cost_per_token": 2e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 1e-05, + "prompt_cache_min_tokens": 1024, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/Qwen/Qwen3.5-397B-A17B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 4.5e-07, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 2.2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Flash-0731": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 8e-08, + "output_cost_per_token": 1.8e-07, + "cache_read_input_token_cost": 1.6e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-E4B-it": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2e-08, + "output_cost_per_token": 1e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V3.2": { + "max_tokens": 163840, + "max_input_tokens": 163840, + "input_cost_per_token": 2.6e-07, + "output_cost_per_token": 3.8e-07, + "cache_read_input_token_cost": 1.3e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.8-Max": { + "max_tokens": 256000, + "max_input_tokens": 256000, + "input_cost_per_token": 1.65e-06, + "output_cost_per_token": 4.951e-06, + "cache_read_input_token_cost": 2.06e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-fable-5": { + "input_cost_per_token": 1e-05, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 5e-05, + "prompt_cache_min_tokens": 512, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "thinking_always_on": true + }, + "deepinfra/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 5e-07, + "output_cost_per_token": 2.2e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-122B-A10B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 2.9e-07, + "output_cost_per_token": 2.4e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-5.1": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 1.05e-06, + "output_cost_per_token": 3.5e-06, + "cache_read_input_token_cost": 2.05e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Pro": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1.3e-06, + "output_cost_per_token": 2.6e-06, + "cache_read_input_token_cost": 1e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/nvidia/NVIDIA-Nemotron-3-Super-120B-A12B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 8.5e-08, + "output_cost_per_token": 4e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-5.2": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 7.5e-07, + "output_cost_per_token": 2.4e-06, + "cache_read_input_token_cost": 1.4e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/moonshotai/Kimi-K3": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 2.85e-06, + "output_cost_per_token": 1.425e-05, + "cache_read_input_token_cost": 2.85e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-opus-4-7": { + "input_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "max_input_tokens": 1000000, + "max_tokens": 1000000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "prompt_cache_min_tokens": 2048, + "source": "https://deepinfra.com/pricing", + "supports_adaptive_thinking": true, + "supports_function_calling": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true + }, + "deepinfra/Qwen/Qwen3.6-27B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 3.2e-07, + "output_cost_per_token": 3.2e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-26B-A4B-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 7e-08, + "output_cost_per_token": 3.4e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemini-3.1-pro": { + "max_tokens": 1000000, + "max_input_tokens": 1000000, + "input_cost_per_token": 2e-06, + "output_cost_per_token": 1.2e-05, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/XiaomiMiMo/MiMo-V2.5-Pro": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 1e-06, + "output_cost_per_token": 3e-06, + "cache_read_input_token_cost": 2e-07, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/anthropic/claude-haiku-4-5": { + "max_tokens": 200000, + "max_input_tokens": 200000, + "input_cost_per_token": 1e-06, + "output_cost_per_token": 5e-06, + "litellm_provider": "deepinfra", + "mode": "chat", + "prompt_cache_min_tokens": 4096, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/deepseek-ai/DeepSeek-V4-Flash": { + "max_tokens": 1048576, + "max_input_tokens": 1048576, + "input_cost_per_token": 9e-08, + "output_cost_per_token": 1.8e-07, + "cache_read_input_token_cost": 1.8e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/openai/gpt-oss-120b-Ultra": { + "max_tokens": 131072, + "max_input_tokens": 131072, + "input_cost_per_token": 2e-07, + "output_cost_per_token": 9.5e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/Qwen/Qwen3.5-9B": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1e-07, + "output_cost_per_token": 1.5e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/MiniMaxAI/MiniMax-M2.7-Turbo": { + "max_tokens": 196608, + "max_input_tokens": 196608, + "input_cost_per_token": 3.8e-07, + "output_cost_per_token": 1.7e-06, + "cache_read_input_token_cost": 7e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/zai-org/GLM-4.7": { + "max_tokens": 202752, + "max_input_tokens": 202752, + "input_cost_per_token": 4e-07, + "output_cost_per_token": 1.75e-06, + "cache_read_input_token_cost": 8e-08, + "supports_prompt_caching": true, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": false, + "source": "https://deepinfra.com/pricing" + }, + "deepinfra/google/gemma-4-31B-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "input_cost_per_token": 1.3e-07, + "output_cost_per_token": 3.8e-07, + "litellm_provider": "deepinfra", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_reasoning": true, + "supports_vision": true, + "source": "https://deepinfra.com/pricing" } } diff --git a/pyproject.toml b/pyproject.toml index 1c3f5a4875c..eba9e5afc98 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,8 +67,8 @@ proxy = [ "azure-identity>=1.25.2,<2.0", "azure-storage-blob>=12.28.0,<13.0", "mcp>=1.28.1,<2.0", - "litellm-proxy-extras==0.4.89", - "litellm-enterprise==0.1.60", + "litellm-proxy-extras==0.4.90", + "litellm-enterprise==0.1.61", "RestrictedPython>=8.1,<9.0", "rich>=13.9.4,<14.0", "InquirerPy>=0.3.4,<1.0", diff --git a/scripts/pre_commit_lint.sh b/scripts/pre_commit_lint.sh index 0861172056e..ff553be6461 100755 --- a/scripts/pre_commit_lint.sh +++ b/scripts/pre_commit_lint.sh @@ -13,7 +13,7 @@ # - tests/e2e Python -> `make lint-e2e-basedpyright` (test-linting.yml's e2e type-check step) # + raw HTTP client ban (test-code-quality.yml's check_e2e_no_raw_requests) # - dashboard -> prettier + eslint + lint budgets (test-litellm-ui-build.yml's frontend-lint) -# - proxy/types -> regenerate dashboard API types and fail on drift (check-ui-api-types.yml) +# - proxy/types -> regenerate the lazy OpenAPI snapshot and dashboard API types, fail on drift (check-ui-api-types.yml) # # Each block is skipped when no matching files are in scope, so unrelated commits # stay fast. This is intentionally not auto-installed as a git hook (see @@ -244,7 +244,7 @@ fi genapi_checks() { local status=0 - echo "check: checking dashboard API types are in sync (npm run gen:api)" + echo "check: checking the lazy OpenAPI snapshot and dashboard API types are in sync (npm run gen:api)" # gen-api-types.mjs imports litellm.proxy.proxy_server, which needs the proxy deps # and an up-to-date Prisma client; check-ui-api-types.yml installs those and runs # prisma generate before gen:api, so mirror that here or a stale client can mask @@ -260,7 +260,14 @@ genapi_checks() { elif ! uv run --no-sync python scripts/prisma_generate_if_needed.py; then echo "✗ Could not regenerate Prisma client (prisma generate failed)." >&2 status=1 + elif ! uv run --no-sync python -m litellm.proxy._lazy_openapi_snapshot; then + echo "✗ Could not regenerate the lazy OpenAPI snapshot (python -m litellm.proxy._lazy_openapi_snapshot failed)." >&2 + status=1 elif ( cd ui/litellm-dashboard && LITELLM_PYTHON="uv run --no-sync python" npm run gen:api ); then + if ! git diff --quiet -- litellm/proxy/_lazy_openapi_snapshot.json; then + echo "✗ The lazy OpenAPI snapshot is stale; regenerated litellm/proxy/_lazy_openapi_snapshot.json. Stage it and commit; re-run make check only if other checks failed too." >&2 + status=1 + fi if ! git diff --quiet -- ui/litellm-dashboard/src/lib/http/schema.d.ts; then echo "✗ Dashboard API types are stale; regenerated src/lib/http/schema.d.ts. Stage it and commit; re-run make check only if other checks failed too." >&2 status=1 diff --git a/tests/code_coverage_tests/check_licenses.py b/tests/code_coverage_tests/check_licenses.py index 389e534b1ff..158e25180e1 100644 --- a/tests/code_coverage_tests/check_licenses.py +++ b/tests/code_coverage_tests/check_licenses.py @@ -5,8 +5,9 @@ import json from pathlib import Path import re import sys +import time import tomllib -from typing import Dict, List, Optional, Set, Tuple +from typing import Callable, Dict, Final, List, Optional, Protocol, Set, Tuple from packaging.requirements import Requirement import requests @@ -37,6 +38,13 @@ DEFAULT_TRANSITIVE_PIN_PACKAGES = ( # of the identifier, not an operator. _SPDX_OPERATOR_SPLIT = re.compile(r"\s+(?:OR|AND)\s+") _SPDX_WITH_SUFFIX = re.compile(r"\s+WITH\s+.*", re.DOTALL) +_PYPI_FETCH_ATTEMPTS: Final[int] = 3 +_PYPI_FETCH_BACKOFF_SECONDS: Final[float] = 0.5 + + +class _HttpGet(Protocol): + def __call__(self, url: str, *, timeout: float) -> requests.Response: + ... @dataclass @@ -50,7 +58,10 @@ class PackageLicense: class LicenseChecker: def __init__( - self, config_file: Path = Path("./tests/code_coverage_tests/liccheck.ini") + self, + config_file: Path = Path("./tests/code_coverage_tests/liccheck.ini"), + http_get: Optional[_HttpGet] = None, + sleep: Optional[Callable[[float], None]] = None, ): if not config_file.exists(): print(f"Error: Config file {config_file} not found") @@ -79,6 +90,8 @@ class LicenseChecker: # Track package results self.package_results: List[PackageLicense] = [] + self._http_get = http_get + self._sleep = sleep @staticmethod def _normalize_package_name(package_name: str) -> str: @@ -123,21 +136,38 @@ class LicenseChecker: last resort derives the license from the ``License :: OSI Approved :: ...`` trove classifiers. """ - try: - url = f"https://pypi.org/pypi/{package_name}/{version}/json" - response = requests.get(url, timeout=10) - response.raise_for_status() - info = response.json().get("info", {}) or {} - return ( - info.get("license_expression") - or info.get("license") - or self._license_from_classifiers(info.get("classifiers") or []) - ) - except Exception as e: - print( - f"Warning: Failed to fetch license for {package_name} {version}: {str(e)}" - ) - return None + url = f"https://pypi.org/pypi/{package_name}/{version}/json" + http_get = self._http_get if self._http_get is not None else requests.get + sleep = self._sleep if self._sleep is not None else time.sleep + + for attempt in range(_PYPI_FETCH_ATTEMPTS): + try: + response = http_get(url, timeout=10) + response.raise_for_status() + info = response.json().get("info", {}) or {} + return ( + info.get("license_expression") + or info.get("license") + or self._license_from_classifiers(info.get("classifiers") or []) + ) + except Exception as error: + if self._is_retryable_pypi_error(error) and attempt < _PYPI_FETCH_ATTEMPTS - 1: + sleep(_PYPI_FETCH_BACKOFF_SECONDS) + continue + print( + f"Warning: Failed to fetch license for {package_name} {version}: {str(error)}" + ) + return None + return None + + @staticmethod + def _is_retryable_pypi_error(error: Exception) -> bool: + if isinstance(error, (requests.ConnectionError, requests.Timeout)): + return True + if not isinstance(error, requests.HTTPError) or error.response is None: + return False + status_code = error.response.status_code + return status_code == 429 or status_code >= 500 @staticmethod def _license_from_classifiers(classifiers: List[str]) -> Optional[str]: diff --git a/tests/e2e/llm_translation/test_together_ai_e2e.py b/tests/e2e/llm_translation/test_together_ai_e2e.py index 788b1858b73..90581aadd43 100644 --- a/tests/e2e/llm_translation/test_together_ai_e2e.py +++ b/tests/e2e/llm_translation/test_together_ai_e2e.py @@ -210,16 +210,24 @@ def _deltas(result: StreamingResponse) -> list[_StreamDelta]: ] -def _single_weather_call(message: OutMessage) -> ToolCall: - assert message.tool_calls, f"Together dropped the tool call: {message}" - assert len(message.tool_calls) == 1, f"expected one tool call, got {message.tool_calls}" - call = message.tool_calls[0] +def _validated_weather_call_id(call: ToolCall) -> str: assert call.id, f"tool call carries no id, so a tool result cannot answer it: {call}" assert call.function.name == "get_weather", f"wrong tool called: {call}" assert call.function.arguments, f"tool call carries no arguments: {call}" args = _WeatherArgs.model_validate_json(call.function.arguments) assert "paris" in args.location.lower(), f"tool arguments lost the location: {args}" - return call + return call.id + + +def _weather_call_ids(message: OutMessage) -> tuple[str, ...]: + """The id of every tool call the model made, each one checked for the fields a + caller needs to answer it. The backend is whichever together_ai row is cheapest + with tools and reasoning, and those rows carry supports_parallel_function_calling, + so one weather prompt can legitimately come back as several get_weather calls. + What the gateway owes us is that each call survives translation intact; how many + the model chose to make is the model's business.""" + assert message.tool_calls, f"Together dropped the tool call: {message}" + return tuple(_validated_weather_call_id(call) for call in message.tool_calls) def _weather_call(client: PassthroughClient, key: str, model: str) -> OutMessage: @@ -289,7 +297,7 @@ class TestTogetherChatCompletions: self, client: PassthroughClient, resources: ResourceManager, reasoning_tool_backend: str ) -> None: model, key = _register(client, resources, reasoning_tool_backend) - _single_weather_call(_weather_call(client, key, model)) + _ = _weather_call_ids(_weather_call(client, key, model)) @pytest.mark.covers("llm.chat_completions.together_ai.tool_use.stream.works") def test_tool_call_is_streamed( @@ -328,8 +336,7 @@ class TestTogetherChatCompletions: ) -> None: model, key = _register(client, resources, reasoning_tool_backend) first = _weather_call(client, key, model) - call = _single_weather_call(first) - assert call.id is not None + call_ids = _weather_call_ids(first) answer = _message( unwrap( @@ -344,7 +351,10 @@ class TestTogetherChatCompletions: reasoning_content=first.reasoning_content, tool_calls=first.tool_calls, ), - ChatToolResultTurn(tool_call_id=call.id, content=WEATHER_REPORT), + *( + ChatToolResultTurn(tool_call_id=call_id, content=WEATHER_REPORT) + for call_id in call_ids + ), ], tools=[WEATHER_TOOL], max_tokens=512, @@ -470,9 +480,21 @@ def _tool_use_blocks(content: list[AnthropicContentBlock] | None) -> list[Anthro return [block for block in content if block.type == "tool_use"] +def _validated_tool_use_id(block: AnthropicContentBlock) -> str: + assert block.name == "get_weather", f"wrong tool called: {block}" + assert block.id, f"tool_use block carries no id, so a tool_result cannot answer it: {block}" + assert block.input is not None, f"tool_use block carries no input: {block}" + args = _WeatherArgs.model_validate(block.input) + assert "paris" in args.location.lower(), f"tool input lost the location: {args}" + return block.id + + def _messages_weather_call( client: PassthroughClient, key: str, model: str -) -> tuple[list[AnthropicContentBlock], AnthropicContentBlock]: +) -> tuple[list[AnthropicContentBlock], tuple[str, ...]]: + """The blocks /v1/messages returned and the id of every tool_use among them. The + count is the model's choice (see _weather_call_ids); what this surface owes us is + that each tool_use arrives named and addressable.""" response = unwrap( client.proxy.messages( key, @@ -485,12 +507,9 @@ def _messages_weather_call( ) ) tool_uses = _tool_use_blocks(response.content) - assert len(tool_uses) == 1, f"expected one tool_use block, got {response.content}" - block = tool_uses[0] - assert block.name == "get_weather", f"wrong tool called: {block}" - assert block.id, f"tool_use block carries no id, so a tool_result cannot answer it: {block}" + assert tool_uses, f"/v1/messages carried no tool_use block: {response.content}" assert response.content is not None - return response.content, block + return response.content, tuple(_validated_tool_use_id(block) for block in tool_uses) class TestTogetherMessages: @@ -506,8 +525,7 @@ class TestTogetherMessages: self, client: PassthroughClient, resources: ResourceManager, reasoning_tool_backend: str ) -> None: model, key = _register(client, resources, reasoning_tool_backend) - first_content, block = _messages_weather_call(client, key, model) - assert block.id is not None + first_content, tool_use_ids = _messages_weather_call(client, key, model) response = unwrap( client.proxy.messages( @@ -520,7 +538,10 @@ class TestTogetherMessages: ChatMessage(role="user", content=WEATHER_PROMPT), AnthropicAssistantTurn(content=first_content), AnthropicToolResultTurn( - content=[AnthropicToolResultBlock(tool_use_id=block.id, content=WEATHER_REPORT)] + content=[ + AnthropicToolResultBlock(tool_use_id=tool_use_id, content=WEATHER_REPORT) + for tool_use_id in tool_use_ids + ] ), ], ), diff --git a/tests/e2e/management/management_client.py b/tests/e2e/management/management_client.py index b2bd41e19ba..387280c8023 100644 --- a/tests/e2e/management/management_client.py +++ b/tests/e2e/management/management_client.py @@ -9,8 +9,21 @@ from __future__ import annotations import time from dataclasses import dataclass +import jwt + +from e2e_config import MASTER_KEY from proxy_client import ProxyClient -from e2e_http import NoBody, ProbeResult, Result, StreamingResponse, Success, UnknownApiError, unwrap +from e2e_http import ( + AuthHeaders, + NetworkError, + NoBody, + ProbeResult, + Result, + StreamingResponse, + Success, + UnknownApiError, + unwrap, +) from models import ( ChatBody, ChatMessage, @@ -50,6 +63,9 @@ from models import ( TeamNewBody, TeamNewResponse, TeamUpdateBody, + UiLoginBody, + UiLoginResponse, + UiSessionClaims, UserDeleteBody, UserDeleteResponse, UserInfoParams, @@ -63,38 +79,73 @@ from models import ( MODEL_ACCESS_DENIED_MARKER = "key_model_access_denied" ROUTE_NOT_ALLOWED_MARKER = "not allowed to call this route" +DASHBOARD_SESSION_TEAM_ID = "litellm-dashboard" _TEAM_READY_ATTEMPTS = 15 _TEAM_READY_SLEEP_SECONDS = 0.4 +_KEY_WRITE_ATTEMPTS = 5 +_TRANSIENT_BACKEND_MARKERS = ("connecting to redis", "name resolution") + + +@dataclass(frozen=True, slots=True) +class DashboardSession: + """What a dashboard sign-in hands the Admin UI: the session key it sends as + its bearer on every subsequent call, the claims it renders the signed-in user + from, and where it lands the browser.""" + + session_key: str + claims: UiSessionClaims + redirect_url: str @dataclass(frozen=True, slots=True) class ManagementClient: proxy: ProxyClient + master_key: str def llm_only_key(self) -> str: return self.proxy.generate_key(KeyGenerateBody(models=[], allowed_routes=["llm_api_routes"])) - def update_key_models(self, key: str, models: list[str]) -> None: - last: Result[NoBody] | None = None - for attempt in range(5): + def generate_key(self, body: KeyGenerateBody, *, caller_key: str | None = None) -> Result[KeyGenerateResponse]: + """POST /key/generate. `caller_key` is who is creating the key: the master + key by default, or a virtual key (an admin filling in Create New Key on the + dashboard creates it under the session key their sign-in minted). Returns + the outcome rather than unwrapping it, so a caller can poll a route that is + only transiently refusing.""" + headers = self.proxy.transport.master if caller_key is None else self.proxy.transport.bearer(caller_key) + return self.proxy.transport.post( + "/key/generate", + headers=headers, + json=body, + response_type=KeyGenerateResponse, + ) + + def update_key(self, body: KeyUpdateBody, *, caller_key: str | None = None) -> Result[NoBody]: + """POST /key/update. `caller_key` is who is editing: the master key by + default, or a virtual key (the dashboard edits under the session key its + sign-in minted, never the master key). Returns the outcome rather than + unwrapping it, so a caller can poll a route that is only transiently + refusing; `update_key_models` is the unwrapping shorthand.""" + headers = self.proxy.transport.master if caller_key is None else self.proxy.transport.bearer(caller_key) + last: Result[NoBody] = NetworkError(message="/key/update was never attempted") + for attempt in range(_KEY_WRITE_ATTEMPTS): last = self.proxy.transport.post( "/key/update", - headers=self.proxy.transport.master, - json=KeyUpdateBody(key=key, models=models), + headers=headers, + json=body, response_type=NoBody, ) match last: - case Success(): - return - case UnknownApiError(body=body) if ( - "connecting to redis" in body.lower() or "name resolution" in body.lower() + case UnknownApiError(body=error_body) if any( + marker in error_body.lower() for marker in _TRANSIENT_BACKEND_MARKERS ): time.sleep(0.5 * (attempt + 1)) continue case _: break - assert last is not None - raise AssertionError(last) + return last + + def update_key_models(self, key: str, models: list[str]) -> None: + _ = unwrap(self.update_key(KeyUpdateBody(key=key, models=models))) def delete_key_strict(self, key: str) -> None: """Strict delete for the act phase of a test: a failed delete is a hard @@ -150,15 +201,42 @@ class ManagementClient: ) ).key + def key_list(self, key_alias: str, *, caller_key: str | None = None) -> Result[KeyListResponse]: + """GET /key/list, the Virtual Keys page's own inventory call. `caller_key` is + who is asking: the master key by default, or a virtual key.""" + headers = self.proxy.transport.master if caller_key is None else self.proxy.transport.bearer(caller_key) + return self.proxy.transport.get( + "/key/list", + headers=headers, + params=KeyListParams(key_alias=key_alias), + response_type=KeyListResponse, + ) + def key_alias_count(self, key_alias: str) -> int: - return unwrap( - self.proxy.transport.get( - "/key/list", - headers=self.proxy.transport.master, - params=KeyListParams(key_alias=key_alias), - response_type=KeyListResponse, + return unwrap(self.key_list(key_alias)).total_count + + def dashboard_login(self, username: str, password: str) -> DashboardSession: + """POST /v2/login, the call the Admin UI's sign-in form makes. + + The proxy authenticates the credentials, mints a UI session key for the + signed-in user, and hands it back inside a JWT signed with the master key. + Decoding that JWT is the only way to reach the session key, and it is what + the dashboard itself does before it can call a single management route.""" + response = unwrap( + self.proxy.transport.post( + "/v2/login", + headers=AuthHeaders(), + json=UiLoginBody(username=username, password=password), + response_type=UiLoginResponse, ) - ).total_count + ) + decoded: object = jwt.decode(response.token, self.master_key, algorithms=["HS256"]) + claims = UiSessionClaims.model_validate(decoded) + return DashboardSession( + session_key=claims.key, + claims=claims, + redirect_url=response.redirect_url, + ) def create_team(self, body: TeamNewBody) -> str: team_id = unwrap( @@ -465,4 +543,4 @@ class ManagementClient: def build_client(proxy: ProxyClient) -> ManagementClient: - return ManagementClient(proxy=proxy) + return ManagementClient(proxy=proxy, master_key=MASTER_KEY) diff --git a/tests/e2e/management/test_management_e2e.py b/tests/e2e/management/test_management_e2e.py index 9b398963ac9..a56eb853823 100644 --- a/tests/e2e/management/test_management_e2e.py +++ b/tests/e2e/management/test_management_e2e.py @@ -15,15 +15,30 @@ from collections.abc import Callable import pytest -from e2e_config import unique_marker -from e2e_http import StreamingResponse +from e2e_config import UI_PASSWORD, UI_USERNAME, unique_marker +from e2e_http import StreamingResponse, Success from lifecycle import ResourceManager from management_client import ( + DASHBOARD_SESSION_TEAM_ID, MODEL_ACCESS_DENIED_MARKER, ROUTE_NOT_ALLOWED_MARKER, ManagementClient, ) -from models import KeyGenerateBody, OrgInfoResponse, OrgNewBody, OrgUpdateBody, TagListEntry, TagNewBody, TeamNewBody, TeamUpdateBody, UserNewBody, UserUpdateBody, LiteLLMParamsBody, ModelInfoEntry +from models import ( + KeyGenerateBody, + KeyUpdateBody, + LiteLLMParamsBody, + ModelInfoEntry, + OrgInfoResponse, + OrgNewBody, + OrgUpdateBody, + TagListEntry, + TagNewBody, + TeamNewBody, + TeamUpdateBody, + UserNewBody, + UserUpdateBody, +) pytestmark = pytest.mark.e2e @@ -199,6 +214,132 @@ class TestKeyRoutes: return True if client.proxy.key_info(key).blocked else None _ = _poll(client, blocked, "/key/info never reported the key blocked after /key/block before the deadline") + + +class TestDashboardKeyRoutes: + """The /key writes as the Admin UI makes them. Signing in mints the session key + the dashboard authenticates with, and every key an admin creates or edits in the + browser is written under that session key rather than the master key, so these + are the same routes the API-surface tests cover with a different caller.""" + + @pytest.mark.covers("mgmt.key.generate.happy_path") + def test_creating_a_key_from_the_dashboard_persists_and_works( + self, client: ManagementClient, resources: ResourceManager + ) -> None: + session = client.dashboard_login(UI_USERNAME, UI_PASSWORD) + resources.defer(lambda: client.proxy.delete_key(session.session_key)) + + assert session.claims.login_method == "username_password", ( + f"/v2/login reports login_method {session.claims.login_method!r} for a username/password sign-in" + ) + assert session.claims.user_role == "proxy_admin", ( + f"/v2/login reports user_role {session.claims.user_role!r} for the admin credentials, " + "expected 'proxy_admin'" + ) + assert session.redirect_url.endswith("/ui?login=success"), ( + f"/v2/login sends the browser to {session.redirect_url!r} instead of the dashboard" + ) + + session_info = client.proxy.key_info(session.session_key) + assert session_info.team_id == DASHBOARD_SESSION_TEAM_ID, ( + f"the minted session key reports team_id {session_info.team_id!r}, expected the dashboard's " + f"{DASHBOARD_SESSION_TEAM_ID!r}" + ) + + alias = f"e2e-mgmt-uicreate-{unique_marker()}" + + def dashboard_creates_the_key() -> str | None: + match client.generate_key( + KeyGenerateBody(models=["gemini-2.5-flash"], key_alias=alias, tpm_limit=100), + caller_key=session.session_key, + ): + case Success(data=created): + return created.key + case _: + return None + + created = _poll( + client, + dashboard_creates_the_key, + "the dashboard session key was never accepted on /key/generate before the deadline", + ) + resources.defer(lambda: client.proxy.delete_key(created)) + + created_info = client.proxy.key_info(created) + assert created_info.key_alias == alias, ( + f"/key/info reports key_alias {created_info.key_alias!r} for the key the dashboard created, " + f"expected {alias!r}" + ) + assert created_info.models == ["gemini-2.5-flash"], ( + f"/key/info reports models {created_info.models} for the key the dashboard created" + ) + assert created_info.tpm_limit == 100, ( + f"/key/info reports tpm_limit {created_info.tpm_limit} for the key the dashboard created, expected 100" + ) + + def dashboard_lists_the_key() -> bool | None: + match client.key_list(alias, caller_key=session.session_key): + case Success(data=listing) if listing.total_count == 1: + return True + case _: + return None + + _ = _poll( + client, + dashboard_lists_the_key, + f"the session key never saw {alias!r} in /key/list before the deadline, so the dashboard " + "would render no keys", + ) + + _poll_chat_ok(client, created, "gemini-2.5-flash") + _assert_model_denied(client.chat_status(created, "gpt-5.5", f"say hi {unique_marker()}"), "gpt-5.5") + + @pytest.mark.covers("mgmt.key.update.happy_path") + def test_editing_a_key_from_the_dashboard_persists_and_is_enforced( + self, client: ManagementClient, resources: ResourceManager + ) -> None: + alias = f"e2e-mgmt-uiedit-{unique_marker()}" + target = _generate_key( + client, + resources, + KeyGenerateBody(models=["gemini-2.5-flash"], key_alias=alias, tpm_limit=100, rpm_limit=200), + ) + _poll_chat_ok(client, target, "gemini-2.5-flash") + _assert_model_denied(client.chat_status(target, "gpt-5.5", f"say hi {unique_marker()}"), "gpt-5.5") + + session = client.dashboard_login(UI_USERNAME, UI_PASSWORD) + resources.defer(lambda: client.proxy.delete_key(session.session_key)) + + def dashboard_saves_the_edit() -> bool | None: + match client.update_key( + KeyUpdateBody(key=target, models=["gpt-5.5"], tpm_limit=300, rpm_limit=400), + caller_key=session.session_key, + ): + case Success(): + return True + case _: + return None + + _ = _poll( + client, + dashboard_saves_the_edit, + "the dashboard session key was never accepted on /key/update before the deadline", + ) + + info = client.proxy.key_info(target) + assert info.models == ["gpt-5.5"], ( + f"/key/info reports models {info.models} after the dashboard edit to ['gpt-5.5']" + ) + assert info.tpm_limit == 300, f"/key/info reports tpm_limit {info.tpm_limit} after the dashboard edit to 300" + assert info.rpm_limit == 400, f"/key/info reports rpm_limit {info.rpm_limit} after the dashboard edit to 400" + assert info.key_alias == alias, ( + f"the dashboard edit renamed the key to {info.key_alias!r}, it should still be {alias!r}" + ) + + _poll_model_access_granted(client, target, "gpt-5.5") + _poll_chat_denied(client, target, "gemini-2.5-flash") + + class TestKeyRegeneration: @pytest.mark.covers("mgmt.key.regenerate.happy_path") def test_regenerate_rotates_to_a_working_new_key( diff --git a/tests/e2e/models.py b/tests/e2e/models.py index 95a02b58824..56b6a7a7055 100644 --- a/tests/e2e/models.py +++ b/tests/e2e/models.py @@ -256,6 +256,7 @@ class ChatBody(BaseModel): reasoning_effort: str | None = None thinking: ThinkingParam | None = None service_tier: str | None = None + prompt_cache_key: str | None = None tools: Sequence[ChatTool | McpChatTool] | None = None tool_choice: str | None = None guardrails: list[str] | None = None @@ -420,6 +421,7 @@ class AnthropicContentBlock(BaseModel): text: str | None = None id: str | None = None name: str | None = None + input: dict[str, object] | None = None class AnthropicToolResultBlock(BaseModel): @@ -892,7 +894,10 @@ class CredentialCreateResponse(BaseModel): class KeyUpdateBody(BaseModel): key: str - models: list[str] + models: list[str] | None = None + key_alias: str | None = None + tpm_limit: int | None = None + rpm_limit: int | None = None class KeyBlockBody(BaseModel): @@ -907,6 +912,27 @@ class KeyListResponse(BaseModel): total_count: int +# ---------- admin UI session ---------- + + +class UiLoginBody(BaseModel): + username: str + password: str + + +class UiLoginResponse(BaseModel): + token: str + redirect_url: str + + +class UiSessionClaims(BaseModel): + user_id: str + key: str + user_role: str + login_method: Literal["sso", "username_password"] + exp: int + + class TeamMemberEntry(BaseModel): role: Literal["admin", "user"] user_id: str diff --git a/tests/e2e/quota_management/spend_tracking/test_cost_headers_e2e.py b/tests/e2e/quota_management/spend_tracking/test_cost_headers_e2e.py index 203be611905..abc321ccde8 100644 --- a/tests/e2e/quota_management/spend_tracking/test_cost_headers_e2e.py +++ b/tests/e2e/quota_management/spend_tracking/test_cost_headers_e2e.py @@ -12,11 +12,16 @@ header is exercised with a real nonzero value instead of passing vacuously. The backend is gpt-5.5 because it reports cached tokens on the second call; the gpt-5.6 line reports cache writes and never a read, which would leave the cache-read header at zero forever. The raw-transport send is used because the -typed chat client validates bodies and drops headers. OpenAI caching is -best-effort, so the prime+measure round retries with a fresh prefix before -failing. +typed chat client validates bodies and drops headers. + +OpenAI publishes a primed prefix asynchronously and routes lookups by +prompt_cache_key, so a measure fired the instant the prime returns can miss a +prefix that is about to become readable. Each round pins a cache key and re-reads +the prefix it already paid to prime before spending a fresh one. """ +import time + import pytest from cost_rows import approx_equal, cacheable_prefix, register_priced_model @@ -31,6 +36,8 @@ pytestmark = pytest.mark.e2e BACKEND = "openai/gpt-5.5" OPENAI_API_KEY = "os.environ/OPENAI_API_KEY" CACHE_ATTEMPTS = 3 +CACHE_REREADS = 3 +CACHE_SETTLE_SECONDS = 2.0 INPUT_RATE = 4e-05 OUTPUT_RATE = 8e-05 @@ -70,7 +77,7 @@ class TestCostHeaders: ), ) - def priced_call(content: str) -> StreamingResponse: + def priced_call(content: str, cache_key: str) -> StreamingResponse: response = client.proxy.transport.send( "/chat/completions", headers=client.proxy.transport.bearer(scoped_key), @@ -78,21 +85,30 @@ class TestCostHeaders: model=model, messages=[ChatMessage(role="user", content=content)], max_completion_tokens=4000, + prompt_cache_key=cache_key, ), ) assert response.ok, f"chat failed (status {response.status_code}): {response.body[:300]}" return response - for _ in range(CACHE_ATTEMPTS): - prefix = cacheable_prefix(unique_marker()) - priced_call(f"{prefix}\nReply with the single word ready.") - measured = priced_call(f"{prefix}\nReply with the single word measured.") - if _header_cost(measured, "x-litellm-response-cost-cache-read") > 0: - break - else: + def prime_then_reread() -> StreamingResponse | None: + marker = unique_marker() + prefix = cacheable_prefix(marker) + priced_call(f"{prefix}\nReply with the single word ready.", marker) + for _ in range(CACHE_REREADS): + time.sleep(CACHE_SETTLE_SECONDS) + response = priced_call(f"{prefix}\nReply with the single word measured.", marker) + if _header_cost(response, "x-litellm-response-cost-cache-read") > 0: + return response + return None + + rounds = (prime_then_reread() for _ in range(CACHE_ATTEMPTS)) + measured = next((response for response in rounds if response is not None), None) + if measured is None: pytest.fail( - f"no cache read landed across {CACHE_ATTEMPTS} prime+measure rounds; " - "the cache-read cost header was never exercised with a nonzero value" + f"no cache read landed across {CACHE_ATTEMPTS} prime rounds of " + f"{CACHE_REREADS} re-reads each; the cache-read cost header was never " + "exercised with a nonzero value" ) total = measured.response_cost diff --git a/tests/e2e/ui/tests/modelsPage/autoRouterTemplateSelect.spec.ts b/tests/e2e/ui/tests/modelsPage/autoRouterTemplateSelect.spec.ts new file mode 100644 index 00000000000..98bd1b84f11 --- /dev/null +++ b/tests/e2e/ui/tests/modelsPage/autoRouterTemplateSelect.spec.ts @@ -0,0 +1,59 @@ +import { expect, test, type Page as PlaywrightPage } from "@playwright/test"; +import { ADMIN_STORAGE_PATH } from "../../constants"; +import { navigateToPage } from "../../helpers/navigation"; +import { Page } from "../../fixtures/pages"; + +/** + * Opens Add Auto Router and returns the Template select's trigger, which is the + * shallowest real page that renders SelectContent with tall multi-line options. + */ +async function openTemplateSelect(page: PlaywrightPage) { + await navigateToPage(page, Page.Models); + await page.getByRole("tab", { name: "Auto-Routers" }).click(); + await page.getByRole("button", { name: "Add Auto Router" }).click(); + + const trigger = page.getByTestId("template-selector"); + await expect(trigger).toBeVisible(); + return trigger; +} + +test.describe("Auto Router template select anchoring", () => { + test.use({ storageState: ADMIN_STORAGE_PATH }); + + test("opens the options below the trigger rather than over it", async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 900 }); + const trigger = await openTemplateSelect(page); + const triggerBox = await trigger.boundingBox(); + + await trigger.click(); + const popup = page.locator('[data-slot="select-content"]'); + await expect(popup).toBeVisible(); + const popupBox = await popup.boundingBox(); + + expect(triggerBox).not.toBeNull(); + expect(popupBox).not.toBeNull(); + + // Item-aligned mode reports "none" and puts the active item over the trigger. + await expect(popup).toHaveAttribute("data-side", "bottom"); + expect(popupBox!.y).toBeGreaterThanOrEqual(triggerBox!.y + triggerBox!.height); + }); + + test("flips above the trigger instead of covering it when there is no room below", async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 560 }); + const trigger = await openTemplateSelect(page); + await trigger.scrollIntoViewIfNeeded(); + const triggerBox = await trigger.boundingBox(); + + await trigger.click(); + const popup = page.locator('[data-slot="select-content"]'); + await expect(popup).toBeVisible(); + const popupBox = await popup.boundingBox(); + + expect(triggerBox).not.toBeNull(); + expect(popupBox).not.toBeNull(); + + const overlaps = + popupBox!.y < triggerBox!.y + triggerBox!.height && popupBox!.y + popupBox!.height > triggerBox!.y; + expect(overlaps).toBe(false); + }); +}); diff --git a/tests/e2e/ui/tests/settings/routerSettings.spec.ts b/tests/e2e/ui/tests/settings/routerSettings.spec.ts index 1188e8f201e..cd64e6e4453 100644 --- a/tests/e2e/ui/tests/settings/routerSettings.spec.ts +++ b/tests/e2e/ui/tests/settings/routerSettings.spec.ts @@ -117,6 +117,11 @@ const ADMIN_AUTH = { Authorization: `Bearer ${users[Role.ProxyAdmin].password}`, }; +// Five probes 2s apart outlast the e2e stack's proxy_config_reload_interval_seconds of 7. +const SETTLE_INTERVAL_MS = 2_000; +const SETTLE_PROBES = 5; +const SETTLE_TIMEOUT_MS = 60_000; + /** * Apply a router_settings patch through the typed /config/update contract. The * server merges it over existing settings (request wins), so only the passed keys @@ -133,6 +138,21 @@ async function patchRouterSettings( expect(res.ok(), `seed /config/update failed: ${res.status()} ${await res.text()}`).toBeTruthy(); } +/** + * Spreads its samples across more than one reload cycle: a single reply only proves the one + * replica that served it has reloaded, not the sibling still on the pre-update config. + */ +async function sampleStatuses(probe: () => Promise): Promise { + return Array.from({ length: SETTLE_PROBES }).reduce>( + async (taken, _unused, index) => { + const sofar = await taken; + if (index > 0) await new Promise((resolve) => setTimeout(resolve, SETTLE_INTERVAL_MS)); + return [...sofar, await probe()]; + }, + Promise.resolve([]), + ); +} + test.describe("Router Settings - Loadbalancing", () => { test.use({ storageState: ADMIN_STORAGE_PATH }); @@ -252,28 +272,34 @@ test.describe("Router Settings - Fallbacks serve the request", () => { }); test("a request to an unreachable model is answered by its fallback", async ({ page, request }) => { - const chat = async () => - request.post("/v1/chat/completions", { - headers: { ...ADMIN_AUTH, "Content-Type": "application/json" }, - data: { - model: BROKEN_PRIMARY, - messages: [{ role: "user", content: "fallback probe" }], - }, - }); + const chatStatus = async () => + ( + await request.post("/v1/chat/completions", { + headers: { ...ADMIN_AUTH, "Content-Type": "application/json" }, + data: { + model: BROKEN_PRIMARY, + messages: [{ role: "user", content: "fallback probe" }], + }, + }) + ).status(); - // The control: it proves the reply below could only have come from the fallback. - expect((await chat()).status(), "broken primary unexpectedly succeeded on its own").toBeGreaterThanOrEqual(400); + // The control: every replica must reject, or the reply below could have come from one + // that was still serving a fallback left behind by an earlier attempt. + await expect + .poll(async () => (await sampleStatuses(chatStatus)).every((status) => status >= 400), { + timeout: SETTLE_TIMEOUT_MS, + message: "broken primary unexpectedly succeeded on its own", + }) + .toBe(true); await patchRouterSettings(request, { fallbacks: [{ [BROKEN_PRIMARY]: [PRIMARY] }], } as Partial>); - // Same call now succeeds, served by the fallback model. + // One success is the whole claim here, so this waits for a first sighting rather than + // for every replica: demanding a streak would also assert a fallback hit rate. await expect - .poll(async () => (await chat()).status(), { - timeout: 30_000, - message: "fallback never took effect", - }) + .poll(chatStatus, { timeout: SETTLE_TIMEOUT_MS, message: "fallback never took effect" }) .toBe(200); // And the playground renders a reply for a model whose own upstream is down. diff --git a/tests/litellm-proxy-extras/test_litellm_proxy_extras_utils.py b/tests/litellm-proxy-extras/test_litellm_proxy_extras_utils.py index 09f3e0ba34f..498d0cb4723 100644 --- a/tests/litellm-proxy-extras/test_litellm_proxy_extras_utils.py +++ b/tests/litellm-proxy-extras/test_litellm_proxy_extras_utils.py @@ -12,7 +12,11 @@ sys.path.insert( ), ) -from litellm_proxy_extras.utils import ProxyExtrasDBManager +from litellm_proxy_extras.utils import ( + PARTITIONED_SPEND_LOGS_PUSH_ERROR, + ProxyExtrasDBManager, + filter_partitioned_spend_logs_diff, +) # Path to the migrations directory _MIGRATIONS_DIR = os.path.abspath( @@ -475,3 +479,205 @@ class TestMigrationGuardScope: if not self._run_rules([(TestMigrationGuardScope._NEW, by_name[name])]) ] assert not redundant, f"these no longer violate and should be removed: {redundant}" + + +_PARTITIONED_DRIFT_SQL = """-- AlterTable +ALTER TABLE "LiteLLM_BudgetTable" ADD COLUMN "updated_by" TEXT; + +-- AlterTable +ALTER TABLE "LiteLLM_SpendLogs" DROP CONSTRAINT "LiteLLM_SpendLogs_pkey", +ADD COLUMN "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, +ADD COLUMN "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, +ADD CONSTRAINT "LiteLLM_SpendLogs_pkey" PRIMARY KEY ("request_id"); + +-- DropTable +DROP TABLE "LiteLLM_SpendLogs_legacy"; +""" + + +class TestPartitionedSpendLogsDriftFilter: + """A doc-partitioned LiteLLM_SpendLogs (db_scripts/partition_spend_logs.sql) has a + composite primary key that schema.prisma cannot express, so `prisma migrate diff` + emits a primary-key rewrite that Postgres rejects, aborting the whole drift script + before its legitimate statements run.""" + + def test_pk_rewrite_and_runbook_artifact_drops_are_removed(self): + filtered = filter_partitioned_spend_logs_diff(_PARTITIONED_DRIFT_SQL) + assert 'DROP CONSTRAINT "LiteLLM_SpendLogs_pkey"' not in filtered + assert 'PRIMARY KEY ("request_id")' not in filtered + assert "LiteLLM_SpendLogs_legacy" not in filtered + + def test_legitimate_statements_in_the_same_script_are_kept(self): + filtered = filter_partitioned_spend_logs_diff(_PARTITIONED_DRIFT_SQL) + assert 'ALTER TABLE "LiteLLM_BudgetTable" ADD COLUMN "updated_by" TEXT;' in filtered + assert 'ADD COLUMN "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP' in filtered + assert 'ADD COLUMN "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP' in filtered + assert filtered.count('ALTER TABLE "LiteLLM_SpendLogs"') == 1 + + def test_an_alter_containing_only_the_pk_rewrite_is_dropped_entirely(self): + sql = ( + 'ALTER TABLE "LiteLLM_SpendLogs" DROP CONSTRAINT "LiteLLM_SpendLogs_pkey",\n' + 'ADD CONSTRAINT "LiteLLM_SpendLogs_pkey" PRIMARY KEY ("request_id");\n' + ) + assert filter_partitioned_spend_logs_diff(sql).strip() == "" + + def test_other_tables_pk_changes_are_untouched(self): + sql = ( + 'ALTER TABLE "LiteLLM_TeamTable" DROP CONSTRAINT "LiteLLM_TeamTable_pkey",\n' + 'ADD CONSTRAINT "LiteLLM_TeamTable_pkey" PRIMARY KEY ("team_id");\n' + ) + filtered = filter_partitioned_spend_logs_diff(sql) + assert 'DROP CONSTRAINT "LiteLLM_TeamTable_pkey"' in filtered + assert 'PRIMARY KEY ("team_id")' in filtered + + +class _FakeCompleted: + stdout = "" + stderr = "" + + +class TestResolveAllMigrationsLedger: + def _run(self, monkeypatch, tmp_path, partitioned, execute_fails): + import subprocess as subprocess_module + + import litellm_proxy_extras.utils as utils_module + + monkeypatch.setenv("DATABASE_URL", "postgresql://u:p@localhost:5432/db") + monkeypatch.delenv("DIRECT_URL", raising=False) + monkeypatch.setattr( + ProxyExtrasDBManager, "spend_logs_is_partitioned", staticmethod(lambda: partitioned) + ) + monkeypatch.setattr( + ProxyExtrasDBManager, + "_get_migration_names", + staticmethod(lambda migrations_dir: ["20250326162113_baseline"]), + ) + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + if "diff" in cmd: + kwargs["stdout"].write(_PARTITIONED_DRIFT_SQL) + return _FakeCompleted() + if "execute" in cmd: + executed_sql = open(cmd[cmd.index("--file") + 1]).read() + calls.append(("executed_sql", executed_sql)) + if execute_fails: + raise subprocess_module.CalledProcessError(1, cmd, stderr="boom") + return _FakeCompleted() + return _FakeCompleted() + + monkeypatch.setattr(utils_module.subprocess, "run", fake_run) + ProxyExtrasDBManager._resolve_all_migrations(str(tmp_path), "schema.prisma") + return calls + + def _resolved(self, calls): + return [c for c in calls if isinstance(c, list) and "resolve" in c] + + def _executed_sql(self, calls): + return next(c[1] for c in calls if isinstance(c, tuple) and c[0] == "executed_sql") + + def test_failed_drift_apply_does_not_mark_migrations_applied(self, monkeypatch, tmp_path): + calls = self._run(monkeypatch, tmp_path, partitioned=False, execute_fails=True) + assert self._resolved(calls) == [] + + def test_successful_drift_apply_still_marks_migrations_applied(self, monkeypatch, tmp_path): + calls = self._run(monkeypatch, tmp_path, partitioned=False, execute_fails=False) + assert len(self._resolved(calls)) == 1 + + def test_partitioned_spend_logs_gets_the_filtered_drift_script(self, monkeypatch, tmp_path): + calls = self._run(monkeypatch, tmp_path, partitioned=True, execute_fails=False) + executed_sql = self._executed_sql(calls) + assert 'PRIMARY KEY ("request_id")' not in executed_sql + assert "LiteLLM_SpendLogs_legacy" not in executed_sql + assert 'ALTER TABLE "LiteLLM_BudgetTable" ADD COLUMN "updated_by" TEXT;' in executed_sql + assert 'ADD COLUMN "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP' in executed_sql + assert len(self._resolved(calls)) == 1 + + def test_unpartitioned_spend_logs_drift_script_is_untouched(self, monkeypatch, tmp_path): + calls = self._run(monkeypatch, tmp_path, partitioned=False, execute_fails=False) + assert self._executed_sql(calls) == _PARTITIONED_DRIFT_SQL + + +class TestPartitionedSpendLogsPushGuard: + def _forbid_subprocess(self, monkeypatch): + import litellm_proxy_extras.utils as utils_module + + def fail_run(cmd, **kwargs): + raise AssertionError(f"subprocess.run should not be called, got: {cmd}") + + monkeypatch.setattr(utils_module.subprocess, "run", fail_run) + + def test_v1_db_push_fails_fast_with_guidance(self, monkeypatch): + monkeypatch.setattr( + ProxyExtrasDBManager, "spend_logs_is_partitioned", staticmethod(lambda: True) + ) + self._forbid_subprocess(monkeypatch) + with pytest.raises(RuntimeError) as err: + ProxyExtrasDBManager._run_migrations(use_migrate=False, use_v2_resolver=False) + assert str(err.value) == PARTITIONED_SPEND_LOGS_PUSH_ERROR + + def test_v2_db_push_fails_fast_with_guidance(self, monkeypatch): + monkeypatch.setattr( + ProxyExtrasDBManager, "spend_logs_is_partitioned", staticmethod(lambda: True) + ) + self._forbid_subprocess(monkeypatch) + with pytest.raises(RuntimeError) as err: + ProxyExtrasDBManager._setup_database_v2(use_migrate=False) + assert str(err.value) == PARTITIONED_SPEND_LOGS_PUSH_ERROR + + +class _FakeCursor: + def fetchone(self): + return (1,) + + +class _FakePsycopgConn: + def __init__(self, executed): + self._executed = executed + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def execute(self, query, params): + self._executed.append((query, params)) + return _FakeCursor() + + +class TestSpendLogsPartitionDetectionSchemaScope: + """A same-named LiteLLM_SpendLogs in another schema must not trip the + detector: the catalog lookup has to be scoped to Prisma's target schema.""" + + def _detect(self, monkeypatch, database_url): + import sys + import types + + executed = [] + fake_psycopg = types.ModuleType("psycopg") + fake_psycopg.connect = lambda url, **kwargs: _FakePsycopgConn(executed) + fake_psycopg.OperationalError = type("OperationalError", (Exception,), {}) + fake_psycopg.DatabaseError = type("DatabaseError", (Exception,), {}) + monkeypatch.setitem(sys.modules, "psycopg", fake_psycopg) + monkeypatch.setenv("DATABASE_URL", database_url) + assert ProxyExtrasDBManager.spend_logs_is_partitioned() is True + return executed[0] + + def test_lookup_is_scoped_to_the_schema_url_param(self, monkeypatch): + query, params = self._detect( + monkeypatch, "postgresql://u:p@localhost:5432/db?schema=tenant_a" + ) + assert "pg_namespace" in query + assert "n.nspname = %s" in query + assert params == ("tenant_a",) + + def test_lookup_falls_back_to_public_without_a_schema_param(self, monkeypatch): + query, params = self._detect(monkeypatch, "postgresql://u:p@localhost:5432/db") + assert "n.nspname = %s" in query + assert params == ("public",) + + def test_only_partitioned_relations_match(self, monkeypatch): + query, _ = self._detect(monkeypatch, "postgresql://u:p@localhost:5432/db") + assert "pg_partitioned_table" in query diff --git a/tests/llm_translation/test_together_ai.py b/tests/llm_translation/test_together_ai.py index c371caefa5e..fd7ad40ed11 100644 --- a/tests/llm_translation/test_together_ai.py +++ b/tests/llm_translation/test_together_ai.py @@ -23,26 +23,18 @@ class TestTogetherAI(BaseLLMChatTest): pass @pytest.mark.parametrize( - "model, expected_bool", + "model", [ - ("meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", True), - ("nvidia/Llama-3.1-Nemotron-70B-Instruct-HF", False), + "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", + "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF", ], ) - def test_get_supported_response_format_together_ai( - self, model: str, expected_bool: bool - ) -> None: + def test_get_supported_response_format_together_ai(self, model: str) -> None: os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" litellm.model_cost = litellm.get_model_cost_map(url="") optional_params = litellm.get_supported_openai_params( model, custom_llm_provider="together_ai" ) - # Mapped provider assert isinstance(optional_params, list) - - if expected_bool: - assert "response_format" in optional_params - assert "tools" in optional_params - else: - assert "response_format" not in optional_params - assert "tools" not in optional_params + assert "response_format" in optional_params + assert "tools" in optional_params diff --git a/tests/mcp_tests/conftest.py b/tests/mcp_tests/conftest.py index 5823893afc0..eff32f27aec 100644 --- a/tests/mcp_tests/conftest.py +++ b/tests/mcp_tests/conftest.py @@ -45,6 +45,22 @@ def setup_and_teardown(): asyncio.set_event_loop(None) # Remove the reference to the loop +@pytest.fixture(scope="function", autouse=True) +async def drain_logging_worker(): + """ + The logging queue is bound to the running loop, so anything left queued when a test's loop + goes away is carried onto the next test's loop and fires against its callbacks. + """ + from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER + + yield + + try: + await asyncio.wait_for(GLOBAL_LOGGING_WORKER.clear_queue(), timeout=10) + except asyncio.TimeoutError: + pass + + def pytest_collection_modifyitems(config, items): # Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests custom_logger_tests = [ diff --git a/tests/proxy_unit_tests/test_proxy_server.py b/tests/proxy_unit_tests/test_proxy_server.py index 375e1117371..47554913419 100644 --- a/tests/proxy_unit_tests/test_proxy_server.py +++ b/tests/proxy_unit_tests/test_proxy_server.py @@ -2661,7 +2661,7 @@ async def test_run_direct_health_check_drops_only_the_rejected_kwarg(monkeypatch rejected argument alongside working ones would probe deployments the operator opted out.""" import litellm.proxy.proxy_server as proxy_server - seen: list = [] + seen: list[tuple[dict[str, str] | None, bool]] = [] async def fake_perform_health_check( model_list, diff --git a/tests/test_litellm/conftest.py b/tests/test_litellm/conftest.py index 1fe73b552da..62c95cb100b 100644 --- a/tests/test_litellm/conftest.py +++ b/tests/test_litellm/conftest.py @@ -375,6 +375,9 @@ def isolate_litellm_state(): litellm.in_memory_llm_clients_cache.flush_cache() image_handling_module.in_memory_cache.flush_cache() _reset_module_level_aws_auth_caches() + # litellm.get_model_info() memoizes ModelInfo built from litellm.model_cost, so a + # test that rebinds the cost map leaves later tests pricing against the old map. + litellm_utils_module._invalidate_model_cost_lowercase_map() # Clear all callback lists to prevent cross-test contamination if hasattr(litellm, "callbacks"): @@ -418,6 +421,7 @@ def isolate_litellm_state(): litellm_utils_module._runtime_registered_model_cost.clear() litellm_utils_module._runtime_registered_model_cost.update(original_runtime_registered_model_cost) + litellm_utils_module._invalidate_model_cost_lowercase_map() for _router in tuple(litellm_router_module._live_routers): litellm_router_module._live_routers.discard(_router) diff --git a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py b/tests/test_litellm/experimental_mcp_client/test_mcp_client.py index b1182dd7262..fd7ab3afdab 100644 --- a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py +++ b/tests/test_litellm/experimental_mcp_client/test_mcp_client.py @@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import anyio import httpx import pytest +from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import StaticHeaderAuth from mcp import McpError from mcp.shared.message import SessionMessage from mcp.types import ( @@ -1095,3 +1096,188 @@ def test_mcp_extra_matches_proxy_extra_and_supports_streamable_http(): specifier = Requirement(mcp_extra[0]).specifier assert not specifier.contains("1.23.0") assert specifier.contains("1.28.1") + + +@pytest.mark.parametrize( + "auth_type, default_header", + [ + (MCPAuth.oauth2, "Authorization"), + (MCPAuth.bearer_token, "Authorization"), + (MCPAuth.api_key, "X-API-Key"), + ], +) +def test_v1_auth_headers_default_to_the_auth_type_slot(auth_type: MCPAuth, default_header: str) -> None: + client = MCPClient(server_url="http://up.example.com/mcp", auth_type=auth_type) + client.update_auth_value("tok") + assert default_header in client._get_auth_headers() + + +@pytest.mark.parametrize("auth_type", [MCPAuth.oauth2, MCPAuth.bearer_token, MCPAuth.api_key]) +def test_v1_auth_headers_honor_the_configured_slot(auth_type: MCPAuth) -> None: + """The v1 stack mints its own client_credentials token (oauth2_token_cache) and writes it here, + so leaving this table hardcoded makes the knob a silent no-op for every server that resolves + through v1 rather than the v2 resolver.""" + client = MCPClient( + server_url="http://up.example.com/mcp", + auth_type=auth_type, + auth_header_name="esb-oauth", + ) + client.update_auth_value("tok") + headers = client._get_auth_headers() + assert "esb-oauth" in headers + assert "Authorization" not in headers + assert "X-API-Key" not in headers + + +def test_v1_static_headers_still_win_their_own_slot(): + # extra_headers (which carries static_headers) is applied last on the v1 path, so a static + # Authorization survives untouched while the resolved credential sits on its own header. + client = MCPClient( + server_url="http://up.example.com/mcp", + auth_type=MCPAuth.oauth2, + auth_header_name="esb-oauth", + extra_headers={"Authorization": "Bearer static-upstream-mcp-token"}, + ) + client.update_auth_value("minted") + headers = client._get_auth_headers() + assert headers["esb-oauth"] == "Bearer minted" + assert headers["Authorization"] == "Bearer static-upstream-mcp-token" + + +@pytest.mark.asyncio +async def test_a_custom_credential_header_is_stripped_when_a_redirect_crosses_origin(): + """httpx drops Authorization across origins but keeps every other header, so a credential the + operator moved to its own slot would be replayed to whatever host the upstream redirects to. + Verified against real httpx redirect handling, not a hand-built request. + """ + seen: "list[tuple[str, str]]" = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append((request.url.host, request.headers.get("esb-oauth", ""))) + if request.url.host == "upstream.example.com": + return httpx.Response(302, headers={"Location": "https://attacker.example.com/collect"}) + return httpx.Response(200) + + client = MCPClient( + server_url="https://upstream.example.com/mcp", + auth_type=MCPAuth.oauth2, + auth_header_name="esb-oauth", + ) + client.update_auth_value("minted-token") + factory = client._create_httpx_client_factory() + async with factory(headers=client._get_auth_headers(), timeout=None) as http_client: + http_client._transport = httpx.MockTransport(handler) + await http_client.get("https://upstream.example.com/mcp") + + assert seen[0] == ("upstream.example.com", "Bearer minted-token") + assert seen[1] == ("attacker.example.com", "") + + +@pytest.mark.asyncio +async def test_authorization_is_left_to_httpx_and_needs_no_guard(): + # The default slot is already protected by httpx, so the client must not install a guard for it + # and must not interfere with the ordinary Authorization path. + url = "https://upstream.example.com/mcp" + from litellm.types.mcp import credential_redirect_hook + + def guard_for(client: MCPClient): + return credential_redirect_hook(client.server_url, client._credential_slot) + + assert guard_for(MCPClient(server_url=url, auth_type=MCPAuth.oauth2)) is None + assert guard_for(MCPClient(server_url=url, resolved_auth=StaticHeaderAuth("Bearer x"))) is None + # a v2 resolver slot is discovered from the auth object, without the caller naming it again + custom = MCPClient(server_url=url, resolved_auth=StaticHeaderAuth("Bearer x", header_name="esb-oauth")) + assert guard_for(custom) is not None + # and the same answer arrives via the v1 configured slot + assert guard_for(MCPClient(server_url=url, auth_header_name="ESB-OAuth")) is not None + + +def test_an_injected_header_cannot_shadow_the_configured_credential_slot(): + """The v2 path drops a colliding injected header so the resolved credential wins its slot. The + v1 path applies extra_headers last, so without this it silently sends the injected value and the + upstream rejects a credential the gateway thought it had sent. + """ + client = MCPClient( + server_url="https://upstream.example.com/mcp", + auth_type=MCPAuth.oauth2, + auth_header_name="esb-oauth", + extra_headers={"esb-oauth": "Bearer injected", "X-Trace": "keep"}, + ) + client.update_auth_value("minted-token") + headers = client._get_auth_headers() + assert headers["esb-oauth"] == "Bearer minted-token" + assert headers["X-Trace"] == "keep" + + +def test_without_a_configured_slot_the_existing_precedence_is_unchanged(): + # extra_headers winning over authentication_token is long-standing v1 behavior; the fix above + # must apply only to the slot the operator explicitly named. + client = MCPClient( + server_url="https://upstream.example.com/mcp", + auth_type=MCPAuth.oauth2, + extra_headers={"Authorization": "Bearer injected"}, + ) + client.update_auth_value("minted-token") + assert client._get_auth_headers()["Authorization"] == "Bearer injected" + + +_REDIRECT_CASES = [ + ("https://upstream.example.com/mcp", "https://upstream.example.com/other"), # same origin + ("https://upstream.example.com/mcp", "https://upstream.example.com:443/other"), # explicit default port + ("https://upstream.example.com/mcp", "https://attacker.example.com/collect"), # different host + ("https://upstream.example.com/mcp", "http://upstream.example.com/collect"), # scheme downgrade + ("https://upstream.example.com/mcp", "https://upstream.example.com:8443/other"), # different port + ("https://upstream.example.com/mcp", "https://sub.upstream.example.com/x"), # different host + ("http://upstream.example.com/mcp", "https://upstream.example.com/other"), # http -> https upgrade + ("http://upstream.example.com/mcp", "http://upstream.example.com/other"), # same origin, plain http +] + + +@pytest.mark.parametrize("start,target", _REDIRECT_CASES) +@pytest.mark.asyncio +async def test_the_guard_agrees_with_httpx_about_authorization(start: str, target: str) -> None: + """Our custom slot must be dropped on exactly the redirects where httpx drops Authorization. + + The rule is mirrored rather than imported, so this drives real httpx and compares the two + outcomes. A future httpx that changes its redirect rule reds here instead of silently leaving + the custom slot forwarded where Authorization is not (or stripped where it is not needed). + """ + seen: "list[tuple[str, str, str]]" = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append( + ( + str(request.url), + request.headers.get("authorization", ""), + request.headers.get("esb-oauth", ""), + ) + ) + if str(request.url) == start: + return httpx.Response(302, headers={"Location": target}) + return httpx.Response(200) + + client = MCPClient(server_url=start, auth_type=MCPAuth.oauth2, auth_header_name="esb-oauth") + factory = client._create_httpx_client_factory() + async with factory(headers={"Authorization": "Bearer AUTH", "esb-oauth": "Bearer ESB"}, timeout=None) as http: + http._transport = httpx.MockTransport(handler) + await http.get(start) + + _url, authorization, esb = seen[-1] + assert (authorization == "") == (esb == ""), ( + f"httpx and the guard disagree for {target}: authorization={authorization!r} esb-oauth={esb!r}" + ) + + +def test_a_differently_cased_injected_header_cannot_shadow_the_slot() -> None: + # HTTP header names are case-insensitive and v2 drops the collision case-insensitively, so an + # exact-key check here would leave both spellings in the dict and let the injected value win. + client = MCPClient( + server_url="https://upstream.example.com/mcp", + auth_type=MCPAuth.oauth2, + auth_header_name="esb-oauth", + extra_headers={"ESB-OAuth": "Bearer injected", "X-Trace": "keep"}, + ) + client.update_auth_value("minted-token") + headers = client._get_auth_headers() + assert [v for k, v in headers.items() if k.lower() == "esb-oauth"] == ["Bearer minted-token"] + assert headers["X-Trace"] == "keep" diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_dynamic.py b/tests/test_litellm/integrations/otel/test_otel_v2_dynamic.py index 633be9f105f..1da8720d1aa 100644 --- a/tests/test_litellm/integrations/otel/test_otel_v2_dynamic.py +++ b/tests/test_litellm/integrations/otel/test_otel_v2_dynamic.py @@ -357,6 +357,92 @@ def test_release_without_eviction_keeps_provider_alive(monkeypatch): cache.release(None) # default-route release is a no-op +# --- per-request service.name routing from trusted key/team config --- # + + +def test_tenant_service_name_precedence_and_blanks(): + from litellm.integrations.otel.plumbing.routing import tenant_service_name + + assert tenant_service_name({"otel_service_name": "team-svc"}) == "team-svc" + assert tenant_service_name({"otel_service_name_override": "override", "otel_service_name": "base"}) == "override" + assert tenant_service_name({"otel_service_name": " "}) is None + assert tenant_service_name({"logging_setting": "x"}) is None + assert tenant_service_name(None) is None + + +def test_key_override_survives_team_metadata_merge(): + from litellm.integrations.otel.plumbing.routing import tenant_service_name + + # Request setup merges team metadata over key metadata (last writer wins), + # so a key keeps its own destination via ``otel_service_name_override``, + # which a team defining only ``otel_service_name`` never touches. + merged = {"otel_service_name_override": "key-svc"} + merged.update({"otel_service_name": "team-svc"}) + assert tenant_service_name(merged) == "key-svc" + + +def test_provider_cached_per_service_name(): + cache = _cache("otel") + default = NoOpTracer() + routed = cache.route_for(default, None, {"otel_service_name": "payments-gateway"}) + assert routed.tracer is not default + assert routed.detached is False # stays parented into the request trace + assert routed.provider is not None + assert routed.provider.resource.attributes["service.name"] == "payments-gateway" + cache.route_for(default, None, {"otel_service_name": "payments-gateway"}) + assert len(cache._providers) == 1 + cache.route_for(default, None, {"otel_service_name": "search-gateway"}) + assert len(cache._providers) == 2 + for provider in cache._providers.values(): + provider.shutdown() + + +def test_service_name_routed_span_carries_team_service_name(monkeypatch): + # The artifact the exporter receives: the finished span's Resource must + # carry the team's service.name, not the env-configured default. + monkeypatch.setenv("OTEL_SERVICE_NAME", "proxy-default") + cache = _cache("otel") + default = NoOpTracer() + route = cache.route_for(default, None, {"otel_service_name": "payments-gateway"}) + with route.tracer.start_as_current_span("chat gpt-4o-mini") as span: + pass + assert span.resource.attributes["service.name"] == "payments-gateway" + cache.release(route.provider) + + unrouted = cache.route_for(default, None, {"logging_setting": "x"}) + assert unrouted.tracer is default # env fallback: no scoped provider built + + +def test_client_dynamic_params_cannot_choose_service_name(): + # ``StandardCallbackDynamicParams`` is populated from client-supplied + # request metadata; the service name may only come from server-set + # key/team config (the ``auth_metadata`` argument). + cache = _cache("otel") + default = NoOpTracer() + assert cache.route_for(default, {"otel_service_name": "attacker"}).tracer is default + assert cache.route_for(default, {"otel_service_name_override": "attacker"}).tracer is default + assert cache._providers == {} + + +def test_service_name_override_leaves_exporters_untouched(): + cache = _cache( + "otel", + exporters=[ + ExporterSpec( + kind="otlp_http", + endpoint="http://collector:4318", + headers="x=base-collector", + owner=None, + ), + ], + ) + cfg = cache._routed_config({}, {}, None, "payments-gateway") + assert cfg.service_name == "payments-gateway" + (spec,) = cfg.exporters + assert spec.headers == "x=base-collector" + assert spec.endpoint == "http://collector:4318" + + # --- New Relic: per-team api-key header + fixed-table region endpoint --- # diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py index 455d84c764f..4973bda29e0 100644 --- a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py +++ b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py @@ -778,11 +778,15 @@ def test_mcp_span_roots_without_transport_or_propagated_context( @pytest.mark.parametrize("make_payload, span_name", _MCP_SPAN_CASES) -def test_mcp_span_parents_to_propagated_meta_trace_context(make_payload, span_name): +def test_mcp_span_links_propagated_meta_trace_context_and_nests_under_transport( + make_payload, span_name +): """When the client propagates W3C trace context in the request's - ``params._meta`` (SEP-414), the MCP span parents to it (one distributed trace) - and still links the transport span — never falling through to the - ambient/session span.""" + ``params._meta`` (SEP-414), the MCP span still nests under the gateway's own + transport span — one renderable trace — and records the client's context as a + span *link*. Parenting to the remote context instead would root the span in a + trace whose root span never reaches the gateway's tracing backend, leaving the + span unreachable from the trace view.""" logger, exporter = _logger() transport = logger._emitter.start_span( SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME @@ -801,12 +805,65 @@ def test_mcp_span_parents_to_propagated_meta_trace_context(make_payload, span_na reset_mcp_message_trace_carrier(token) transport.end() span = next(s for s in exporter.get_finished_spans() if s.name == span_name) - assert span.context.trace_id == 0x11111111111111111111111111111111 assert span.parent is not None - assert span.parent.span_id == 0x2222222222222222 - assert [link.context.span_id for link in span.links] == [ - transport.get_span_context().span_id + assert span.parent.span_id == transport.get_span_context().span_id + assert span.context.trace_id == transport.get_span_context().trace_id + assert [link.context.trace_id for link in span.links] == [ + 0x11111111111111111111111111111111 ] + assert [link.context.span_id for link in span.links] == [0x2222222222222222] + + +@pytest.mark.parametrize("make_payload, span_name", _MCP_SPAN_CASES) +def test_mcp_span_without_transport_roots_and_links_propagated_context( + make_payload, span_name +): + """With no transport span at all there is nothing of the gateway's to anchor + to, so the span starts its own root trace — and the client context stays a + span link there too, so the event keeps one shape everywhere.""" + logger, exporter = _logger() + token = set_mcp_message_trace_carrier( + {"traceparent": "00-11111111111111111111111111111111-2222222222222222-01"} + ) + try: + asyncio.run( + logger.async_log_success_event( + {"standard_logging_object": make_payload()}, None, None, None + ) + ) + finally: + reset_mcp_message_trace_carrier(token) + span = next(s for s in exporter.get_finished_spans() if s.name == span_name) + assert span.parent is None + assert span.context.trace_id != 0x11111111111111111111111111111111 + assert [link.context.span_id for link in span.links] == [0x2222222222222222] + + +def test_mcp_span_links_unsampled_client_traceparent(): + """A client traceparent with the sampled flag off ('-00') still yields a valid + remote context, so the link is recorded; the span's own recording follows the + transport's sampling decision, never the client's flag.""" + logger, exporter = _logger() + transport = logger._emitter.start_span( + SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME + ) + set_request_root_span(transport) + token = set_mcp_message_trace_carrier( + {"traceparent": "00-11111111111111111111111111111111-2222222222222222-00"} + ) + try: + asyncio.run( + logger.async_log_success_event( + {"standard_logging_object": _mcp_list_payload()}, None, None, None + ) + ) + finally: + reset_mcp_message_trace_carrier(token) + transport.end() + span = next(s for s in exporter.get_finished_spans() if s.name == "tools/list") + assert span.parent is not None + assert span.parent.span_id == transport.get_span_context().span_id + assert [link.context.span_id for link in span.links] == [0x2222222222222222] @pytest.mark.parametrize("make_payload, span_name", _MCP_SPAN_CASES) @@ -839,8 +896,11 @@ def test_mcp_span_ignores_client_supplied_baggage(make_payload, span_name): reset_mcp_message_trace_carrier(token) transport.end() span = next(s for s in exporter.get_finished_spans() if s.name == span_name) - # Trace context still honored: proves the carrier was processed, not dropped wholesale. - assert span.parent is not None and span.parent.span_id == 0x2222222222222222 + # Trace context still honored (as a link): proves the carrier was processed, + # not dropped wholesale. + assert [link.context.span_id for link in span.links] == [0x2222222222222222] + assert span.parent is not None + assert span.parent.span_id == transport.get_span_context().span_id # Identity is the authenticated payload's team, never the client's spoofed value. assert span.attributes[LiteLLM.TEAM_ID] == "t1" assert "litellm.metadata.user_api_key_user_id" not in span.attributes @@ -888,10 +948,10 @@ def test_mcp_span_malformed_traceparent_nests_under_transport(): assert span.links == () -def test_mcp_span_links_this_messages_transport_when_context_is_propagated(): - """On the semconv path the transport is recorded as a link, and that link must - point at the POST carrying this message too. Reading the stale session anchor - would attribute the tool call to whichever request opened the session.""" +def test_mcp_span_with_propagated_context_nests_under_this_messages_transport(): + """With client context propagated, the span must still anchor to the POST + carrying this message, not the stale session anchor — otherwise the tool call + is attributed to whichever request opened the session.""" logger, exporter = _logger() session_opener = logger._emitter.start_span( SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME @@ -916,10 +976,10 @@ def test_mcp_span_links_this_messages_transport_when_context_is_propagated(): session_opener.end() this_message.end() span = next(s for s in exporter.get_finished_spans() if s.name == "tools/list") - assert span.parent is not None and span.parent.span_id == 0x2222222222222222 - assert [link.context.span_id for link in span.links] == [ - this_message.get_span_context().span_id - ] + assert span.parent is not None + assert span.parent.span_id == this_message.get_span_context().span_id + assert span.context.trace_id == this_message.get_span_context().trace_id + assert [link.context.span_id for link in span.links] == [0x2222222222222222] def test_pre_call_idempotent_keeps_first_span(): diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py index cc9b311084e..baa72b5a7fe 100644 --- a/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py +++ b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py @@ -107,32 +107,29 @@ def test_registry_parent_integrity_no_orphans(): def test_registry_hierarchy_shape(): - # MCP roles have no in-process parent: per the MCP semconv they root (or adopt - # the client's propagated _meta context), so they sit alongside PROXY_REQUEST. - assert set(root_roles()) == { - SpanRole.PROXY_REQUEST, - SpanRole.MCP_TOOL_CALL, - SpanRole.MCP_LIST_TOOLS, - } + assert set(root_roles()) == {SpanRole.PROXY_REQUEST} # Guardrails parent to the request span, not the LLM call: a pre-call - # guardrail runs before the LLM call exists, so it's a sibling of it. + # guardrail runs before the LLM call exists, so it's a sibling of it. MCP + # spans nest under the transport span of the request carrying that message. assert set(child_roles(SpanRole.PROXY_REQUEST)) == { SpanRole.LLM_CALL, SpanRole.GUARDRAIL, SpanRole.DB_CALL, SpanRole.SERVICE, + SpanRole.MCP_TOOL_CALL, + SpanRole.MCP_LIST_TOOLS, } assert SPAN_REGISTRY[SpanRole.LLM_CALL].kind is LiteLLMSpanKind.CLIENT # The proxy is an MCP client to the upstream tool server: CLIENT span. Listing # tools is the same client relationship, so it's a CLIENT span too. assert SPAN_REGISTRY[SpanRole.MCP_TOOL_CALL].kind is LiteLLMSpanKind.CLIENT assert SPAN_REGISTRY[SpanRole.MCP_LIST_TOOLS].kind is LiteLLMSpanKind.CLIENT - # MCP spans don't nest under the transport: they link the PROXY_REQUEST span - # instead of parenting to it (OTel GenAI MCP semconv). - assert SPAN_REGISTRY[SpanRole.MCP_TOOL_CALL].parent is None - assert SPAN_REGISTRY[SpanRole.MCP_LIST_TOOLS].parent is None - assert SPAN_REGISTRY[SpanRole.MCP_TOOL_CALL].links is SpanRole.PROXY_REQUEST - assert SPAN_REGISTRY[SpanRole.MCP_LIST_TOOLS].links is SpanRole.PROXY_REQUEST + # MCP spans nest under the transport span of the request carrying that + # message (resolved per message at emit time); a client-propagated context + # becomes a span link to that remote context, which is not a registry role + # (SpanSpec declares no link field at all). + assert SPAN_REGISTRY[SpanRole.MCP_TOOL_CALL].parent is SpanRole.PROXY_REQUEST + assert SPAN_REGISTRY[SpanRole.MCP_LIST_TOOLS].parent is SpanRole.PROXY_REQUEST assert SPAN_REGISTRY[SpanRole.PROXY_REQUEST].kind is LiteLLMSpanKind.SERVER assert SPAN_REGISTRY[SpanRole.GUARDRAIL].parent is SpanRole.PROXY_REQUEST # An outbound datastore call is a CLIENT span; an internal service is INTERNAL. diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking_dict_safety.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking_dict_safety.py index 3a0a3574539..78bf9292ef5 100644 --- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking_dict_safety.py +++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking_dict_safety.py @@ -10,8 +10,8 @@ import pytest from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import ( StandardBuiltInToolCostTracking, - get_web_search_requests, ) +from litellm.litellm_core_utils.llm_cost_calc.utils import get_web_search_requests from litellm.types.utils import ModelResponse, ServerToolUse, Usage diff --git a/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py b/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py index 895044c8ad5..8e89180a9e4 100644 --- a/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py +++ b/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py @@ -1002,6 +1002,17 @@ def test_an_exception_without_a_status_is_still_a_connection_error(quiet_excepti ) +def test_an_unmapped_exception_with_no_model_or_provider_is_a_connection_error(quiet_exception_mapping): + with pytest.raises(litellm.APIConnectionError) as raised: + exception_type( + model=None, + original_exception=ValueError("boom"), + custom_llm_provider=None, + ) + + assert "boom" in raised.value.message + + CONTEXT_WINDOW_MESSAGE = "This model's maximum context length is 4096 tokens." CONTENT_POLICY_MESSAGE = ( '{"error": {"type": "invalid_request_error", "code": "content_policy_violation"}}' diff --git a/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py b/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py index 61b63e2b917..52e88db753a 100644 --- a/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py +++ b/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py @@ -2957,3 +2957,157 @@ async def test_log_messages_routes_async_logging_through_bounded_worker(): logging_obj.success_handler.assert_not_called() # the bare create_task path must no longer be used for success logging mock_create_task.assert_not_called() + + +@pytest.mark.asyncio +async def test_provider_config_path_captures_transcription_usage(): + """A transcription.completed event with usage from the provider transform must + land in the logged messages so realtime cost calculation can bill it.""" + from typing import Final + + from litellm.types.realtime import RealtimeInputAudioTranscriptionUsage, RealtimeResponseTypedDict + + client_ws: Final = MagicMock() + client_ws.send_text = AsyncMock() + backend_ws: Final = MagicMock() + backend_ws.send = AsyncMock() + logging_obj: Final = MagicMock() + + usage: Final[RealtimeInputAudioTranscriptionUsage] = { + "type": "tokens", + "input_tokens": 50, + "output_tokens": 6, + "total_tokens": 56, + "input_token_details": {"text_tokens": 0, "audio_tokens": 50}, + } + transform_output: Final[RealtimeResponseTypedDict] = { + "response": { + "type": "conversation.item.input_audio_transcription.completed", + "event_id": "event_1", + "transcript": "ahoy", + "item_id": "item_1", + "content_index": 0, + "usage": usage, + }, + "current_output_item_id": None, + "current_response_id": None, + "current_delta_chunks": None, + "current_conversation_id": None, + "current_item_chunks": None, + "current_delta_type": None, + "session_configuration_request": None, + } + provider_config: Final = MagicMock() + provider_config.transform_realtime_request = MagicMock(return_value=()) + provider_config.transform_realtime_response = MagicMock(return_value=transform_output) + + streaming: Final = RealTimeStreaming( + client_ws, + backend_ws, + logging_obj, + provider_config=provider_config, + model="gemini-3.5-transcribe-live", + ) + + await streaming._handle_provider_config_message("{}") + + usage_events: Final = tuple( + message + for message in streaming.messages + if isinstance(message, dict) + and message.get("type") == "conversation.item.input_audio_transcription.completed" + and message.get("usage") == usage + ) + assert len(usage_events) == 1 + + +@pytest.mark.asyncio +async def test_session_close_flushes_unbilled_transcription_usage(): + """Trailing audio appended after the last transcript frame must still be billed: + on session close the provider's unbilled estimate is flushed into the logged + messages before log_messages runs, and never forwarded to the client.""" + from typing import Final + + from litellm.types.realtime import RealtimeInputAudioTranscriptionUsage + + client_ws: Final = MagicMock() + client_ws.send_text = AsyncMock() + backend_ws: Final = MagicMock() + backend_ws.recv = AsyncMock(side_effect=ConnectionClosed(None, None)) + logging_obj: Final = MagicMock() + logging_obj.async_success_handler = AsyncMock() + logging_obj.success_handler = MagicMock() + + usage: Final[RealtimeInputAudioTranscriptionUsage] = { + "type": "tokens", + "input_tokens": 153, + "output_tokens": 18, + "total_tokens": 171, + "input_token_details": {"text_tokens": 0, "audio_tokens": 153}, + } + provider_config: Final = MagicMock() + provider_config.unbilled_usage_on_session_close = MagicMock(return_value=usage) + + streaming: Final = RealTimeStreaming( + client_ws, + backend_ws, + logging_obj, + provider_config=provider_config, + model="gemini-3.5-transcribe-live", + ) + logged_snapshots: Final[list[tuple]] = [] + + original_log_messages: Final = streaming.log_messages + + async def _snapshot_then_log(): + logged_snapshots.append(tuple(streaming.messages)) + await original_log_messages() + + streaming.log_messages = _snapshot_then_log + + await streaming.backend_to_client_send_messages() + + provider_config.unbilled_usage_on_session_close.assert_called_once_with("gemini-3.5-transcribe-live") + flushed: Final = tuple( + message + for message in streaming.messages + if isinstance(message, dict) + and message.get("type") == "conversation.item.input_audio_transcription.completed" + and message.get("usage") == usage + ) + assert len(flushed) == 1 + assert flushed[0] in logged_snapshots[0] + assert not client_ws.send_text.called + + +@pytest.mark.asyncio +async def test_session_close_flush_noop_without_unbilled_usage(): + """Everything already billed mid-stream: the session-close flush must not append + a duplicate transcription event.""" + from typing import Final + + client_ws: Final = MagicMock() + client_ws.send_text = AsyncMock() + backend_ws: Final = MagicMock() + backend_ws.recv = AsyncMock(side_effect=ConnectionClosed(None, None)) + logging_obj: Final = MagicMock() + logging_obj.async_success_handler = AsyncMock() + logging_obj.success_handler = MagicMock() + + provider_config: Final = MagicMock() + provider_config.unbilled_usage_on_session_close = MagicMock(return_value=None) + + streaming: Final = RealTimeStreaming( + client_ws, + backend_ws, + logging_obj, + provider_config=provider_config, + model="gemini-3.5-transcribe-live", + ) + + await streaming.backend_to_client_send_messages() + + assert not any( + isinstance(message, dict) and message.get("type") == "conversation.item.input_audio_transcription.completed" + for message in streaming.messages + ) diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py index b690b3448ec..5fc4a361e78 100644 --- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py +++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py @@ -17,7 +17,12 @@ from litellm.anthropic_interface import messages from litellm.integrations.custom_logger import CustomLogger from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler -from litellm.types.utils import Delta, ModelResponse, StreamingChoices +from litellm.types.utils import ( + Delta, + ModelResponse, + StandardLoggingPayloadErrorInformation, + StreamingChoices, +) def test_anthropic_experimental_pass_through_messages_handler(): @@ -1292,7 +1297,7 @@ class TestMessagesStreamingSuccessLogging: class _FailureCapture(CustomLogger): def __init__(self): super().__init__() - self.error_information: List[Dict[str, Any]] = [] + self.error_information: list[StandardLoggingPayloadErrorInformation] = [] async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): payload = kwargs.get("standard_logging_object") or {} diff --git a/tests/test_litellm/llms/anthropic/test_cost_calculation_dict_safety.py b/tests/test_litellm/llms/anthropic/test_cost_calculation_dict_safety.py index 27115ffe241..44b8bb3c9a2 100644 --- a/tests/test_litellm/llms/anthropic/test_cost_calculation_dict_safety.py +++ b/tests/test_litellm/llms/anthropic/test_cost_calculation_dict_safety.py @@ -8,10 +8,8 @@ See https://github.com/BerriAI/litellm/issues/26153. import pytest -from litellm.llms.anthropic.cost_calculation import ( - get_cost_for_anthropic_web_search, - get_web_search_requests, -) +from litellm.litellm_core_utils.llm_cost_calc.utils import get_web_search_requests +from litellm.llms.anthropic.cost_calculation import get_cost_for_anthropic_web_search from litellm.types.utils import ModelInfo, ServerToolUse diff --git a/tests/test_litellm/llms/bedrock/rerank/test_bedrock_rerank_header_forwarding.py b/tests/test_litellm/llms/bedrock/rerank/test_bedrock_rerank_header_forwarding.py index 253edad57e9..2ea61b5e978 100644 --- a/tests/test_litellm/llms/bedrock/rerank/test_bedrock_rerank_header_forwarding.py +++ b/tests/test_litellm/llms/bedrock/rerank/test_bedrock_rerank_header_forwarding.py @@ -12,6 +12,7 @@ import pytest import litellm from litellm.llms.bedrock.base_aws_llm import Boto3CredentialsInfo +from litellm.llms.bedrock.rerank.handler import BedrockRerankHandler from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler # Mock response for Bedrock rerank @@ -402,6 +403,66 @@ def test_bedrock_rerank_extra_headers_and_headers_merge(): pytest.fail(f"Failed to merge and forward headers: {str(e)}") +def test_bedrock_rerank_forwarded_headers_excluded_from_sigv4_signature(): + """ + A forwarded header like x-forwarded-for can be rewritten between LiteLLM + signing the request and AWS receiving it (e.g. by an intermediate load + balancer), which invalidates the signature if that header was part of + the signed set. It must still reach Bedrock, just unsigned. + """ + handler = BedrockRerankHandler() + + prepared_request = handler._prepare_request( + model="cohere.rerank-v3-5:0", + api_base=None, + extra_headers={"x-forwarded-for": "203.0.113.5"}, + data={"query": test_query, "documents": test_documents}, + optional_params={ + "aws_access_key_id": "test-access-key", + "aws_secret_access_key": "test-secret-key", + "aws_region_name": "us-east-1", + }, + ) + + headers = prepared_request["prepped"].headers + signed_headers = headers["Authorization"].split("SignedHeaders=")[1].split(",")[0].split(";") + + assert "x-forwarded-for" not in signed_headers, ( + f"x-forwarded-for must not be part of the SigV4 signature, got SignedHeaders={signed_headers}" + ) + assert headers["x-forwarded-for"] == "203.0.113.5", "forwarded header must still reach Bedrock, unsigned" + + +def test_bedrock_rerank_signs_with_sigv4_even_when_bedrock_api_key_is_set(monkeypatch): + """ + Bedrock API keys are only valid for Bedrock and Bedrock Runtime actions, not for + Agents for Amazon Bedrock Runtime ones. Rerank is served by bedrock-agent-runtime, + so it has to keep signing with SigV4 even when AWS_BEARER_TOKEN_BEDROCK is set. + """ + monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "test-bedrock-api-key") + + handler = BedrockRerankHandler() + + prepared_request = handler._prepare_request( + model="cohere.rerank-v3-5:0", + api_base=None, + extra_headers=None, + data={"query": test_query, "documents": test_documents}, + optional_params={ + "aws_access_key_id": "test-access-key", + "aws_secret_access_key": "test-secret-key", + "aws_region_name": "us-east-1", + }, + ) + + assert prepared_request["endpoint_url"].startswith("https://bedrock-agent-runtime.") + + authorization = prepared_request["prepped"].headers["Authorization"] + assert authorization.startswith("AWS4-HMAC-SHA256"), ( + f"rerank must sign with SigV4, got Authorization={authorization[:30]}" + ) + + @pytest.mark.asyncio async def test_bedrock_rerank_records_llm_api_duration(): """The bedrock rerank handler must feed httpx timing into the logging obj, so the diff --git a/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py b/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py index 1388073381e..5f12ae8566c 100644 --- a/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py +++ b/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py @@ -59,17 +59,17 @@ class GptProfile(NamedTuple): GPT_5_6_PROFILES = [ GptProfile( model_id="us.openai.gpt-5.6-sol", - input_cost=5.5e-06, input_cost_above_272k=1.1e-05, - cache_write=6.875e-06, cache_write_above_272k=1.375e-05, - cache_read=5.5e-07, cache_read_above_272k=1.1e-06, - output_cost=3.3e-05, output_cost_above_272k=4.95e-05, + input_cost=4.4e-06, input_cost_above_272k=8.8e-06, + cache_write=5.5e-06, cache_write_above_272k=1.1e-05, + cache_read=4.4e-07, cache_read_above_272k=8.8e-07, + output_cost=2.2e-05, output_cost_above_272k=3.3e-05, ), GptProfile( model_id="global.openai.gpt-5.6-sol", - input_cost=5e-06, input_cost_above_272k=1e-05, - cache_write=6.25e-06, cache_write_above_272k=1.25e-05, - cache_read=5e-07, cache_read_above_272k=1e-06, - output_cost=3e-05, output_cost_above_272k=4.5e-05, + input_cost=4e-06, input_cost_above_272k=8e-06, + cache_write=5e-06, cache_write_above_272k=1e-05, + cache_read=4e-07, cache_read_above_272k=8e-07, + output_cost=2e-05, output_cost_above_272k=3e-05, ), GptProfile( model_id="us.openai.gpt-5.6-terra", @@ -221,7 +221,7 @@ def test_bedrock_gpt_5_6_above_272k_tier_applies_to_cost(local_model_cost_map): custom_llm_provider="bedrock", ) - assert cost == pytest.approx((300000 * 1.1e-05) + (1000 * 4.95e-05), rel=1e-9) + assert cost == pytest.approx((300000 * 8.8e-06) + (1000 * 3.3e-05), rel=1e-9) def test_bedrock_gpt_5_6_bills_cache_read_tokens(local_model_cost_map): @@ -241,10 +241,10 @@ def test_bedrock_gpt_5_6_bills_cache_read_tokens(local_model_cost_map): custom_llm_provider="bedrock", ) - expected = (2 * 5.5e-06) + (15609 * 5.5e-07) + (5 * 3.3e-05) + expected = (2 * 4.4e-06) + (15609 * 4.4e-07) + (5 * 2.2e-05) assert cost == pytest.approx(expected, rel=1e-9) # Without cache_read_input_token_cost the cached prefix bills at zero. - assert cost > (15611 * 5.5e-06) * 0.1 + assert cost > (15611 * 4.4e-06) * 0.1 def test_bedrock_gpt_5_6_bills_cache_write_tokens(local_model_cost_map): @@ -263,7 +263,7 @@ def test_bedrock_gpt_5_6_bills_cache_write_tokens(local_model_cost_map): custom_llm_provider="bedrock", ) - expected = (2 * 5.5e-06) + (15609 * 6.875e-06) + (5 * 3.3e-05) + expected = (2 * 4.4e-06) + (15609 * 5.5e-06) + (5 * 2.2e-05) assert cost == pytest.approx(expected, rel=1e-9) diff --git a/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_responses_transformation.py b/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_responses_transformation.py index 6a6fb8e3730..a8a20670d4e 100644 --- a/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_responses_transformation.py +++ b/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_responses_transformation.py @@ -1683,10 +1683,19 @@ class TestBedrockMantleResponsesPricing: assert info["cache_read_input_token_cost"] == pytest.approx(2.75e-07) assert info["max_input_tokens"] == 1050000 + def test_gpt_5_6_cyber_pricing_and_mode(self, local_cost_map): + info = litellm.get_model_info("bedrock_mantle/openai.gpt-5.6-cyber") + assert info["mode"] == "responses" + assert info["input_cost_per_token"] == pytest.approx(1.375e-05) + assert info["cache_creation_input_token_cost"] == pytest.approx(1.71875e-05) + assert info["cache_read_input_token_cost"] == pytest.approx(1.375e-06) + assert info["output_cost_per_token"] == pytest.approx(8.25e-05) + assert info["max_input_tokens"] == 272000 + @pytest.mark.parametrize( "model, input_cost, cache_creation_cost, cache_read_cost, output_cost", [ - ("openai.gpt-5.6-sol", 5.5e-06, 6.875e-06, 5.5e-07, 3.3e-05), + ("openai.gpt-5.6-sol", 4.4e-06, 5.5e-06, 4.4e-07, 2.2e-05), ("openai.gpt-5.6-terra", 2.2e-06, 2.75e-06, 2.2e-07, 1.32e-05), ("openai.gpt-5.6-luna", 2.2e-07, 2.75e-07, 2.2e-08, 1.32e-06), ], @@ -1709,7 +1718,7 @@ class TestBedrockMantleResponsesPricing: @pytest.mark.parametrize( "model, input_cost, output_cost", [ - ("openai.gpt-5.6-sol", 5.5e-06, 3.3e-05), + ("openai.gpt-5.6-sol", 4.4e-06, 2.2e-05), ("openai.gpt-5.6-terra", 2.2e-06, 1.32e-05), ("openai.gpt-5.6-luna", 2.2e-07, 1.32e-06), ], diff --git a/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py b/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py index 21f047b753c..29ad8ee4b6e 100644 --- a/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py +++ b/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py @@ -61,6 +61,8 @@ PUBLISHED_DBU_PER_MILLION: Final = { "databricks/databricks-gemini-3-1-flash-lite": ("4.464", "26.786", "4.464", "0.446"), "databricks/databricks-gemini-2-5-pro": ("22.321", "178.571", "22.321", "2.232"), "databricks/databricks-gemini-2-5-flash": ("5.357", "44.643", "5.357", "0.536"), + "databricks/databricks-kimi-k3": ("42.857", "214.286", "42.857", "4.286"), + "databricks/databricks-glm-5-2": ("20.000", "62.857", "20.000", "3.714"), } PROMOTIONAL_DISCOUNT: Final = 0.80 PROMOTION_EXPIRES: Final = "2027-01-31" diff --git a/tests/test_litellm/llms/gemini/audio_transcription/__init__.py b/tests/test_litellm/llms/gemini/audio_transcription/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/test_litellm/llms/gemini/audio_transcription/test_gemini_audio_transcription_transformation.py b/tests/test_litellm/llms/gemini/audio_transcription/test_gemini_audio_transcription_transformation.py new file mode 100644 index 00000000000..fef037974a7 --- /dev/null +++ b/tests/test_litellm/llms/gemini/audio_transcription/test_gemini_audio_transcription_transformation.py @@ -0,0 +1,248 @@ +import base64 +import json + +import httpx +import pytest + + +import litellm +from litellm.llms.gemini.audio_transcription.transformation import ( + GeminiAudioTranscriptionConfig, +) +from litellm.llms.gemini.common_utils import GeminiError +from litellm.types.utils import LlmProviders +from litellm.utils import ProviderConfigManager + +AUDIO_BYTES = b"RIFF....WAVEfmt fake-wav-bytes" + +COMPLETED_RESPONSE = { + "id": "v1_abc123", + "status": "completed", + "usage": { + "total_tokens": 200, + "total_input_tokens": 200, + "input_tokens_by_modality": [ + {"modality": "text", "tokens": 1}, + {"modality": "audio", "tokens": 199}, + ], + "total_output_tokens": 0, + }, + "steps": [ + { + "type": "model_generation", + "content": [ + { + "type": "text", + "text": "Hello world.", + "annotations": [ + { + "type": "word_info", + "text": "Hello", + "speaker": "spk:0", + "start_offset": "0.100s", + "end_offset": "0.400s", + }, + { + "type": "word_info", + "text": "world.", + "speaker": "spk:1", + "start_offset": "0.500s", + "end_offset": "0.900s", + }, + ], + } + ], + } + ], +} + + +def make_response(payload): + return httpx.Response(200, json=payload, request=httpx.Request("POST", "https://example.test")) + + +@pytest.fixture +def config(): + return GeminiAudioTranscriptionConfig() + + +def test_provider_config_manager_returns_gemini_config(): + provider_config = ProviderConfigManager.get_provider_audio_transcription_config( + model="gemini-3.5-transcribe", provider=LlmProviders.GEMINI + ) + assert isinstance(provider_config, GeminiAudioTranscriptionConfig) + + +class TestValidateEnvironment: + def test_sets_api_key_and_revision_headers(self, config): + headers = config.validate_environment( + headers={}, + model="gemini-3.5-transcribe", + messages=[], + optional_params={}, + litellm_params={}, + api_key="test-key", + ) + assert headers["x-goog-api-key"] == "test-key" + assert headers["Api-Revision"] == "2026-05-20" + assert headers["Content-Type"] == "application/json" + + def test_missing_api_key_raises(self, config, monkeypatch): + monkeypatch.delenv("GOOGLE_API_KEY", raising=False) + monkeypatch.delenv("GEMINI_API_KEY", raising=False) + with pytest.raises(GeminiError) as excinfo: + config.validate_environment( + headers={}, + model="gemini-3.5-transcribe", + messages=[], + optional_params={}, + litellm_params={}, + ) + assert excinfo.value.status_code == 401 + + +class TestGetCompleteUrl: + def test_defaults_to_interactions_endpoint(self, config): + url = config.get_complete_url( + api_base=None, + api_key=None, + model="gemini-3.5-transcribe", + optional_params={}, + litellm_params={}, + ) + assert url == "https://generativelanguage.googleapis.com/v1beta/interactions" + + def test_api_base_override(self, config): + url = config.get_complete_url( + api_base="http://localhost:8080", + api_key=None, + model="gemini-3.5-transcribe", + optional_params={}, + litellm_params={}, + ) + assert url == "http://localhost:8080/v1beta/interactions" + + +class TestTransformRequest: + def test_builds_json_interaction_request(self, config): + request_data = config.transform_audio_transcription_request( + model="gemini/gemini-3.5-transcribe", + audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"), + optional_params={}, + litellm_params={}, + ) + assert request_data.files is None + assert json.loads(json.dumps(request_data.data)) == { + "model": "gemini-3.5-transcribe", + "input": [ + { + "type": "audio", + "data": base64.b64encode(AUDIO_BYTES).decode("utf-8"), + "mime_type": "audio/wav", + } + ], + } + + def test_language_maps_to_bcp47_language_codes(self, config): + request_data = config.transform_audio_transcription_request( + model="gemini-3.5-transcribe", + audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"), + optional_params={"language": "en"}, + litellm_params={}, + ) + transcription_config = request_data.data["generation_config"]["transcription_config"] + assert json.loads(json.dumps(transcription_config)) == {"language_codes": ["en-US"]} + + def test_word_timestamp_granularity_maps_to_verbatim_diarization_mode(self, config): + request_data = config.transform_audio_transcription_request( + model="gemini-3.5-transcribe", + audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"), + optional_params={"timestamp_granularities": ["word"]}, + litellm_params={}, + ) + transcription_config = request_data.data["generation_config"]["transcription_config"] + assert json.loads(json.dumps(transcription_config)) == { + "mode": { + "type": "verbatim", + "timestamp_granularities": ["word"], + "diarization_mode": "speaker", + } + } + + def test_segment_granularity_sends_no_mode(self, config): + request_data = config.transform_audio_transcription_request( + model="gemini-3.5-transcribe", + audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"), + optional_params={"timestamp_granularities": ["segment"]}, + litellm_params={}, + ) + assert "generation_config" not in request_data.data + + +class TestTransformResponse: + def test_completed_interaction_maps_to_transcription_response(self, config): + response = config.transform_audio_transcription_response(make_response(COMPLETED_RESPONSE)) + assert response.text == "Hello world." + assert response["task"] == "transcribe" + assert response["words"] == [ + {"word": "Hello", "start": 0.1, "end": 0.4, "speaker": "spk:0"}, + {"word": "world.", "start": 0.5, "end": 0.9, "speaker": "spk:1"}, + ] + assert response["duration"] == 0.9 + assert response.usage.input_tokens == 200 + assert response.usage.output_tokens == 0 + assert response.usage.total_tokens == 200 + assert response.usage.input_token_details.audio_tokens == 199 + assert response.usage.input_token_details.text_tokens == 1 + + def test_non_completed_status_raises(self, config): + with pytest.raises(GeminiError, match="did not complete"): + config.transform_audio_transcription_response( + make_response({**COMPLETED_RESPONSE, "status": "in_progress"}) + ) + + def test_non_json_response_raises(self, config): + raw = httpx.Response(200, text="oops", request=httpx.Request("POST", "https://example.test")) + with pytest.raises(GeminiError, match="non-JSON"): + config.transform_audio_transcription_response(raw) + + def test_word_without_offsets_survives(self, config): + payload = json.loads(json.dumps(COMPLETED_RESPONSE)) + payload["steps"][0]["content"][0]["annotations"] = [{"type": "word_info", "text": "Hello"}] + response = config.transform_audio_transcription_response(make_response(payload)) + assert response["words"] == [{"word": "Hello"}] + assert response.get("duration") is None + + +class TestCostRegression: + @pytest.fixture + def local_cost_map(self, monkeypatch): + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) + + def test_registry_entries(self, local_cost_map): + batch_entry = litellm.model_cost["gemini/gemini-3.5-transcribe"] + assert batch_entry["mode"] == "audio_transcription" + assert batch_entry["input_cost_per_audio_token"] == 2e-06 + assert batch_entry["input_cost_per_token"] == 2e-06 + assert batch_entry["output_cost_per_token"] == 1.2e-05 + assert batch_entry["supported_endpoints"] == ["/v1/audio/transcriptions"] + + live_entry = litellm.model_cost["gemini/gemini-3.5-transcribe-live"] + assert live_entry["mode"] == "audio_transcription" + assert live_entry["input_cost_per_audio_token"] == 3.5e-06 + assert live_entry["input_cost_per_token"] == 3.5e-06 + assert live_entry["output_cost_per_token"] == 2.1e-05 + assert live_entry["supported_endpoints"] == ["/v1/realtime"] + + def test_completion_cost_bills_provider_reported_tokens(self, config, local_cost_map): + payload = json.loads(json.dumps(COMPLETED_RESPONSE)) + payload["usage"]["total_output_tokens"] = 10 + payload["usage"]["total_tokens"] = 210 + response = config.transform_audio_transcription_response(make_response(payload)) + cost = litellm.completion_cost( + completion_response=response, + model="gemini/gemini-3.5-transcribe", + call_type="transcription", + ) + assert cost == pytest.approx(199 * 2e-06 + 1 * 2e-06 + 10 * 1.2e-05) diff --git a/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py b/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py index 42e330925a0..42994dbd2af 100644 --- a/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py +++ b/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py @@ -1864,3 +1864,282 @@ def test_map_openai_params_drops_stock_voice_case_insensitively(): passthrough = cfg.map_openai_params(optional_params={}, non_default_params={"voice": "Kore"}) assert passthrough["generationConfig"]["speechConfig"]["voiceConfig"]["prebuiltVoiceConfig"]["voiceName"] == "Kore" + + +@pytest.fixture(autouse=False) +def patch_gemini_transcribe_live_cost_map_entry(monkeypatch): + """Inject the gemini-3.5-transcribe-live registry entry locally. + + litellm.model_cost is fetched from main branch at import time, so in CI + the entry may not exist yet. Also stamp supported_output_modalities on a + chat model to prove mode, not output modalities, drives the discriminator. + """ + for m in ["gemini-3.5-transcribe-live", "gemini/gemini-3.5-transcribe-live"]: + entry = dict(litellm.model_cost.get(m, {})) + entry["mode"] = "audio_transcription" + monkeypatch.setitem(litellm.model_cost, m, entry) + chat_entry = dict(litellm.model_cost.get("gemini-2.5-flash", {})) + chat_entry["supported_output_modalities"] = ["text"] + monkeypatch.setitem(litellm.model_cost, "gemini-2.5-flash", chat_entry) + + +@pytest.mark.parametrize("model", ["gemini-3.5-transcribe-live", "gemini/gemini-3.5-transcribe-live"]) +def test_gemini_transcribe_live_eager_setup_uses_text_modality(model, patch_gemini_transcribe_live_cost_map_entry): + """Regression: the hardcoded AUDIO eager setup closes transcribe-live sessions with 1007.""" + config = GeminiRealtimeConfig() + + setup = json.loads(config.session_configuration_request(model))["setup"] + + assert setup["generationConfig"]["responseModalities"] == ["TEXT"] + + +def test_gemini_transcribe_live_session_update_defaults_to_text_modality( + patch_gemini_transcribe_live_cost_map_entry, +): + config = GeminiRealtimeConfig() + session_update = { + "type": "session.update", + "session": {"instructions": "Transcribe the audio."}, + } + + messages = config.transform_realtime_request( + json.dumps(session_update), + "gemini-3.5-transcribe-live", + session_configuration_request=None, + ) + + setup = json.loads(messages[0])["setup"] + assert setup["generationConfig"]["responseModalities"] == ["TEXT"] + + +@pytest.mark.parametrize("modalities", [["audio"], ["audio", "text"]]) +def test_gemini_transcribe_live_coerces_audio_modality_to_text(modalities, patch_gemini_transcribe_live_cost_map_entry): + config = GeminiRealtimeConfig() + session_update = { + "type": "session.update", + "session": {"modalities": modalities}, + } + + messages = config.transform_realtime_request( + json.dumps(session_update), + "gemini-3.5-transcribe-live", + session_configuration_request=None, + ) + + setup = json.loads(messages[0])["setup"] + assert setup["generationConfig"]["responseModalities"] == ["TEXT"] + + +def test_gemini_chat_model_with_text_output_modalities_keeps_audio_eager_setup( + patch_gemini_transcribe_live_cost_map_entry, +): + """Chat entries also declare supported_output_modalities ["text"]; they must keep AUDIO.""" + config = GeminiRealtimeConfig() + + setup = json.loads(config.session_configuration_request("gemini-2.5-flash"))["setup"] + + assert setup["generationConfig"]["responseModalities"] == ["AUDIO"] + + +def test_generation_complete_without_prior_delta_keeps_turn_usage(patch_gemini_audio_cost_map_entries): + from typing import Final + + from litellm.types.llms.gemini import BidiGenerateContentServerMessage + from litellm.types.realtime import RealtimeResponseTransformInput + + config: Final = GeminiRealtimeConfig() + turn_end_frame: Final[BidiGenerateContentServerMessage] = { + "serverContent": {"generationComplete": True, "turnComplete": True}, + "usageMetadata": { + "promptTokenCount": 200, + "totalTokenCount": 200, + "promptTokensDetails": [ + {"modality": "AUDIO", "tokenCount": 199}, + {"modality": "TEXT", "tokenCount": 1}, + ], + }, + } + transform_input: Final[RealtimeResponseTransformInput] = { + "session_configuration_request": None, + "current_output_item_id": None, + "current_response_id": None, + "current_conversation_id": None, + "current_delta_chunks": None, + "current_item_chunks": None, + "current_delta_type": None, + } + + result: Final = config.transform_realtime_response( + json.dumps(turn_end_frame), + "gemini-3.5-transcribe-live", + MagicMock(), + realtime_response_transform_input=transform_input, + ) + + done_events: Final = tuple(event for event in result["response"] if event["type"] == "response.done") + assert len(done_events) == 1 + assert done_events[0]["response"]["usage"]["input_tokens"] == 200 + + +def test_bare_generation_complete_without_prior_delta_is_dropped(patch_gemini_audio_cost_map_entries): + from typing import Final + + from litellm.types.llms.gemini import BidiGenerateContentServerMessage + from litellm.types.realtime import RealtimeResponseTransformInput + + config: Final = GeminiRealtimeConfig() + bare_frame: Final[BidiGenerateContentServerMessage] = {"serverContent": {"generationComplete": True}} + transform_input: Final[RealtimeResponseTransformInput] = { + "session_configuration_request": None, + "current_output_item_id": None, + "current_response_id": None, + "current_conversation_id": None, + "current_delta_chunks": None, + "current_item_chunks": None, + "current_delta_type": None, + } + + result: Final = config.transform_realtime_response( + json.dumps(bare_frame), + "gemini-3.5-transcribe-live", + MagicMock(), + realtime_response_transform_input=transform_input, + ) + + assert result["response"] == [] + + +def _input_audio_append_message(raw_byte_count: int) -> str: + import base64 + + return json.dumps( + {"type": "input_audio_buffer.append", "audio": base64.b64encode(b"\x00" * raw_byte_count).decode()} + ) + + +def test_transcribe_live_completed_event_carries_estimated_usage(patch_gemini_transcribe_live_cost_map_entry): + """Gemini Live sends no usageMetadata for transcribe sessions, so LiteLLM bills + from streamed audio duration at Google's published estimate (25 audio tok/sec in, + 175 text tok/min out): 96000 pcm16 bytes = 2s at 24kHz -> 50 in / 6 out.""" + from typing import Final + + from litellm.types.llms.gemini import BidiGenerateContentServerMessage + from litellm.types.realtime import RealtimeInputAudioTranscriptionUsage, RealtimeResponseTransformInput + + config: Final = GeminiRealtimeConfig() + config.transform_realtime_request(_input_audio_append_message(96000), "gemini-3.5-transcribe-live") + + transcript_frame: Final[BidiGenerateContentServerMessage] = { + "serverContent": {"inputTranscription": {"text": "ahoy there"}} + } + transform_input: Final[RealtimeResponseTransformInput] = { + "session_configuration_request": None, + "current_output_item_id": None, + "current_response_id": None, + "current_conversation_id": None, + "current_delta_chunks": None, + "current_item_chunks": None, + "current_delta_type": None, + } + + result: Final = config.transform_realtime_response( + json.dumps(transcript_frame), + "gemini-3.5-transcribe-live", + MagicMock(), + realtime_response_transform_input=transform_input, + ) + + completed: Final = tuple( + event + for event in result["response"] + if event["type"] == "conversation.item.input_audio_transcription.completed" + ) + assert len(completed) == 1 + assert completed[0]["transcript"] == "ahoy there" + expected_usage: Final[RealtimeInputAudioTranscriptionUsage] = { + "type": "tokens", + "input_tokens": 50, + "output_tokens": 6, + "total_tokens": 56, + "input_token_details": {"text_tokens": 0, "audio_tokens": 50}, + } + assert completed[0]["usage"] == expected_usage + + second: Final = config.transform_realtime_response( + json.dumps(transcript_frame), + "gemini-3.5-transcribe-live", + MagicMock(), + realtime_response_transform_input=transform_input, + ) + second_completed: Final = tuple( + event + for event in second["response"] + if event["type"] == "conversation.item.input_audio_transcription.completed" + ) + assert len(second_completed) == 1 + assert "usage" not in second_completed[0] + + +def test_non_transcription_live_model_completed_event_has_no_usage(patch_gemini_audio_cost_map_entries): + """Conversational Live models get their audio tokens from usageMetadata via + response.done; attaching estimated usage to their transcription events would + double-bill, so the estimate is gated to audio_transcription-mode models.""" + from typing import Final + + from litellm.types.llms.gemini import BidiGenerateContentServerMessage + from litellm.types.realtime import RealtimeResponseTransformInput + + config: Final = GeminiRealtimeConfig() + config.transform_realtime_request(_input_audio_append_message(96000), "gemini-3.1-flash-live-preview") + + transcript_frame: Final[BidiGenerateContentServerMessage] = { + "serverContent": {"inputTranscription": {"text": "ahoy there"}} + } + transform_input: Final[RealtimeResponseTransformInput] = { + "session_configuration_request": None, + "current_output_item_id": None, + "current_response_id": None, + "current_conversation_id": None, + "current_delta_chunks": None, + "current_item_chunks": None, + "current_delta_type": None, + } + + result: Final = config.transform_realtime_response( + json.dumps(transcript_frame), + "gemini-3.1-flash-live-preview", + MagicMock(), + realtime_response_transform_input=transform_input, + ) + + completed: Final = tuple( + event + for event in result["response"] + if event["type"] == "conversation.item.input_audio_transcription.completed" + ) + assert len(completed) == 1 + assert "usage" not in completed[0] + + +def test_unbilled_usage_on_session_close_flushes_trailing_audio(patch_gemini_transcribe_live_cost_map_entry): + """Audio appended after the last transcript frame is still unbilled when the + session closes; the session-close hook must hand back the estimate exactly once + so the streaming layer can bill it (144000 pcm16 bytes = 3s -> 75 in / 9 out).""" + from typing import Final + + from litellm.types.realtime import RealtimeInputAudioTranscriptionUsage + + config: Final = GeminiRealtimeConfig() + config.transform_realtime_request(_input_audio_append_message(144000), "gemini-3.5-transcribe-live") + + usage: Final = config.unbilled_usage_on_session_close("gemini-3.5-transcribe-live") + + expected: Final[RealtimeInputAudioTranscriptionUsage] = { + "type": "tokens", + "input_tokens": 75, + "output_tokens": 9, + "total_tokens": 84, + "input_token_details": {"text_tokens": 0, "audio_tokens": 75}, + } + assert usage == expected + assert config.unbilled_usage_on_session_close("gemini-3.5-transcribe-live") is None diff --git a/tests/test_litellm/llms/together_ai/chat/test_together_ai_chat_transformation.py b/tests/test_litellm/llms/together_ai/chat/test_together_ai_chat_transformation.py index bee8ab3a9ac..6b803578067 100644 --- a/tests/test_litellm/llms/together_ai/chat/test_together_ai_chat_transformation.py +++ b/tests/test_litellm/llms/together_ai/chat/test_together_ai_chat_transformation.py @@ -18,8 +18,14 @@ from litellm.types.utils import LlmProviders, ModelResponse TOOL_CALLING_MODEL = "openai/gpt-oss-20b" REASONING_MODEL = "deepseek-ai/DeepSeek-V3.1" +PLAIN_MODEL = "Qwen/Qwen3-235B-A22B-fp8-tput" UNMAPPED_MODEL = "example-org/brand-new-model" NO_TOOLS_MODEL = "example-org/no-tools-model" +ADJUSTABLE_REASONING_MODEL = "openai/gpt-oss-120b" +HYBRID_REASONING_MODEL = "Qwen/Qwen3.5-9B" +HIGH_MAX_REASONING_MODEL = "deepseek-ai/DeepSeek-V4-Pro" +REGISTRY_FLAGGED_REASONING_MODEL = "zai-org/GLM-4.6" +NON_REASONING_MODEL = "meta-llama/Llama-3.3-70B-Instruct-Turbo" NO_SCHEMA_MODEL = "example-org/no-schema-model" TOOL_PARAMS = ("tools", "tool_choice", "function_call") @@ -39,6 +45,15 @@ JSON_SCHEMA_RESPONSE_FORMAT = { REGEX_RESPONSE_FORMAT = {"type": "regex", "pattern": "(positive|neutral|negative)"} +def _map_reasoning_effort(model: str, effort: str) -> dict: + return TogetherAIChatConfig().map_openai_params( + non_default_params={"reasoning_effort": effort}, + optional_params={}, + model=model, + drop_params=False, + ) + + @pytest.fixture(autouse=True) def force_local_model_cost(monkeypatch): monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") @@ -191,6 +206,116 @@ def test_map_openai_params_schema_model_passes_response_format_through(response_ assert mapped["response_format"] == response_format +@pytest.mark.parametrize( + "model", + [ADJUSTABLE_REASONING_MODEL, HYBRID_REASONING_MODEL, HIGH_MAX_REASONING_MODEL, REGISTRY_FLAGGED_REASONING_MODEL], +) +def test_supported_params_includes_reasoning_effort_for_reasoning_models(model): + supported = TogetherAIChatConfig().get_supported_openai_params(model=model) + + assert "reasoning_effort" in supported + + +@pytest.mark.parametrize("model", [NON_REASONING_MODEL, PLAIN_MODEL]) +def test_supported_params_excludes_reasoning_effort_for_non_reasoning_models(model): + supported = TogetherAIChatConfig().get_supported_openai_params(model=model) + + assert "reasoning_effort" not in supported + + +@pytest.mark.parametrize( + "effort, expected", + [("low", "low"), ("medium", "medium"), ("high", "high"), ("minimal", "low"), ("xhigh", "high"), ("max", "high")], +) +def test_adjustable_model_translates_reasoning_effort(effort, expected): + mapped = _map_reasoning_effort(ADJUSTABLE_REASONING_MODEL, effort) + + assert mapped["reasoning_effort"] == expected + assert "reasoning" not in mapped + + +def test_adjustable_model_cannot_disable_reasoning_so_none_becomes_low(): + mapped = _map_reasoning_effort(ADJUSTABLE_REASONING_MODEL, "none") + + assert mapped["reasoning_effort"] == "low" + assert "reasoning" not in mapped + + +@pytest.mark.parametrize( + "effort, expected", + [("low", "low"), ("medium", "medium"), ("high", "high"), ("minimal", "low"), ("xhigh", "high"), ("max", "high")], +) +def test_hybrid_model_translates_reasoning_effort(effort, expected): + mapped = _map_reasoning_effort(HYBRID_REASONING_MODEL, effort) + + assert mapped["reasoning_effort"] == expected + assert "reasoning" not in mapped + + +@pytest.mark.parametrize("model", [HYBRID_REASONING_MODEL, HIGH_MAX_REASONING_MODEL, REGISTRY_FLAGGED_REASONING_MODEL]) +def test_reasoning_effort_none_becomes_reasoning_toggle(model): + mapped = _map_reasoning_effort(model, "none") + + assert mapped["reasoning"] == {"enabled": False} + assert "reasoning_effort" not in mapped + + +def test_reasoning_effort_none_does_not_clobber_user_reasoning(): + mapped = TogetherAIChatConfig().map_openai_params( + non_default_params={"reasoning_effort": "none"}, + optional_params={"reasoning": {"enabled": True}}, + model=HYBRID_REASONING_MODEL, + drop_params=False, + ) + + assert mapped["reasoning"] == {"enabled": True} + assert "reasoning_effort" not in mapped + + +@pytest.mark.parametrize( + "effort, expected", + [("minimal", "high"), ("low", "high"), ("medium", "high"), ("high", "high"), ("xhigh", "max"), ("max", "max")], +) +def test_deepseek_v4_pro_remaps_to_high_max(effort, expected): + mapped = _map_reasoning_effort(HIGH_MAX_REASONING_MODEL, effort) + + assert mapped["reasoning_effort"] == expected + + +def test_deepseek_v4_pro_dated_variant_remaps_via_prefix(): + mapped = _map_reasoning_effort(f"{HIGH_MAX_REASONING_MODEL}-0813", "low") + + assert mapped["reasoning_effort"] == "high" + + +@pytest.mark.parametrize("model", [ADJUSTABLE_REASONING_MODEL, HYBRID_REASONING_MODEL, HIGH_MAX_REASONING_MODEL]) +def test_reasoning_effort_default_is_dropped(model): + mapped = _map_reasoning_effort(model, "default") + + assert "reasoning_effort" not in mapped + assert "reasoning" not in mapped + + +def test_get_optional_params_translates_reasoning_effort_for_together(): + optional_params = litellm.get_optional_params( + model=ADJUSTABLE_REASONING_MODEL, + custom_llm_provider="together_ai", + reasoning_effort="max", + ) + + assert optional_params["reasoning_effort"] == "high" + + +def test_get_optional_params_rejects_reasoning_effort_for_non_reasoning_together_model(): + with pytest.raises(litellm.UnsupportedParamsError): + litellm.get_optional_params( + model=NON_REASONING_MODEL, + custom_llm_provider="together_ai", + reasoning_effort="low", + drop_params=False, + ) + + @pytest.mark.parametrize("drop_params", [False, True]) def test_map_openai_params_unmapped_model_passes_response_format_through(drop_params, together_warning_log): mapped = TogetherAIChatConfig().map_openai_params( diff --git a/tests/test_litellm/llms/xai/test_xai_model_registry.py b/tests/test_litellm/llms/xai/test_xai_model_registry.py new file mode 100644 index 00000000000..25b2002968d --- /dev/null +++ b/tests/test_litellm/llms/xai/test_xai_model_registry.py @@ -0,0 +1,75 @@ +""" +Registry regression tests for xAI entries in the model cost map. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).parents[4] +PRICES_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PRICES_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +# Retired by xAI and no longer served: requests to these slugs 404 rather than +# redirecting, and they are absent from https://docs.x.ai/docs/models +RETIRED_MODELS = ( + "xai/grok-2", + "xai/grok-2-1212", + "xai/grok-2-latest", + "xai/grok-2-vision", + "xai/grok-2-vision-1212", + "xai/grok-2-vision-latest", + "xai/grok-beta", + "xai/grok-vision-beta", +) + +# https://docs.x.ai/developers/model-capabilities/text/multi-agent +# "The multi-agent model does not work with the OpenAI Chat Completions API." +RESPONSES_ONLY_MODELS = ( + "xai/grok-4.20-multi-agent-0309", + "xai/grok-4.20-multi-agent-beta-0309", +) + +MAP_PATHS = (PRICES_PATH, BACKUP_PRICES_PATH) + + +@pytest.fixture(scope="module", params=[p.name for p in MAP_PATHS]) +def cost_map(request: pytest.FixtureRequest) -> dict: + path = next(p for p in MAP_PATHS if p.name == request.param) + return json.loads(path.read_text(encoding="utf-8")) + + +@pytest.mark.parametrize("model", RETIRED_MODELS) +def test_retired_xai_models_are_not_advertised(cost_map: dict, model: str): + assert model not in cost_map + + +@pytest.mark.parametrize("model", RESPONSES_ONLY_MODELS) +def test_multi_agent_models_are_responses_only(cost_map: dict, model: str): + entry = cost_map[model] + assert entry["supported_endpoints"] == ["/v1/responses"] + assert entry["mode"] == "responses" + assert "/v1/chat/completions" not in entry["supported_endpoints"] + + +def test_surviving_xai_chat_models_still_serve_chat_completions(cost_map: dict): + """Guard against the removal above over-reaching into live models.""" + chat_models = [ + key + for key, value in cost_map.items() + if isinstance(value, dict) and value.get("litellm_provider") == "xai" and value.get("mode") == "chat" + ] + assert "xai/grok-4.3" in chat_models + assert "xai/grok-4.6" in chat_models + assert not any(key.startswith("xai/grok-2") for key in chat_models) + + +def test_both_cost_maps_agree_on_xai_entries(): + prices = json.loads(PRICES_PATH.read_text(encoding="utf-8")) + backup = json.loads(BACKUP_PRICES_PATH.read_text(encoding="utf-8")) + xai_keys = {k for k, v in prices.items() if isinstance(v, dict) and v.get("litellm_provider") == "xai"} + assert xai_keys + assert {k: prices[k] for k in xai_keys} == {k: backup[k] for k in xai_keys} diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.py index 0020dbf8d61..c667db7f07c 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.py @@ -10,6 +10,7 @@ from types import SimpleNamespace import pytest from fastapi import HTTPException +from pydantic import ValidationError from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import ( oauth_protected_resource_path, @@ -598,3 +599,92 @@ def test_client_credentials_uses_admin_entered_token_url_when_issuer_yield_empti assert spec is not None assert isinstance(spec.config, ClientCredentialsConfig) assert spec.config.token_url == "https://idp.example.com/token" + + +_M2M_FIELDS = dict( + auth_type=MCPAuth.oauth2, + oauth2_flow="client_credentials", + client_id="cid", + client_secret="csec", + token_url="https://idp.example.com/token", +) +_OBO_FIELDS = dict( + auth_type=MCPAuth.oauth2_token_exchange, + client_id="cid", + client_secret="csec", + token_exchange_endpoint="https://idp.example.com/token", +) +_ID_JAG_FIELDS = dict( + auth_type=MCPAuth.oauth2_id_jag, + client_id="cid", + client_secret="csec", + token_exchange_endpoint="https://idp.example.com/token", + id_jag_resource_token_endpoint="https://mcp-as.example.com/token", + audience="api://mcp", +) +_AUTHZ_CODE_FIELDS = dict(auth_type=MCPAuth.oauth2, url="https://up.example.com/mcp") +_STATIC_FIELDS = dict(auth_type=MCPAuth.bearer_token, authentication_token="static-tok") + +_ARM_FIELDS = ( + ("client_credentials", _M2M_FIELDS), + ("token_exchange", _OBO_FIELDS), + ("id_jag", _ID_JAG_FIELDS), + ("authorization_code", _AUTHZ_CODE_FIELDS), + ("api_key", _STATIC_FIELDS), +) + + +@pytest.mark.parametrize("name,fields", _ARM_FIELDS, ids=[n for n, _ in _ARM_FIELDS]) +def test_upstream_token_header_reaches_every_arms_config(name, fields): + # to_server_spec builds each arm's config from a hand-written kwargs list, so an arm that + # forgets to read the field fails silently: the server keeps writing to Authorization. + spec = to_server_spec(_server(upstream_token_header="esb-oauth", **fields)) + assert spec is not None + assert spec.config.header_name == "esb-oauth" + + +@pytest.mark.parametrize("name,fields", _ARM_FIELDS, ids=[n for n, _ in _ARM_FIELDS]) +def test_omitting_the_field_keeps_each_arms_shipped_default(name, fields): + spec = to_server_spec(_server(**fields)) + assert spec is not None + assert spec.config.header_name == "Authorization" + + +def test_api_key_scheme_default_survives_when_the_field_is_unset(): + spec = to_server_spec(_server(auth_type=MCPAuth.api_key, authentication_token="k")) + assert spec is not None + assert spec.config.header_name == "X-API-Key" + assert spec.config.value_prefix == "" + + +def test_the_field_overrides_the_api_key_scheme_default(): + spec = to_server_spec(_server(auth_type=MCPAuth.api_key, authentication_token="k", upstream_token_header="X-Esb")) + assert spec is not None + assert spec.config.header_name == "X-Esb" + + +@pytest.mark.parametrize("bad", ["with space", "has:colon", "trailing\r\nX-Injected", 'quoted"name']) +def test_a_malformed_header_name_is_refused_when_the_server_is_built(bad): + """Validation belongs at ingestion, not at spec building. Raising inside to_server_spec would + abort the whole aggregate tools/list, so one mistyped server would silently empty the tool list + for every other server too. Refusing at MCPServer construction fails the config load loudly + instead, and means no malformed value can ever reach an arm. + """ + with pytest.raises(ValidationError): + _server(upstream_token_header=bad, **_M2M_FIELDS) + + +def test_a_valid_header_name_is_trimmed_at_ingestion(): + assert _server(upstream_token_header=" esb-oauth ", **_M2M_FIELDS).upstream_token_header == "esb-oauth" + + +@pytest.mark.parametrize("blank", ["", " ", "\t"]) +def test_a_blank_header_name_means_unset_rather_than_an_error(blank): + """The management API treats a blank as "not supplied" and stores it, so raising here made every + later rebuild of that server 500 instead of falling back to the default Authorization behavior. + """ + server = _server(upstream_token_header=blank, **_M2M_FIELDS) + assert server.upstream_token_header is None + spec = to_server_spec(server) + assert spec is not None + assert spec.config.header_name == "Authorization" diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_bridge_credentials.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_bridge_credentials.py index 753a3d6a942..f8fb22469f1 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_bridge_credentials.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_bridge_credentials.py @@ -10,6 +10,7 @@ through the consumer; and no path leaks the upstream token in a repr. from datetime import datetime, timedelta, timezone +import pytest from pydantic import SecretStr from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import ( @@ -188,6 +189,31 @@ def test_resolve_strips_optional_bearer_scheme_before_detection(): assert prefixed.upstream_authorization.get_secret_value() == bare.upstream_authorization.get_secret_value() +@pytest.mark.parametrize("token_type", ("bearer", "BEARER", "beArEr")) +def test_resolve_canonicalizes_case_insensitive_bearer_token_type(token_type: str): + keys = envelope_keys_from_master_key(_MASTER_KEY) + grant = UpstreamTokenGrant(access_token=SecretStr(_ACCESS_TOKEN), token_type=token_type, expires_in=600) + sealed = mint_envelope(_IDENTITY, grant, keys, _NOW) + assert isinstance(sealed, SealedEnvelope) + + result = resolve_bridge_envelope(sealed.token.get_secret_value(), keys, _NOW, _SERVER_ID) + + assert isinstance(result, BridgeEnvelopeAdmitted) + assert result.upstream_authorization.get_secret_value() == f"Bearer {_ACCESS_TOKEN}" + + +def test_resolve_preserves_non_bearer_token_type(): + keys = envelope_keys_from_master_key(_MASTER_KEY) + grant = UpstreamTokenGrant(access_token=SecretStr(_ACCESS_TOKEN), token_type="DPoP", expires_in=600) + sealed = mint_envelope(_IDENTITY, grant, keys, _NOW) + assert isinstance(sealed, SealedEnvelope) + + result = resolve_bridge_envelope(sealed.token.get_secret_value(), keys, _NOW, _SERVER_ID) + + assert isinstance(result, BridgeEnvelopeAdmitted) + assert result.upstream_authorization.get_secret_value() == f"DPoP {_ACCESS_TOKEN}" + + def test_resolve_expired_envelope_is_invalid_not_admitted(): keys = envelope_keys_from_master_key(_MASTER_KEY) token = _sealed_token(keys, now=_NOW) diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_client_credentials.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_client_credentials.py index a5d17428b37..010e7e14d39 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_client_credentials.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_client_credentials.py @@ -341,7 +341,7 @@ async def test_bearer_auth_sends_the_token_and_leaves_a_success_alone(): async def refetch(failed: str) -> "str | None": raise AssertionError("must not refetch on success") - auth = ClientCredentialsBearerAuth("m2m-token", refetch) + auth = ClientCredentialsBearerAuth("m2m-token", refetch, ClientCredentialsConfig()) async with httpx.AsyncClient(transport=transport, auth=auth) as client: response = await client.get("https://upstream.example.com/mcp") assert response.status_code == 200 @@ -357,7 +357,7 @@ async def test_bearer_auth_retries_a_401_once_with_a_fresh_token(): refetched.append(failed) return "fresh-token" - auth = ClientCredentialsBearerAuth("stale-token", refetch) + auth = ClientCredentialsBearerAuth("stale-token", refetch, ClientCredentialsConfig()) async with httpx.AsyncClient(transport=transport, auth=auth) as client: response = await client.get("https://upstream.example.com/mcp") assert response.status_code == 200 @@ -377,7 +377,7 @@ async def test_bearer_auth_remembers_the_rotated_token_for_later_requests(): refetched.append(failed) return "fresh-token" - auth = ClientCredentialsBearerAuth("stale-token", refetch) + auth = ClientCredentialsBearerAuth("stale-token", refetch, ClientCredentialsConfig()) async with httpx.AsyncClient(transport=transport, auth=auth) as client: first = await client.get("https://upstream.example.com/mcp") second = await client.get("https://upstream.example.com/mcp") @@ -393,7 +393,7 @@ async def test_bearer_auth_surfaces_the_401_when_the_refetch_fails(): async def refetch(failed: str) -> "str | None": return None - auth = ClientCredentialsBearerAuth("stale-token", refetch) + auth = ClientCredentialsBearerAuth("stale-token", refetch, ClientCredentialsConfig()) async with httpx.AsyncClient(transport=transport, auth=auth) as client: response = await client.get("https://upstream.example.com/mcp") assert response.status_code == 401 @@ -409,7 +409,7 @@ async def test_bearer_auth_gives_up_after_a_second_401(): refetched.append(failed) return "fresh-token" - auth = ClientCredentialsBearerAuth("stale-token", refetch) + auth = ClientCredentialsBearerAuth("stale-token", refetch, ClientCredentialsConfig()) async with httpx.AsyncClient(transport=transport, auth=auth) as client: response = await client.get("https://upstream.example.com/mcp") assert response.status_code == 401 @@ -421,7 +421,60 @@ def test_bearer_auth_rejects_sync_clients(): async def refetch(failed: str) -> "str | None": return None - auth = ClientCredentialsBearerAuth("token", refetch) + auth = ClientCredentialsBearerAuth("token", refetch, ClientCredentialsConfig()) with httpx.Client(transport=httpx.MockTransport(lambda request: httpx.Response(200)), auth=auth) as client: with pytest.raises(RuntimeError): client.get("https://upstream.example.com/mcp") + + +@pytest.mark.asyncio +async def test_bearer_auth_writes_the_minted_token_to_the_configured_header(): + seen: "list[dict[str, str]]" = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(dict(request.headers)) + return httpx.Response(200) + + async def refetch(failed: str) -> "str | None": + raise AssertionError("must not refetch on success") + + auth = ClientCredentialsBearerAuth("m2m-token", refetch, ClientCredentialsConfig(header_name="esb-oauth")) + async with httpx.AsyncClient(transport=httpx.MockTransport(handler), auth=auth) as client: + await client.get("https://upstream.example.com/mcp") + assert seen[0]["esb-oauth"] == "Bearer m2m-token" + assert "authorization" not in seen[0] + + +@pytest.mark.asyncio +async def test_the_401_refetch_retry_also_targets_the_configured_header(): + # The retry is a SECOND write of the credential. Honoring the carrier only on the first write + # would silently send the fresh token to Authorization, so the ESB rejects every recovered + # request while the first attempt looked correct. + seen: "list[dict[str, str]]" = [] + responses = [httpx.Response(401), httpx.Response(200)] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(dict(request.headers)) + return responses[min(len(seen) - 1, len(responses) - 1)] + + async def refetch(failed: str) -> "str | None": + return "fresh-token" + + auth = ClientCredentialsBearerAuth("stale-token", refetch, ClientCredentialsConfig(header_name="esb-oauth")) + async with httpx.AsyncClient(transport=httpx.MockTransport(handler), auth=auth) as client: + response = await client.get("https://upstream.example.com/mcp") + assert response.status_code == 200 + assert [h["esb-oauth"] for h in seen] == ["Bearer stale-token", "Bearer fresh-token"] + assert all("authorization" not in h for h in seen) + + +@pytest.mark.asyncio +async def test_bearer_auth_advertises_the_header_it_will_occupy(): + # _resolve_v2_auth reads header_name off the auth object to decide which injected header + # conflicts; an auth object that lies about its slot would drop the wrong one. + async def refetch(failed: str) -> "str | None": + return None + + assert ClientCredentialsBearerAuth("t", refetch, ClientCredentialsConfig()).header_name == "Authorization" + default_carrier = ClientCredentialsConfig(header_name="esb-oauth") + assert ClientCredentialsBearerAuth("t", refetch, default_carrier).header_name == "esb-oauth" diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.py index 0d130767bd5..9d63e8c2c1c 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.py @@ -1033,3 +1033,70 @@ async def test_invalidate_credentials_for_id_jag_is_a_noop_without_a_caller_toke assert isinstance(first, Ok) and isinstance(second, Ok) assert _emitted(second.ok)["Authorization"] == "Bearer cached-bearer" assert len(endpoint.calls) == 2 + + +async def _resolve_with_carrier(kind: str, header: str): + """Resolve one minted-token arm whose config targets ``header``.""" + if kind == "client_credentials": + source = _FakeM2MSource(Ok(OAuthToken(access_token="minted"))) + config = _M2M.model_copy(update={"header_name": header}) + provider = UpstreamCredentialProvider(client_credentials_source=source) + return await provider.resolve_credentials(_SUBJECT, _spec(config)) + if kind == "token_exchange": + exchanger = _FakeExchanger(Ok(OAuthToken(access_token="minted"))) + config = _OBO.model_copy(update={"header_name": header}) + subject = Subject(tenant_id="acme", subject_id="alice", inbound_token=SecretStr("caller-jwt")) + provider = UpstreamCredentialProvider(token_exchanger=exchanger) + return await provider.resolve_credentials(subject, _spec(config)) + if kind == "authorization_code": + store = _FakeTokenStore({("alice", "s"): OAuthToken(access_token="minted")}) + provider = UpstreamCredentialProvider(oauth_token_store=store) + return await provider.resolve_credentials( + Subject(tenant_id="", subject_id="alice"), + _spec(AuthorizationCodeConfig(header_name=header)), + ) + endpoint = _FakeTokenEndpoint( + [ + Ok(ExchangedToken(access_token="id-jag-assertion", expires_in=300)), + Ok(ExchangedToken(access_token="minted", expires_in=300)), + ] + ) + config = _id_jag_config().model_copy(update={"header_name": header}) + subject = Subject(tenant_id="acme", subject_id="alice", inbound_token=SecretStr("caller-id-token")) + provider = UpstreamCredentialProvider(token_endpoint=endpoint) + return await provider.resolve_credentials(subject, _spec(config)) + + +_MINTED_ARMS = ("client_credentials", "token_exchange", "authorization_code", "id_jag") + + +@pytest.mark.parametrize("kind", _MINTED_ARMS) +@pytest.mark.asyncio +async def test_every_minted_arm_emits_its_configured_header(kind): + # One arm left on a hardcoded Authorization is a silent no-op for exactly the server that + # configured the knob, so this is asserted across all four rather than on the M2M arm alone. + result = await _resolve_with_carrier(kind, "esb-oauth") + assert isinstance(result, Ok) + headers, _ = await _emitted_async(result.ok) + assert headers["esb-oauth"] == "Bearer minted" + assert "authorization" not in headers + + +@pytest.mark.parametrize("kind", _MINTED_ARMS) +@pytest.mark.asyncio +async def test_every_minted_arm_still_defaults_to_authorization(kind): + result = await _resolve_with_carrier(kind, "Authorization") + assert isinstance(result, Ok) + headers, _ = await _emitted_async(result.ok) + assert headers["Authorization"] == "Bearer minted" + + +@pytest.mark.asyncio +async def test_passthrough_ignores_the_carrier_and_keeps_the_callers_slot(): + # Passthrough mints nothing: it forwards the caller's own credential, so it has no carrier to + # configure and must keep using the header the caller aimed it at. + subject = Subject(tenant_id="", subject_id="", inbound_token=SecretStr("caller-token")) + result = await UpstreamCredentialProvider().resolve_credentials(subject, _spec(PassthroughConfig())) + assert isinstance(result, Ok) + headers, _ = await _emitted_async(result.ok) + assert headers["Authorization"] == "caller-token" diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py index bb25ab6bd3c..d4b51b08e06 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py @@ -14,9 +14,11 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials import ( Ambient, ApiKeyConfig, AuthConfig, + AuthorizationCodeConfig, AuthSpecKind, AwsSigV4Config, Byok, + ClientCredentialsConfig, ClientSecretAuth, CredError, Error, @@ -27,7 +29,9 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials import ( ServerSpec, SharedKey, StaticKeys, + TokenExchangeConfig, parse_auth_spec_kind, + validate_header_name, ) _AUTH_CONFIG = TypeAdapter(AuthConfig) @@ -229,3 +233,61 @@ def test_id_jag_server_spec_derives_auth_spec_kind(): config=config, ) assert spec.auth_spec_kind is AuthSpecKind.id_jag + + +_CARRIER_CONFIGS = ( + ("client_credentials", ClientCredentialsConfig), + ("token_exchange", lambda **kw: TokenExchangeConfig(token_exchange_endpoint="https://idp/te", **kw)), + ("authorization_code", AuthorizationCodeConfig), + ( + "id_jag", + lambda **kw: IdJagConfig( + org_token_endpoint="https://idp.example.com/token", + resource_token_endpoint="https://mcp-as.example.com/token", + client_id="litellm", + client_auth=ClientSecretAuth(client_secret=SecretStr("s")), + **kw, + ), + ), + ("api_key", lambda **kw: ApiKeyConfig(key_source=SharedKey(value=SecretStr("k")), **kw)), +) + + +@pytest.mark.parametrize("name,build", _CARRIER_CONFIGS, ids=[n for n, _ in _CARRIER_CONFIGS]) +def test_every_resolved_credential_config_defaults_to_rfc6750_authorization(name, build): + # The default is what preserves today's wire behavior for every existing server. + assert build().header("tok") == ("Authorization", "Bearer tok") + + +@pytest.mark.parametrize("name,build", _CARRIER_CONFIGS, ids=[n for n, _ in _CARRIER_CONFIGS]) +def test_every_resolved_credential_config_honors_a_custom_header(name, build): + assert build(header_name="esb-oauth").header("tok") == ("esb-oauth", "Bearer tok") + + +@pytest.mark.parametrize("name,build", _CARRIER_CONFIGS, ids=[n for n, _ in _CARRIER_CONFIGS]) +def test_every_resolved_credential_config_can_send_a_raw_value(name, build): + assert build(header_name="esb-oauth", value_prefix="").header("tok") == ("esb-oauth", "tok") + + +@pytest.mark.parametrize( + "bad", + [ + "with space", + "has:colon", + "trailing\r\nX-Injected", + "", + " ", + "quoted\"name", + ], +) +def test_header_name_outside_the_rfc7230_token_grammar_is_rejected(bad): + # An operator-supplied name reaches egress verbatim, so anything that could split a + # header must fail closed at construction rather than be sanitized later. + with pytest.raises(ValidationError): + ClientCredentialsConfig(header_name=bad) + assert isinstance(validate_header_name(bad), Error) + + +def test_header_name_is_trimmed_by_the_one_validator(): + assert validate_header_name(" esb-oauth ") == Ok("esb-oauth") + assert ClientCredentialsConfig(header_name=" esb-oauth ").header_name == "esb-oauth" diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.py index 4081681daef..56851d31241 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.py @@ -5,7 +5,8 @@ Validates that: 1. _convert_mcp_hook_response_to_kwargs extracts extra_headers from hook response 2. pre_call_tool_check returns hook-provided extra_headers AND modified arguments 3. call_tool flows hook headers and modified arguments downstream -4. Hook-provided headers take highest priority (merge after static_headers) +4. Hook-provided headers merge after static_headers, but a hook Authorization + header never displaces an existing upstream Authorization credential 5. OpenAPI-backed servers log a warning and continue (skip injection) when hook headers are present 6. JWT claims are propagated in both standard and virtual-key fast paths 7. Backward compatibility: hooks without extra_headers continue to work @@ -487,8 +488,8 @@ class TestHookHeaderMergePriority: ) @pytest.mark.asyncio - async def test_hook_headers_override_static_headers(self): - """Hook headers should take precedence over static_headers.""" + async def test_hook_authorization_does_not_override_static_authorization(self): + """A hook Authorization must not displace a static_headers Authorization (LIT-6321).""" manager = MCPServerManager() server = self._make_server(static_headers={"Authorization": "Bearer static-token", "X-Static": "yes"}) @@ -521,7 +522,7 @@ class TestHookHeaderMergePriority: pass headers = captured_extra_headers.get("value", {}) - assert headers["Authorization"] == "Bearer hook-signed-jwt" + assert headers["Authorization"] == "Bearer static-token" assert headers["X-Static"] == "yes" @pytest.mark.asyncio @@ -560,8 +561,8 @@ class TestHookHeaderMergePriority: assert headers == {"X-Static": "static-value"} @pytest.mark.asyncio - async def test_hook_headers_merge_with_oauth2(self): - """Hook headers merge on top of OAuth2 headers.""" + async def test_hook_authorization_does_not_override_oauth2_authorization(self): + """tools/call keeps the user's OAuth Authorization; only non-auth hook headers merge (LIT-6321).""" manager = MCPServerManager() server = MCPServer( server_id="test-id", @@ -570,6 +571,8 @@ class TestHookHeaderMergePriority: url="https://example.com", transport=MCPTransport.http, auth_type=MCPAuth.oauth2, + oauth2_flow="authorization_code", + delegate_auth_to_upstream=True, ) captured_extra_headers: Dict[str, Any] = {} @@ -605,10 +608,245 @@ class TestHookHeaderMergePriority: pass headers = captured_extra_headers.get("value", {}) - assert headers["Authorization"] == "Bearer hook-jwt" + assert headers["Authorization"] == "Bearer oauth2-token" assert headers["X-OAuth"] == "yes" assert headers["X-Trace-Id"] == "trace-123" + @pytest.mark.asyncio + async def test_hook_authorization_used_when_no_upstream_credential(self): + """With no upstream credential, the signer JWT is still injected.""" + manager = MCPServerManager() + server = self._make_server() + + captured_extra_headers: Dict[str, Optional[Dict[str, str]]] = {} + + async def fake_create_mcp_client(server, mcp_auth_header=None, extra_headers=None, stdio_env=None, **kwargs): + captured_extra_headers["value"] = extra_headers + mock_client = MagicMock() + mock_client.call_tool = AsyncMock(return_value=MagicMock()) + return mock_client + + with patch.object(manager, "_create_mcp_client", side_effect=fake_create_mcp_client): + with patch.object(manager, "_build_stdio_env", return_value=None): + try: + await manager._call_regular_mcp_tool( + mcp_server=server, + original_tool_name="test_tool", + arguments={"key": "val"}, + tasks=[], + mcp_auth_header=None, + mcp_server_auth_headers=None, + oauth2_headers=None, + raw_headers=None, + proxy_logging_obj=None, + hook_extra_headers={"Authorization": "Bearer hook-jwt"}, + ) + except Exception: + pass + + headers = captured_extra_headers.get("value") or {} + assert headers["Authorization"] == "Bearer hook-jwt" + + @pytest.mark.asyncio + async def test_hook_authorization_dropped_when_server_auth_header_present(self): + """With a configured authentication_token (auth_value), the hook Authorization is dropped.""" + manager = MCPServerManager() + server = self._make_server() + + captured: Dict[str, object] = {} + + async def fake_create_mcp_client(server, mcp_auth_header=None, extra_headers=None, stdio_env=None, **kwargs): + captured["extra_headers"] = extra_headers + captured["mcp_auth_header"] = mcp_auth_header + mock_client = MagicMock() + mock_client.call_tool = AsyncMock(return_value=MagicMock()) + return mock_client + + with patch.object(manager, "_create_mcp_client", side_effect=fake_create_mcp_client): + with patch.object(manager, "_build_stdio_env", return_value=None): + try: + await manager._call_regular_mcp_tool( + mcp_server=server, + original_tool_name="test_tool", + arguments={"key": "val"}, + tasks=[], + mcp_auth_header="server-static-token", + mcp_server_auth_headers=None, + oauth2_headers=None, + raw_headers=None, + proxy_logging_obj=None, + hook_extra_headers={ + "Authorization": "Bearer hook-jwt", + "X-Trace-Id": "trace-123", + }, + ) + except Exception: + pass + + headers = captured.get("extra_headers") or {} + assert isinstance(headers, dict) + assert "Authorization" not in headers + assert headers.get("X-Trace-Id") == "trace-123" + assert captured.get("mcp_auth_header") == "server-static-token" + + @pytest.mark.asyncio + async def test_hook_authorization_case_insensitive_conflict(self): + """Authorization conflicts are matched case-insensitively.""" + manager = MCPServerManager() + server = self._make_server(static_headers={"authorization": "Bearer static-token"}) + + captured_extra_headers: Dict[str, Optional[Dict[str, str]]] = {} + + async def fake_create_mcp_client(server, mcp_auth_header=None, extra_headers=None, stdio_env=None, **kwargs): + captured_extra_headers["value"] = extra_headers + mock_client = MagicMock() + mock_client.call_tool = AsyncMock(return_value=MagicMock()) + return mock_client + + with patch.object(manager, "_create_mcp_client", side_effect=fake_create_mcp_client): + with patch.object(manager, "_build_stdio_env", return_value=None): + try: + await manager._call_regular_mcp_tool( + mcp_server=server, + original_tool_name="test_tool", + arguments={"key": "val"}, + tasks=[], + mcp_auth_header=None, + mcp_server_auth_headers=None, + oauth2_headers=None, + raw_headers=None, + proxy_logging_obj=None, + hook_extra_headers={"Authorization": "Bearer hook-jwt"}, + ) + except Exception: + pass + + headers = captured_extra_headers.get("value") or {} + assert headers.get("authorization") == "Bearer static-token" + assert "Authorization" not in headers + + @pytest.mark.asyncio + async def test_hook_authorization_kept_with_api_key_server_credential(self): + """An api_key credential maps to X-API-Key, so the hook Authorization is kept.""" + manager = MCPServerManager() + server = MCPServer( + server_id="test-id", + name="Test Server", + server_name="test_server", + url="https://example.com", + transport=MCPTransport.http, + auth_type=MCPAuth.api_key, + ) + + captured: Dict[str, object] = {} + + async def fake_create_mcp_client(server, mcp_auth_header=None, extra_headers=None, stdio_env=None, **kwargs): + captured["extra_headers"] = extra_headers + captured["mcp_auth_header"] = mcp_auth_header + mock_client = MagicMock() + mock_client.call_tool = AsyncMock(return_value=MagicMock()) + return mock_client + + with patch.object(manager, "_create_mcp_client", side_effect=fake_create_mcp_client): + with patch.object(manager, "_build_stdio_env", return_value=None): + try: + await manager._call_regular_mcp_tool( + mcp_server=server, + original_tool_name="test_tool", + arguments={"key": "val"}, + tasks=[], + mcp_auth_header="server-api-key", + mcp_server_auth_headers=None, + oauth2_headers=None, + raw_headers=None, + proxy_logging_obj=None, + hook_extra_headers={"Authorization": "Bearer hook-jwt"}, + ) + except Exception: + pass + + headers = captured.get("extra_headers") or {} + assert isinstance(headers, dict) + assert headers.get("Authorization") == "Bearer hook-jwt" + assert captured.get("mcp_auth_header") == "server-api-key" + + @pytest.mark.asyncio + async def test_hook_authorization_kept_with_non_authorization_server_header_dict(self): + """A per-server header dict without Authorization does not block the hook JWT.""" + manager = MCPServerManager() + server = self._make_server() + + captured: Dict[str, object] = {} + + async def fake_create_mcp_client(server, mcp_auth_header=None, extra_headers=None, stdio_env=None, **kwargs): + captured["extra_headers"] = extra_headers + captured["mcp_auth_header"] = mcp_auth_header + mock_client = MagicMock() + mock_client.call_tool = AsyncMock(return_value=MagicMock()) + return mock_client + + with patch.object(manager, "_create_mcp_client", side_effect=fake_create_mcp_client): + with patch.object(manager, "_build_stdio_env", return_value=None): + try: + await manager._call_regular_mcp_tool( + mcp_server=server, + original_tool_name="test_tool", + arguments={"key": "val"}, + tasks=[], + mcp_auth_header=None, + mcp_server_auth_headers={"test_server": {"X-API-Key": "per-server-key"}}, + oauth2_headers=None, + raw_headers=None, + proxy_logging_obj=None, + hook_extra_headers={"Authorization": "Bearer hook-jwt"}, + ) + except Exception: + pass + + headers = captured.get("extra_headers") or {} + assert isinstance(headers, dict) + assert headers.get("Authorization") == "Bearer hook-jwt" + assert captured.get("mcp_auth_header") == {"X-API-Key": "per-server-key"} + + @pytest.mark.asyncio + async def test_hook_authorization_dropped_with_authorization_server_header_dict(self): + """A per-server header dict carrying Authorization blocks the hook JWT.""" + manager = MCPServerManager() + server = self._make_server() + + captured: Dict[str, object] = {} + + async def fake_create_mcp_client(server, mcp_auth_header=None, extra_headers=None, stdio_env=None, **kwargs): + captured["extra_headers"] = extra_headers + captured["mcp_auth_header"] = mcp_auth_header + mock_client = MagicMock() + mock_client.call_tool = AsyncMock(return_value=MagicMock()) + return mock_client + + with patch.object(manager, "_create_mcp_client", side_effect=fake_create_mcp_client): + with patch.object(manager, "_build_stdio_env", return_value=None): + try: + await manager._call_regular_mcp_tool( + mcp_server=server, + original_tool_name="test_tool", + arguments={"key": "val"}, + tasks=[], + mcp_auth_header=None, + mcp_server_auth_headers={"test_server": {"authorization": "Bearer per-server-token"}}, + oauth2_headers=None, + raw_headers=None, + proxy_logging_obj=None, + hook_extra_headers={"Authorization": "Bearer hook-jwt", "X-Trace-Id": "trace-123"}, + ) + except Exception: + pass + + headers = captured.get("extra_headers") or {} + assert isinstance(headers, dict) + assert "Authorization" not in headers + assert headers.get("X-Trace-Id") == "trace-123" + assert captured.get("mcp_auth_header") == {"authorization": "Bearer per-server-token"} + @pytest.mark.asyncio async def test_m2m_oauth2_does_not_forward_litellm_caller_authorization(self): """M2M must not put caller Bearer (LiteLLM API key) into extra_headers (#23652).""" diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py index cdea803ebf3..5508259273d 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py @@ -43,7 +43,6 @@ from litellm.proxy._experimental.mcp_server.mcp_server_manager import ( _obo_retry_applies, _resolve_openapi_tool_auth, _should_strip_caller_authorization, - _without_authorization, ) from litellm.proxy._types import ( LiteLLM_MCPServerTable, @@ -2405,6 +2404,104 @@ class TestMCPServerManager: assert client._resolved_auth is not None assert "authorization" not in {k.lower() for k in (client.extra_headers or {})} + @staticmethod + def _esb_server(header: "str | None") -> MCPServer: + return MCPServer( + server_id="esb", + name="esb-server", + url="https://up.example.com/mcp", + transport=MCPTransport.http, + auth_type=MCPAuth.oauth2, + oauth2_flow="client_credentials", + client_id="cid", + client_secret="csec", + token_url="https://idp.example.com/token", + upstream_token_header=header, + static_headers={"Authorization": "Bearer static-upstream-mcp-token"}, + ) + + @pytest.mark.asyncio + async def test_static_authorization_survives_a_minted_token_aimed_elsewhere(self): + """The dual-credential case: an ESB wants the gateway-minted token on its own header while a + separate static Authorization passes through to the origin. Dropping Authorization here (the + old name-blind behavior) deletes the second credential and the upstream 401s.""" + from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import ( + StaticHeaderAuth, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Ok + + class _FakeProvider: + async def resolve_credentials(self, subject, server): + return Ok(StaticHeaderAuth("Bearer MINTED-M2M", header_name="esb-oauth")) + + manager = MCPServerManager(cred_provider=_FakeProvider()) + client = await manager._create_mcp_client( + self._esb_server("esb-oauth"), + extra_headers={"Authorization": "Bearer static-upstream-mcp-token"}, + ) + + assert client._resolved_auth is not None + assert (client.extra_headers or {})["Authorization"] == "Bearer static-upstream-mcp-token" + + @pytest.mark.asyncio + async def test_a_minted_token_aimed_at_the_static_header_still_wins_that_slot(self): + """The negative class of the test above: when the two DO collide the resolver-owned + credential is still authoritative, so the knob cannot be used to smuggle a second + credential into the same slot.""" + from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import ( + StaticHeaderAuth, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Ok + + class _FakeProvider: + async def resolve_credentials(self, subject, server): + return Ok(StaticHeaderAuth("Bearer MINTED-M2M", header_name="esb-oauth")) + + manager = MCPServerManager(cred_provider=_FakeProvider()) + client = await manager._create_mcp_client( + self._esb_server("esb-oauth"), + extra_headers={"esb-oauth": "Bearer signer-jwt", "X-Trace": "keep-me"}, + ) + + assert client._resolved_auth is not None + assert "esb-oauth" not in {k.lower() for k in (client.extra_headers or {})} + assert (client.extra_headers or {})["X-Trace"] == "keep-me" + + @pytest.mark.asyncio + async def test_a_differently_cased_injected_header_is_still_recognised_as_the_collision(self): + """HTTP header names are case-insensitive, so the conflict check must be too. + + A case-sensitive check reports no conflict and hands the injected header back untouched, so + the returned extra_headers still carries a second copy of the credential slot for every + downstream consumer of that dict. httpx happens to collapse the two on the wire, which is + exactly why this needs pinning rather than being left to luck. + """ + from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import ( + StaticHeaderAuth, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Ok + + class _FakeProvider: + async def resolve_credentials(self, subject, server): + return Ok(StaticHeaderAuth("Bearer MINTED", header_name="esb-oauth")) + + manager = MCPServerManager(cred_provider=_FakeProvider()) + client = await manager._create_mcp_client( + self._esb_server("esb-oauth"), + extra_headers={"ESB-OAuth": "Bearer injected", "X-Trace": "keep"}, + ) + + assert client._resolved_auth is not None + assert not any(k.lower() == "esb-oauth" for k in (client.extra_headers or {})) + assert (client.extra_headers or {})["X-Trace"] == "keep" + + def test_without_header_drops_only_the_named_header(self): + from litellm.types.mcp import DEFAULT_CREDENTIAL_HEADER, without_header + + headers = {"Authorization": "Bearer a", "esb-oauth": "Bearer b", "X-Trace": "t"} + assert without_header(headers, "ESB-OAuth") == {"Authorization": "Bearer a", "X-Trace": "t"} + assert without_header(headers, DEFAULT_CREDENTIAL_HEADER) == {"esb-oauth": "Bearer b", "X-Trace": "t"} + @pytest.mark.asyncio async def test_preflight_token_exchange_challenges_on_rejected_subject(self): """A subject the IdP rejects must raise the RFC 9728 401 challenge from the preflight, so a @@ -2624,14 +2721,16 @@ class TestMCPServerManager: if captured_extra_headers: assert "authorization" not in {k.lower() for k in captured_extra_headers} - def test_without_authorization_drops_only_the_credential(self): + def test_without_header_drops_only_the_credential(self): + from litellm.types.mcp import without_header + # None / empty -> None - assert _without_authorization(None) is None - assert _without_authorization({}) is None + assert without_header(None, "Authorization") is None + assert without_header({}, "Authorization") is None # Only Authorization present -> nothing left -> None (case-insensitive) - assert _without_authorization({"authorization": "Bearer x"}) is None + assert without_header({"authorization": "Bearer x"}, "Authorization") is None # Authorization dropped, other headers kept - assert _without_authorization({"Authorization": "Bearer x", "X-Trace-Id": "t"}) == {"X-Trace-Id": "t"} + assert without_header({"Authorization": "Bearer x", "X-Trace-Id": "t"}, "Authorization") == {"X-Trace-Id": "t"} @pytest.mark.asyncio async def test_call_regular_mcp_tool_passthrough_forwards_authorization_with_admission_header( @@ -9641,13 +9740,38 @@ class TestMaterializeAuthHeaders: from litellm.proxy._experimental.mcp_server.outbound_credentials.client_credentials import ( ClientCredentialsBearerAuth, ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( + ClientCredentialsConfig, + ) async def _refetch(_stale: str): return None - headers = await _materialize_auth_headers(ClientCredentialsBearerAuth("m2m-token", _refetch)) + default_carrier = ClientCredentialsConfig() + headers = await _materialize_auth_headers(ClientCredentialsBearerAuth("m2m-token", _refetch, default_carrier)) assert headers == {"Authorization": "Bearer m2m-token"} + @pytest.mark.asyncio + async def test_materialize_follows_the_minted_token_to_a_custom_header(self): + # The OpenAPI arm reads header_name off the auth object rather than assuming Authorization, + # so it carries the knob with no per-arm change. This pins that it stays that way. + from litellm.proxy._experimental.mcp_server.mcp_server_manager import ( + _materialize_auth_headers, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.client_credentials import ( + ClientCredentialsBearerAuth, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( + ClientCredentialsConfig, + ) + + async def _refetch(_stale: str): + return None + + esb_carrier = ClientCredentialsConfig(header_name="esb-oauth") + headers = await _materialize_auth_headers(ClientCredentialsBearerAuth("m2m-token", _refetch, esb_carrier)) + assert headers == {"esb-oauth": "Bearer m2m-token"} + @pytest.mark.asyncio async def test_noop_and_none_materialize_to_none(self): from litellm.proxy._experimental.mcp_server.mcp_server_manager import ( diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth2_token_cache.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth2_token_cache.py index b1aa16a30c0..f7567efcabc 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth2_token_cache.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth2_token_cache.py @@ -13,6 +13,7 @@ import pytest from litellm.proxy._experimental.mcp_server.oauth2_token_cache import ( MCPOAuth2TokenCache, resolve_mcp_auth, + resolved_token_header, ) from litellm.proxy._types import MCPTransport from litellm.types.mcp import MCPAuth @@ -411,3 +412,50 @@ async def test_m2m_mint_uses_admin_entered_token_url_when_issuer_yield_empties_r assert result == "m2m-token-configured" assert mock_client.post.call_args[0][0] == "https://auth.example.com/token" + + +def _m2m_server(**overrides): + from litellm.types.mcp import MCPAuth, MCPTransport + from litellm.types.mcp_server.mcp_server_manager import MCPServer + + fields = dict( + server_id="s", + name="n", + transport=MCPTransport.http, + auth_type=MCPAuth.oauth2, + oauth2_flow="client_credentials", + client_id="cid", + client_secret="csec", + token_url="https://idp.example.com/token", + ) + fields.update(overrides) + return MCPServer(**fields) + + +def test_resolved_token_header_follows_the_configured_header_for_a_gateway_resolved_token(): + # resolve_mcp_auth mints the M2M token on this branch, so the value is the gateway's own and + # follows upstream_token_header. + assert resolved_token_header(_m2m_server(upstream_token_header="esb-oauth")) == "esb-oauth" + + +def test_resolved_token_header_is_none_when_the_server_configures_nothing(): + assert resolved_token_header(_m2m_server()) is None + + +def test_a_caller_supplied_credential_never_moves(): + # The caller aimed their own token at the slot the upstream normally uses. Relocating it would + # break every existing x-mcp-auth caller on a server that sets the field for its own token. + server = _m2m_server(upstream_token_header="esb-oauth") + assert resolved_token_header(server, "Bearer caller-token") is None + assert resolved_token_header(server, {"Authorization": "Bearer caller-token"}) is None + + +def test_the_header_and_the_value_agree_on_which_branch_they_took(): + # The two helpers are read as a pair at one call site, so they must never disagree about + # whether the credential came from the caller or from the server's own config. + import asyncio + + server = _m2m_server(upstream_token_header="esb-oauth", authentication_token="static-tok") + caller = "Bearer caller-token" + assert asyncio.run(resolve_mcp_auth(server, caller)) == caller + assert resolved_token_header(server, caller) is None diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py index bd953dc55f3..64614c094ba 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py @@ -729,3 +729,121 @@ async def test_local_dispatch_reports_the_outcome_instead_of_success(failure: st # A non-auth upstream failure stays a 200 with isError, so REST does not report it as a gateway 500 assert result.isError is True assert "upstream returned HTTP 429" in result.content[0].text + + +@pytest.mark.parametrize( + "resolved,expect_guard", + [ + ({"esb-oauth": "Bearer minted"}, True), + ({"Authorization": "Bearer minted"}, False), + ({}, False), + ], +) +def test_only_a_custom_credential_slot_needs_the_redirect_guard(resolved, expect_guard): + """The OpenAPI arm sends resolved credentials through a redirect-following client, so a custom + slot needs the same cross-origin guard the MCP client installs. Authorization does not: the HTTP + client already strips that one, and taking the guarded path would give up the shared client. + """ + from litellm.types.mcp import DEFAULT_CREDENTIAL_HEADER, same_header + + guarded = next((n for n in resolved if not same_header(n, DEFAULT_CREDENTIAL_HEADER)), None) + assert (guarded is not None) is expect_guard + + +@pytest.mark.asyncio +async def test_the_openapi_arm_drops_a_custom_slot_across_origins(): + """End to end on the hook the OpenAPI arm installs: same origin keeps the credential, a redirect + to another host does not carry it. + """ + import httpx + + from litellm.types.mcp import credential_redirect_hook + + hook = credential_redirect_hook("https://api.example.com/v1/things", "esb-oauth") + + same = httpx.Request("POST", "https://api.example.com/v1/other", headers={"esb-oauth": "Bearer m"}) + await hook(same) + assert same.headers["esb-oauth"] == "Bearer m" + + foreign = httpx.Request("POST", "https://attacker.example.com/collect", headers={"esb-oauth": "Bearer m"}) + await hook(foreign) + assert "esb-oauth" not in foreign.headers + + +def test_the_openapi_arm_installs_the_guard_when_a_credential_rides_a_custom_slot(): + """Pins the wiring, not just the hook: the arm must actually build a guarded client. Testing the + hook alone passes even if this arm never installs it. + """ + from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import ( + _request_resolved_auth_headers, + _upstream_client, + ) + + token = _request_resolved_auth_headers.set({"esb-oauth": "Bearer minted"}) + try: + client = _upstream_client() + assert client.client.event_hooks["request"], "custom slot must install a redirect guard" + finally: + _request_resolved_auth_headers.reset(token) + + +def test_the_guarded_client_is_reused_rather_than_built_per_call(): + """A fresh handler per guarded call is never closed, so every OpenAPI tool call on a server that + sets upstream_token_header would leak an httpx client and its connection pool. Both variants + have to come from the shared cache. + """ + from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import ( + _request_resolved_auth_headers, + _upstream_client, + ) + + token = _request_resolved_auth_headers.set({"esb-oauth": "Bearer minted"}) + try: + assert _upstream_client() is _upstream_client() + finally: + _request_resolved_auth_headers.reset(token) + + +@pytest.mark.asyncio +async def test_the_shared_guard_reads_the_url_from_the_request_context(): + """The hook is one stable object so the client stays cacheable, which means the origin it guards + against has to arrive per request rather than being closed over. + """ + import httpx + + from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import ( + _drop_credential_across_origin, + _request_resolved_auth_headers, + _request_upstream_url, + ) + + creds = _request_resolved_auth_headers.set({"esb-oauth": "Bearer minted"}) + url = _request_upstream_url.set("https://api.example.com/v1/things") + try: + same = httpx.Request("POST", "https://api.example.com/v1/other", headers={"esb-oauth": "Bearer m"}) + await _drop_credential_across_origin(same) + assert same.headers["esb-oauth"] == "Bearer m" + + foreign = httpx.Request("POST", "https://attacker.example.com/x", headers={"esb-oauth": "Bearer m"}) + await _drop_credential_across_origin(foreign) + assert "esb-oauth" not in foreign.headers + finally: + _request_upstream_url.reset(url) + _request_resolved_auth_headers.reset(creds) + + +@pytest.mark.parametrize("resolved", [{"Authorization": "Bearer minted"}, {}, None]) +def test_the_openapi_arm_keeps_the_shared_client_when_no_guard_is_needed(resolved): + # Authorization is already stripped across origins by the HTTP client, so taking the guarded + # path for it would give up the shared connection pool for nothing. + from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import ( + _request_resolved_auth_headers, + _upstream_client, + ) + + token = _request_resolved_auth_headers.set(resolved) + try: + client = _upstream_client() + assert not client.client.event_hooks.get("request") + finally: + _request_resolved_auth_headers.reset(token) diff --git a/tests/test_litellm/proxy/auth/test_user_api_key_auth.py b/tests/test_litellm/proxy/auth/test_user_api_key_auth.py index 6a117985820..d44f96d95bf 100644 --- a/tests/test_litellm/proxy/auth/test_user_api_key_auth.py +++ b/tests/test_litellm/proxy/auth/test_user_api_key_auth.py @@ -4972,6 +4972,143 @@ async def test_centralized_common_checks_ui_sentinel_team_vouches_despite_absent setattr(_proxy_server_mod, k, v) +@pytest.mark.asyncio +async def test_centralized_common_checks_ui_sentinel_team_skips_db_lookup(): + """LIT-6297 / GH#28775: ``UI_TEAM_ID`` never has a team row and the + not-found path bypasses the DB throttle, so building the team fetch for it + cost one guaranteed-miss ``LiteLLM_TeamTable.find_unique`` plus a 404 debug + log on every dashboard request. The gate must not call ``get_team_object`` + for the sentinel at all, while the token-derived team object still reaches + ``common_checks``.""" + import litellm.proxy.proxy_server as _proxy_server_mod + from fastapi import Request + from starlette.datastructures import URL + + from litellm.proxy._types import UI_TEAM_ID, LiteLLM_TeamTableCachedObj + + token = UserAPIKeyAuth( + api_key="sk-test", + user_id="ui-session-user", + team_id=UI_TEAM_ID, + models=[], + team_models=[], + ) + request = Request(scope={"type": "http"}) + request._url = URL(url="/user/info") + request._body = b"{}" + + received_team_objects: list[LiteLLM_TeamTableCachedObj | None] = [] + + async def _capturing_common_checks(*_args, **kwargs) -> bool: + received_team_objects.append(kwargs.get("team_object")) + return True + + attrs = _proxy_attrs_for_centralized_checks(user_custom_auth=None) + originals = {a: getattr(_proxy_server_mod, a, None) for a in attrs} + try: + for k, v in attrs.items(): + setattr(_proxy_server_mod, k, v) + with ( + patch( # test-quality-ok: the regression IS that this DB lookup is never made for the sentinel + "litellm.proxy.auth.user_api_key_auth.get_team_object", + new_callable=AsyncMock, + ) as mock_get_team_object, + patch( # test-quality-ok: capture the team_object the consumer receives without a DB + "litellm.proxy.auth.user_api_key_auth.common_checks", + _capturing_common_checks, + ), + ): + await _run_centralized_common_checks( + user_api_key_auth_obj=token, + request=request, + request_data={}, + route="/user/info", + ) + mock_get_team_object.assert_not_awaited() + assert len(received_team_objects) == 1 + received_team_object = received_team_objects[0] + assert received_team_object is not None + assert received_team_object.team_id == UI_TEAM_ID + finally: + for k, v in originals.items(): + setattr(_proxy_server_mod, k, v) + + +@pytest.mark.asyncio +async def test_builder_ui_sentinel_team_never_hits_get_team_object(): # test-quality-ok: absence of the guaranteed-miss DB call is the observable being pinned + """Companion to the centralized-gate test for the builder path: the cached + UI session token's team refresh and the post-validation team fetch must + both skip ``get_team_object`` for ``UI_TEAM_ID`` instead of 404ing on + every request.""" + import litellm.proxy.proxy_server as _proxy_server_mod + from fastapi import Request + from starlette.datastructures import URL + + from litellm.proxy._types import UI_TEAM_ID + from litellm.proxy.auth.user_api_key_auth import _user_api_key_auth_builder + from litellm.proxy.proxy_server import hash_token + + api_key = "sk-test-ui-session-key" + cached_token = UserAPIKeyAuth( + api_key=api_key, + token=hash_token(api_key), + user_id="ui-session-user", + user_role=LitellmUserRoles.INTERNAL_USER, + team_id=UI_TEAM_ID, + ) + + mock_proxy_logging_obj = MagicMock() + mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None) + + attrs = { + "prisma_client": MagicMock(), + "user_api_key_cache": DualCache(), + "proxy_logging_obj": mock_proxy_logging_obj, + "master_key": "sk-master-key", + "general_settings": {}, + "llm_model_list": [], + "llm_router": None, + "open_telemetry_logger": None, + "model_max_budget_limiter": MagicMock(), + "user_custom_auth": None, + "jwt_handler": None, + "litellm_proxy_admin_name": "admin", + } + originals = {a: getattr(_proxy_server_mod, a, None) for a in attrs} + try: + for k, v in attrs.items(): + setattr(_proxy_server_mod, k, v) + + request = Request(scope={"type": "http"}) + request._url = URL(url="/user/info") + + with ( + patch( # test-quality-ok: seed the cached UI session token without a DB + "litellm.proxy.auth.resolvers.store.IdentityStore._resolve_key", + new_callable=AsyncMock, + return_value=cached_token, + ), + patch( # test-quality-ok: the regression IS that this DB lookup is never made for the sentinel + "litellm.proxy.auth.user_api_key_auth.get_team_object", + new_callable=AsyncMock, + ) as mock_get_team_object, + ): + result = await _user_api_key_auth_builder( + request=request, + api_key=f"Bearer {api_key}", + azure_api_key_header="", + anthropic_api_key_header=None, + google_ai_studio_api_key_header=None, + azure_apim_header=None, + request_data={}, + ) + assert result.team_id == UI_TEAM_ID + mock_get_team_object.assert_not_awaited() + finally: + for k, v in originals.items(): + setattr(_proxy_server_mod, k, v) + + @pytest.mark.asyncio async def test_centralized_common_checks_user_http_exception_isolates_to_user_only(): """Per-fetch isolation, mirror of the team case: an HTTPException diff --git a/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py b/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py index aa844304604..5d3afd95a55 100644 --- a/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py +++ b/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py @@ -1458,7 +1458,7 @@ def test_budget_cascade_writes_land_in_a_single_transaction(reset_budget_job, mo budget = _budget_row(budget_id="budget-1", budget_duration="7d") mock_prisma_client.data["budget"] = [budget] mock_prisma_client.data["enduser"] = [ - type("EndUser", (), {"spend": 5.0, "litellm_budget_table": budget, "user_id": "enduser-1"}) + type("EndUser", (), {"spend": 5.0, "litellm_budget_table": budget, "user_id": "enduser-1", "budget_id": "budget-1"}) ] asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table()) @@ -2588,3 +2588,303 @@ def test_ambiguous_commit_replay_does_not_erase_newly_accrued_spend( assert client.key_spend == expected_spend assert client.commit_attempts == expected_commits assert client.reconnect_reasons == expected_reconnects + + +# --------------------------------------------------------------------------- +# Budget rollover (LIT-3085): overage beyond max_budget carries into the next +# window instead of being forgiven +# --------------------------------------------------------------------------- + + +@pytest.fixture +def rollover_enabled(monkeypatch): + import litellm + + monkeypatch.setattr(litellm, "budget_rollover", True) + + +@pytest.mark.parametrize( + "run_phase, table, id_field, id_value, row_factory", + [ + ( + lambda job: job.reset_budget_for_litellm_keys(), + "key", + "token", + "tok-roll", + lambda now: type( + "Key", + (), + { + "spend": 150.0, + "max_budget": 100.0, + "budget_duration": "1d", + "budget_reset_at": now, + "token": "tok-roll", + }, + ), + ), + ( + lambda job: job.reset_budget_for_litellm_users(), + "user", + "user_id", + "user-roll", + lambda now: type( + "User", + (), + { + "spend": 150.0, + "max_budget": 100.0, + "budget_duration": "30d", + "budget_reset_at": now, + "user_id": "user-roll", + }, + ), + ), + ( + lambda job: job.reset_budget_for_litellm_teams(), + "team", + "team_id", + "team-roll", + lambda now: type( + "Team", + (), + { + "spend": 150.0, + "max_budget": 100.0, + "budget_duration": "1mo", + "budget_reset_at": now, + "team_id": "team-roll", + }, + ), + ), + ], +) +def test_direct_reset_carries_overage_when_rollover_enabled( + rollover_enabled, reset_budget_job, mock_prisma_client, monkeypatch, run_phase, table, id_field, id_value, row_factory +): + """spend=150 against max_budget=100 must decrement by the cap (leaving 50) + rather than zero the row, and the spend counter must be seeded with 50.""" + counter_cache = _make_counter_invalidation_job(monkeypatch) + now = datetime.now(timezone.utc) + mock_prisma_client.data[table] = [row_factory(now)] + + asyncio.run(run_phase(reset_budget_job)) + + writes = _batch_writes(mock_prisma_client, table) + assert len(writes) == 1 + assert writes[0]["where"] == {id_field: id_value} + assert writes[0]["data"]["spend"] == {"decrement": 100.0} + assert writes[0]["data"]["budget_reset_at"] > now + counter_prefix = {"key": "spend:key", "user": "spend:user", "team": "spend:team"}[table] + counter_cache.in_memory_cache.set_cache.assert_any_call(key=f"{counter_prefix}:{id_value}", value=50.0, ttl=60) + + +def test_direct_reset_zeroes_under_budget_row_even_with_rollover( + rollover_enabled, reset_budget_job, mock_prisma_client, monkeypatch +): + counter_cache = _make_counter_invalidation_job(monkeypatch) + now = datetime.now(timezone.utc) + mock_prisma_client.data["key"] = [ + type( + "Key", + (), + {"spend": 40.0, "max_budget": 100.0, "budget_duration": "1d", "budget_reset_at": now, "token": "tok-under"}, + ) + ] + + asyncio.run(reset_budget_job.reset_budget_for_litellm_keys()) + + assert _batch_writes(mock_prisma_client, "key")[0]["data"]["spend"] == 0 + counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:key:tok-under", value=0.0, ttl=60) + + +def test_direct_reset_zeroes_row_without_max_budget_even_with_rollover( + rollover_enabled, reset_budget_job, mock_prisma_client, monkeypatch +): + """No cap means nothing to carry against: reset to zero as before.""" + _make_counter_invalidation_job(monkeypatch) + now = datetime.now(timezone.utc) + mock_prisma_client.data["key"] = [ + type( + "Key", + (), + {"spend": 150.0, "max_budget": None, "budget_duration": "1d", "budget_reset_at": now, "token": "tok-nocap"}, + ) + ] + + asyncio.run(reset_budget_job.reset_budget_for_litellm_keys()) + + assert _batch_writes(mock_prisma_client, "key")[0]["data"]["spend"] == 0 + + +def test_budget_cascade_carries_overage_per_tier_when_rollover_enabled( + rollover_enabled, reset_budget_job, mock_prisma_client, monkeypatch +): + """A team member 5 over the tier cap keeps a spend of 5 in the next window: + the cascade decrements over-cap rows by the cap, zeroes the rest, and seeds + the spend counter with the carried amount.""" + counter_cache = _make_counter_invalidation_job(monkeypatch) + budget = _budget_row(budget_id="budget-roll", budget_duration="7d", max_budget=10.0) + mock_prisma_client.data["budget"] = [budget] + membership = type( + "Membership", + (), + {"user_id": "member-1", "team_id": "team-1", "spend": 15.0, "budget_id": "budget-roll"}, + ) + mock_prisma_client.db.litellm_teammembership.set_find_many_results([membership]) + + asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table()) + + membership_writes = _batch_writes(mock_prisma_client, "team_membership") + assert { + "table": "team_membership", + "op": "update_many", + "where": {"budget_id": "budget-roll", "spend": {"gt": 10.0}}, + "data": {"spend": {"decrement": 10.0}}, + } in membership_writes + assert { + "table": "team_membership", + "op": "update_many", + "where": {"budget_id": "budget-roll", "spend": {"gt": 0, "lte": 10.0}}, + "data": {"spend": 0}, + } in membership_writes + counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:team_member:member-1:team-1", value=5.0, ttl=60) + + +def test_budget_cascade_carries_enduser_overage_when_rollover_enabled( + rollover_enabled, reset_budget_job, mock_prisma_client, monkeypatch +): + _make_counter_invalidation_job(monkeypatch) + budget = _budget_row(budget_id="budget-roll", budget_duration="1d", max_budget=10.0) + mock_prisma_client.data["budget"] = [budget] + mock_prisma_client.data["enduser"] = [ + type( + "EndUser", + (), + {"spend": 15.0, "litellm_budget_table": budget, "user_id": "enduser-roll", "budget_id": "budget-roll"}, + ) + ] + + asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table()) + + enduser_writes = _batch_writes(mock_prisma_client, "enduser") + assert { + "table": "enduser", + "op": "update_many", + "where": {"user_id": {"in": ["enduser-roll"]}, "spend": {"gt": 10.0}}, + "data": {"spend": {"decrement": 10.0}}, + } in enduser_writes + assert { + "table": "enduser", + "op": "update_many", + "where": {"user_id": {"in": ["enduser-roll"]}, "spend": {"lte": 10.0}}, + "data": {"spend": 0}, + } in enduser_writes + + +def _replay_spend_writes(writes, spend): + """Apply the queued update_many statements in order, the way the DB + transaction executes them, and return the row's final spend.""" + for write in writes: + condition = write["where"].get("spend") + if isinstance(condition, dict): + if "gt" in condition and not spend > condition["gt"]: + continue + if "lte" in condition and not spend <= condition["lte"]: + continue + payload = write["data"]["spend"] + spend = payload if not isinstance(payload, dict) else spend - payload["decrement"] + return spend + + +@pytest.mark.parametrize("table", ["team_membership", "enduser"]) +def test_cascade_rollover_writes_survive_sequential_execution( + rollover_enabled, reset_budget_job, mock_prisma_client, monkeypatch, table +): + """The statements run one after another inside a transaction, so a + decrement-then-zero order would re-match the decremented row (now in the + 0..cap range) and erase the carried spend. Replaying the writes in queue + order must leave the overage, for any spend between cap and twice the cap.""" + _make_counter_invalidation_job(monkeypatch) + budget = _budget_row(budget_id="budget-roll", budget_duration="7d", max_budget=10.0) + mock_prisma_client.data["budget"] = [budget] + membership = type( + "Membership", + (), + {"user_id": "member-1", "team_id": "team-1", "spend": 15.0, "budget_id": "budget-roll"}, + ) + mock_prisma_client.db.litellm_teammembership.set_find_many_results([membership]) + mock_prisma_client.data["enduser"] = [ + type( + "EndUser", + (), + {"spend": 15.0, "litellm_budget_table": budget, "user_id": "enduser-roll", "budget_id": "budget-roll"}, + ) + ] + + asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table()) + + writes = _batch_writes(mock_prisma_client, table) + assert _replay_spend_writes(writes, 15.0) == 5.0 + assert _replay_spend_writes(writes, 8.0) == 0 + assert _replay_spend_writes(writes, 25.0) == 15.0 + + +def test_budget_cascade_zeroes_everything_when_rollover_disabled(reset_budget_job, mock_prisma_client, monkeypatch): + """Control: with the flag off the cascade keeps the plain zeroing writes.""" + _make_counter_invalidation_job(monkeypatch) + budget = _budget_row(budget_id="budget-off", budget_duration="7d", max_budget=10.0) + mock_prisma_client.data["budget"] = [budget] + + asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table()) + + membership_writes = _batch_writes(mock_prisma_client, "team_membership") + assert membership_writes == [ + { + "table": "team_membership", + "op": "update_many", + "where": {"budget_id": {"in": ["budget-off"]}}, + "data": {"spend": 0}, + } + ] + + +def test_window_reset_carries_counter_overage_when_rollover_enabled(rollover_enabled, monkeypatch): + """A per-window counter at 130 against a 100 cap restarts the window at 30.""" + now = datetime.utcnow() + expired = (now - timedelta(minutes=5)).isoformat() + "Z" + key_rows = [ + { + "token": "sk-roll", + "budget_limits": [{"budget_duration": "1d", "reset_at": expired, "max_budget": 100.0}], + } + ] + job, prisma_client, spend_counter_cache = _make_reset_budget_windows_job( + monkeypatch, key_rows=key_rows, team_rows=[] + ) + spend_counter_cache.async_get_cache = AsyncMock(return_value=130.0) + + asyncio.run(job.reset_budget_windows()) + + prisma_client.db.litellm_verificationtoken.update.assert_awaited_once() + spend_counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:key:sk-roll:window:1d", value=30.0) + + +def test_window_reset_zeroes_counter_when_rollover_disabled(monkeypatch): + now = datetime.utcnow() + expired = (now - timedelta(minutes=5)).isoformat() + "Z" + key_rows = [ + { + "token": "sk-off", + "budget_limits": [{"budget_duration": "1d", "reset_at": expired, "max_budget": 100.0}], + } + ] + job, prisma_client, spend_counter_cache = _make_reset_budget_windows_job( + monkeypatch, key_rows=key_rows, team_rows=[] + ) + spend_counter_cache.async_get_cache = AsyncMock(return_value=130.0) + + asyncio.run(job.reset_budget_windows()) + + spend_counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:key:sk-off:window:1d", value=0.0) + spend_counter_cache.async_get_cache.assert_not_awaited() diff --git a/tests/test_litellm/proxy/db/test_prisma_client.py b/tests/test_litellm/proxy/db/test_prisma_client.py index b1ecbfeff8e..f0983d6bf62 100644 --- a/tests/test_litellm/proxy/db/test_prisma_client.py +++ b/tests/test_litellm/proxy/db/test_prisma_client.py @@ -215,6 +215,44 @@ def test_db_push_applies_replica_identity_full_when_requested(monkeypatch): assert applied == [True] +def test_db_push_is_rejected_when_spend_logs_is_partitioned(monkeypatch): + """A doc-partitioned LiteLLM_SpendLogs makes `prisma db push` rewrite the + primary key back to ("request_id"), which Postgres rejects; the guard must + fail fast with guidance instead of running the push.""" + from litellm.proxy.db.prisma_client import PrismaManager + from litellm_proxy_extras.utils import ( + PARTITIONED_SPEND_LOGS_PUSH_ERROR, + ProxyExtrasDBManager, + ) + + monkeypatch.setattr( + ProxyExtrasDBManager, "spend_logs_is_partitioned", staticmethod(lambda: True) + ) + with patch( # test-quality-ok: subprocess.run is the external prisma CLI boundary, asserted never reached + "litellm.proxy.db.prisma_client.subprocess.run" + ) as mock_run: + with pytest.raises(RuntimeError) as err: + PrismaManager.setup_database(use_migrate=False) + + assert str(err.value) == PARTITIONED_SPEND_LOGS_PUSH_ERROR + mock_run.assert_not_called() + + +def test_db_push_proceeds_when_spend_logs_is_not_partitioned(monkeypatch): + from litellm.proxy.db.prisma_client import PrismaManager + from litellm_proxy_extras.utils import ProxyExtrasDBManager + + monkeypatch.setattr( + ProxyExtrasDBManager, "spend_logs_is_partitioned", staticmethod(lambda: False) + ) + with patch( # test-quality-ok: subprocess.run is the external prisma CLI boundary, not SDK logic + "litellm.proxy.db.prisma_client.subprocess.run" + ) as mock_run: + assert PrismaManager.setup_database(use_migrate=False) is True + + assert mock_run.call_args[0][0][:3] == ["prisma", "db", "push"] + + def _entra_jwt(expires_in_seconds: int) -> str: """A JWT shaped like a real Entra access token, expiring ``expires_in_seconds`` from now.""" import base64 diff --git a/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.py b/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.py index 2ce36b73de0..0c3fe175b48 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.py +++ b/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.py @@ -1,91 +1,120 @@ import jwt +import pytest -from litellm.proxy.management_endpoints.ui_sso import MicrosoftSSOHandler -from litellm.proxy.management_endpoints.types import get_litellm_user_role from litellm.proxy._types import LitellmUserRoles +from litellm.proxy.management_endpoints.ui_sso import MicrosoftSSOHandler + + +def _id_token(**claims) -> str: + """Build a signed id_token carrying the given claims.""" + payload = { + "sub": "user123", + "email": "user@company.com", + "aud": "litellm-app", + "iss": "https://login.microsoftonline.com/tenant-id/v2.0", + "exp": 9999999999, + **claims, + } + return jwt.encode(payload, "secret", algorithm="HS256") def test_extracts_proxy_admin_role_from_jwt(): """Ensure supported app roles like 'proxy_admin' are extracted from the id_token.""" - payload = { - "sub": "user123", - "email": "admin@company.com", - "app_roles": ["proxy_admin"], - "aud": "litellm-app", - "iss": "https://login.microsoftonline.com/tenant-id/v2.0", - "exp": 9999999999, - } + token = _id_token(app_roles=["proxy_admin"]) - token = jwt.encode(payload, "secret", algorithm="HS256") roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token) assert roles == ["proxy_admin"] -def test_maps_internal_user_role(): - """Ensure internal_user role is correctly mapped to LitellmUserRoles.""" - payload = { - "sub": "user456", - "email": "user@company.com", - "app_roles": ["internal_user"], - "aud": "litellm-app", - "iss": "https://login.microsoftonline.com/tenant-id/v2.0", - "exp": 9999999999, - } +def test_extracts_app_roles_from_roles_claim(): + """Entra emits app role values in the `roles` claim; both spellings are read.""" + token = _id_token(roles=["internal_user"]) - token = jwt.encode(payload, "secret", algorithm="HS256") roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token) - # Map to LitellmUserRoles - chosen = None - for r in roles: - mapped = get_litellm_user_role(r) - if mapped is not None: - chosen = mapped - break - - assert chosen == LitellmUserRoles.INTERNAL_USER + assert roles == ["internal_user"] -def test_maps_proxy_admin_viewer_role(): - """Ensure proxy_admin_viewer role is correctly mapped.""" - payload = { - "sub": "user789", - "email": "viewer@company.com", - "app_roles": ["proxy_admin_viewer"], - "aud": "litellm-app", - "iss": "https://login.microsoftonline.com/tenant-id/v2.0", - "exp": 9999999999, - } - - token = jwt.encode(payload, "secret", algorithm="HS256") - roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token) - - chosen = None - for r in roles: - mapped = get_litellm_user_role(r) - if mapped is not None: - chosen = mapped - break - - assert chosen == LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY +@pytest.mark.parametrize( + "app_roles, expected", + [ + (["proxy_admin"], LitellmUserRoles.PROXY_ADMIN), + (["proxy_admin_viewer"], LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY), + (["internal_user"], LitellmUserRoles.INTERNAL_USER), + (["internal_user_viewer"], LitellmUserRoles.INTERNAL_USER_VIEW_ONLY), + # Case-insensitive, matching get_litellm_user_role. + (["PROXY_ADMIN_VIEWER"], LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY), + # Roles outside the privilege hierarchy still resolve. + (["org_admin"], LitellmUserRoles.ORG_ADMIN), + ], +) +def test_maps_single_app_role(app_roles, expected): + """A lone app role maps to its LitellmUserRoles equivalent.""" + assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == expected -def test_defaults_to_internal_user_viewer_when_no_role(): - """Ensure default role is internal_user_viewer when no app role is present.""" - payload = { - "sub": "user_no_role", - "email": "noRole@company.com", - "aud": "litellm-app", - "iss": "https://login.microsoftonline.com/tenant-id/v2.0", - "exp": 9999999999, - } +@pytest.mark.parametrize( + "app_roles", + [ + ["internal_user", "proxy_admin_viewer"], + ["proxy_admin_viewer", "internal_user"], + ], +) +def test_highest_privilege_role_wins_regardless_of_claim_order(app_roles): + """ + A user in one group mapped to `internal_user` and another mapped to + `proxy_admin_viewer` gets the higher privilege role either way. + + Entra does not guarantee the ordering of the `roles` claim, so the resolved + role must not depend on it. + """ + assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == (LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY) + + +@pytest.mark.parametrize( + "app_roles", + [ + ["internal_user", "proxy_admin_viewer", "proxy_admin"], + ["proxy_admin", "proxy_admin_viewer", "internal_user"], + ["proxy_admin_viewer", "internal_user", "proxy_admin"], + ], +) +def test_proxy_admin_beats_every_other_role(app_roles): + """proxy_admin outranks every other role in the hierarchy, in any claim order.""" + assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == LitellmUserRoles.PROXY_ADMIN + + +def test_unrecognised_app_roles_are_ignored(): + """App roles that are not LitellmUserRoles values do not shadow ones that are.""" + app_roles = ["Some.Custom.Role", "msiam_access", "internal_user"] + + assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == LitellmUserRoles.INTERNAL_USER + + +@pytest.mark.parametrize("app_roles", [None, [], ["msiam_access"], ["User"]]) +def test_returns_none_when_no_role_resolves(app_roles): + """ + Returning None lets the caller keep the user's stored role or apply + default_internal_user_params, rather than forcing a role. + """ + assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) is None + + +def test_no_role_claim_yields_no_app_roles(): + """An id_token with no role claim produces no app roles, and so no role.""" + token = _id_token() - token = jwt.encode(payload, "secret", algorithm="HS256") roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token) assert roles == [] + assert MicrosoftSSOHandler.get_user_role_from_app_roles(roles) is None - # Default role would be internal_user_viewer - default_role = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY - assert default_role.value == "internal_user_viewer" + +def test_end_to_end_from_id_token_to_role(): + """The id_token -> role path resolves the highest privilege role.""" + token = _id_token(roles=["internal_user", "proxy_admin_viewer"]) + + roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token) + + assert MicrosoftSSOHandler.get_user_role_from_app_roles(roles) == LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index a37c4f72b3d..6045b64023d 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -730,6 +730,68 @@ async def test_update_key_personal_non_admin_denied_vector_stores(monkeypatch): assert "Vector stores" in str(exc.value.detail) +@pytest.mark.asyncio +async def test_update_key_grandfathers_existing_mcp_servers(monkeypatch): + """/key/update on a team key that already holds MCP servers outside the + team allowlist must accept re-sent or shrunk grants (LIT-6062). The wrapper + must pass the existing key's object_permission row into the validator when + the team is unchanged.""" + from unittest.mock import AsyncMock, MagicMock + + from litellm.proxy._types import ( + LiteLLM_ObjectPermissionBase, + UpdateKeyRequest, + ) + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_mcp_servers_for_key_update, + ) + + existing_row = MagicMock() + existing_row.mcp_servers = ["server-a", "server-b"] + existing_row.mcp_tool_permissions = {} + mock_prisma = MagicMock() + mock_prisma.db.litellm_mcpservertable.find_many = AsyncMock(return_value=[]) + + team_obj = MagicMock() + team_obj.team_id = "team-1" + team_obj.object_permission = None + + existing_key_row = MagicMock( + team_id="team-1", + object_permission_id="perm-1", + object_permission=existing_row, + ) + + mock_server_a = MagicMock() + mock_server_a.server_id = "server-a" + mock_server_b = MagicMock() + mock_server_b.server_id = "server-b" + mock_mgr = MagicMock() + mock_mgr.get_registry.return_value = { + "server-a": mock_server_a, + "server-b": mock_server_b, + } + mock_mgr.get_allow_all_keys_server_ids.return_value = [] + monkeypatch.setattr( + "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager", + mock_mgr, + ) + + result = await _validate_mcp_servers_for_key_update( + data=UpdateKeyRequest( + key="sk-team-key", + object_permission=LiteLLM_ObjectPermissionBase(mcp_servers=["server-a"]), + ), + team_obj=team_obj, + existing_key_row=existing_key_row, + prisma_client=mock_prisma, + user_api_key_cache=MagicMock(), + is_proxy_admin=False, + ) + assert result is not None + assert result["mcp_servers"] == ["server-a"] + + @pytest.mark.asyncio async def test_update_key_personal_non_admin_denied_access_groups( monkeypatch, @@ -6552,7 +6614,7 @@ async def test_get_and_validate_existing_key(): assert result == mock_key mock_prisma_client.db.litellm_verificationtoken.find_unique.assert_called_once_with( - where={"token": "hashed-test-key-123"} + where={"token": "hashed-test-key-123"}, include={"object_permission": True} ) # Test Case 2: Key not found raises ProxyException diff --git a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py index 0d639e1cb6a..ceb44de5576 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py @@ -1573,6 +1573,7 @@ class TestTemporaryMCPSessionEndpoints: existing_server.aws_region_name = None existing_server.aws_service_name = None existing_server.upstream_resource = None + existing_server.upstream_token_header = None mock_manager = MagicMock() mock_manager.get_mcp_server_by_id.return_value = existing_server @@ -1608,6 +1609,7 @@ class TestTemporaryMCPSessionEndpoints: existing_server.aws_region_name = None existing_server.aws_service_name = None existing_server.upstream_resource = None + existing_server.upstream_token_header = None for key, value in server_overrides.items(): setattr(existing_server, key, value) @@ -1639,6 +1641,23 @@ class TestTemporaryMCPSessionEndpoints: assert updated.credentials["client_id"] == "client-123" assert updated.credentials["client_secret"] == "secret-xyz" + def test_upstream_token_header_is_inherited_like_other_admin_config(self): + """It is admin config rather than a credential, so a session server derived from an existing + one must carry it. Miss it and the derived server silently sends its token to Authorization + while the original sends it to the gateway's header.""" + updated = self._inherit_with({}, upstream_token_header="esb-oauth") + + assert updated.credentials["upstream_token_header"] == "esb-oauth" + + def test_a_supplied_upstream_token_header_does_not_read_as_a_credential(self): + """It is in the admin-config key set, so submitting only it must still inherit the declared + app rather than reading as "the caller supplied real credentials".""" + updated = self._inherit_with({"upstream_token_header": "esb-oauth"}) + + assert updated.credentials["client_id"] == "client-123" + assert updated.credentials["client_secret"] == "secret-xyz" + assert updated.credentials["upstream_token_header"] == "esb-oauth" + def test_supplied_credential_still_wins_over_inheritance(self): """A caller that supplies a real credential keeps it; inheritance must not overwrite it.""" updated = self._inherit_with({"auth_value": "caller-token"}) @@ -2256,6 +2275,7 @@ class TestTemporaryMCPSessionEndpoints: aws_region_name=None, aws_service_name=None, upstream_resource=None, + upstream_token_header=None, ) built_server = generate_mock_mcp_server_config_record(server_id="temp-server") mock_manager = MagicMock() diff --git a/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py b/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py index b129ad0f659..5ef83344c1a 100644 --- a/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py +++ b/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py @@ -1213,6 +1213,124 @@ async def test_empty_object_permission_passes_for_personal_non_admin(): ) +# ---- Tests for grandfathering existing key MCP servers on /key/update (LIT-6062) ---- + + +def _make_grandfather_fixtures(mcp_servers=None, mcp_tool_permissions=None): + """Mock prisma client plus the key's existing object permission row.""" + existing_row = MagicMock() + existing_row.mcp_servers = mcp_servers or [] + existing_row.mcp_tool_permissions = mcp_tool_permissions or {} + mock_prisma = MagicMock() + mock_prisma.db.litellm_mcpservertable.find_many = AsyncMock(return_value=[]) + return mock_prisma, existing_row + + +def _patch_grandfather_env(monkeypatch, mock_mgr): + monkeypatch.setattr( + "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager", + mock_mgr, + ) + monkeypatch.setattr( + "litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids", + lambda: set(), + ) + + +@pytest.mark.asyncio +async def test_validate_key_update_grandfathers_existing_servers(monkeypatch): + """A key already holding servers outside the team allowlist can re-send or + shrink those grants on /key/update without a 403 (LIT-6062).""" + _patch_grandfather_env(monkeypatch, _make_mock_mcp_manager("server-a", "server-b")) + team_obj = _make_team_obj(mcp_servers=[]) + mock_prisma, existing_row = _make_grandfather_fixtures(mcp_servers=["server-a", "server-b"]) + resend = await validate_key_mcp_servers_against_team( + object_permission={"mcp_servers": ["server-a", "server-b"]}, + team_obj=team_obj, + prisma_client=mock_prisma, + existing_key_object_permission=existing_row, + ) + assert sorted(resend["mcp_servers"]) == ["server-a", "server-b"] + shrink = await validate_key_mcp_servers_against_team( + object_permission={"mcp_servers": ["server-a"]}, + team_obj=team_obj, + prisma_client=mock_prisma, + existing_key_object_permission=existing_row, + ) + assert shrink["mcp_servers"] == ["server-a"] + + +@pytest.mark.asyncio +async def test_validate_key_update_grandfather_does_not_allow_new_servers(monkeypatch): + """Grandfathering only covers servers the key already holds; adding a new + server outside the team allowlist still raises 403.""" + _patch_grandfather_env(monkeypatch, _make_mock_mcp_manager("server-a", "server-new")) + team_obj = _make_team_obj(mcp_servers=[]) + mock_prisma, existing_row = _make_grandfather_fixtures(mcp_servers=["server-a"]) + with pytest.raises(HTTPException) as exc_info: + await validate_key_mcp_servers_against_team( + object_permission={"mcp_servers": ["server-a", "server-new"]}, + team_obj=team_obj, + prisma_client=mock_prisma, + existing_key_object_permission=existing_row, + ) + assert exc_info.value.status_code == 403 + assert "server-new" in str(exc_info.value.detail) + + +@pytest.mark.asyncio +async def test_validate_key_update_without_existing_permission_still_raises(monkeypatch): + """Without an existing permission row (new grants or team change) the + subset check stays strict.""" + _patch_grandfather_env(monkeypatch, _make_mock_mcp_manager("server-a")) + team_obj = _make_team_obj(mcp_servers=[]) + mock_prisma, _ = _make_grandfather_fixtures(mcp_servers=["server-a"]) + with pytest.raises(HTTPException) as exc_info: + await validate_key_mcp_servers_against_team( + object_permission={"mcp_servers": ["server-a"]}, + team_obj=team_obj, + prisma_client=mock_prisma, + existing_key_object_permission=None, + ) + assert exc_info.value.status_code == 403 + + +@pytest.mark.asyncio +async def test_validate_key_update_grandfathers_tool_permission_keys(monkeypatch): + """Servers granted only via mcp_tool_permissions keys on the existing row + (stored as a JSON string) are grandfathered too.""" + _patch_grandfather_env(monkeypatch, _make_mock_mcp_manager("server-a")) + team_obj = _make_team_obj(mcp_servers=[]) + mock_prisma, existing_row = _make_grandfather_fixtures( + mcp_tool_permissions=json.dumps({"server-a": ["tool1"]}) + ) + result = await validate_key_mcp_servers_against_team( + object_permission={"mcp_servers": ["server-a"]}, + team_obj=team_obj, + prisma_client=mock_prisma, + existing_key_object_permission=existing_row, + ) + assert result["mcp_servers"] == ["server-a"] + + +@pytest.mark.asyncio +async def test_validate_key_update_sentinels_do_not_grandfather(monkeypatch): + """Sentinels stored on the existing row must not grandfather anything.""" + _patch_grandfather_env(monkeypatch, _make_mock_mcp_manager("server-a")) + team_obj = _make_team_obj(mcp_servers=[]) + mock_prisma, existing_row = _make_grandfather_fixtures( + mcp_servers=[SpecialMCPServerName.all_proxy_servers.value, "no-mcp-servers"] + ) + with pytest.raises(HTTPException) as exc_info: + await validate_key_mcp_servers_against_team( + object_permission={"mcp_servers": ["server-a"]}, + team_obj=team_obj, + prisma_client=mock_prisma, + existing_key_object_permission=existing_row, + ) + assert exc_info.value.status_code == 403 + + def test_object_permission_dict_mirrors_pydantic_model(): """ObjectPermissionDict must stay field-for-field aligned with LiteLLM_ObjectPermissionBase. If a new field is added to the Pydantic diff --git a/tests/test_litellm/proxy/proxy_server/test_background_health.py b/tests/test_litellm/proxy/proxy_server/test_background_health.py index d5a97c0a087..990844369f7 100644 --- a/tests/test_litellm/proxy/proxy_server/test_background_health.py +++ b/tests/test_litellm/proxy/proxy_server/test_background_health.py @@ -581,3 +581,73 @@ async def test_run_background_health_check_runs_one_cycle_then_cancels(monkeypat "unhealthy_count": 1, "sleep_invoked": True, } + + +@pytest.mark.asyncio +async def test_run_background_health_check_probes_only_listed_model_groups(monkeypatch): + monkeypatch.setattr(proxy_server, "health_check_interval", 60) + monkeypatch.setattr(proxy_server, "health_check_concurrency", 1) + monkeypatch.setattr(proxy_server, "health_check_details", True) + monkeypatch.setattr(proxy_server, "use_shared_health_check", False) + monkeypatch.setattr(proxy_server, "redis_usage_cache", None) + monkeypatch.setattr(proxy_server, "prisma_client", None) + monkeypatch.setattr(proxy_server, "background_health_check_loop_active", False) + monkeypatch.setattr( + proxy_server, + "llm_router", + SimpleNamespace(background_health_check_model_groups=frozenset({"prod-openai"})), + ) + monkeypatch.setattr( + proxy_server, + "llm_model_list", + [ + {"model_name": "prod-openai", "model_info": {"id": "listed-1"}}, + {"model_name": "prod-openai", "model_info": {"id": "listed-2"}}, + {"model_name": "internal-claude", "model_info": {"id": "unlisted-1"}}, + { + "model_name": "prod-openai", + "model_info": { + "id": "listed-disabled", + "disable_background_health_check": True, + }, + }, + ], + ) + monkeypatch.setattr( + proxy_server, + "health_check_results", + {"healthy_endpoints": [], "unhealthy_endpoints": []}, + ) + + probed = {} + + async def _fake_direct(model_list, *_a, **_kw): + probed["ids"] = [m["model_info"]["id"] for m in model_list] + return ([], [], {}) + + monkeypatch.setattr( + proxy_server, + "_run_direct_health_check_with_instrumentation", + _fake_direct, + ) + monkeypatch.setattr( + proxy_server, "_schedule_background_health_check_db_save", lambda *a, **kw: None + ) + monkeypatch.setattr( + proxy_server, "_write_health_state_to_router_cache", lambda *a, **kw: None + ) + monkeypatch.setattr( + proxy_server, + "health_check_filter_kwargs_from_general_settings", + lambda _gs: {}, + ) + + async def _stop_sleep(_seconds): + raise asyncio.CancelledError() + + monkeypatch.setattr(proxy_server.asyncio, "sleep", _stop_sleep) + + with pytest.raises(asyncio.CancelledError): + await _run_background_health_check() + + assert probed["ids"] == ["listed-1", "listed-2"] diff --git a/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py b/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py index dda2f5a4d73..8f25cffecf5 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py +++ b/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py @@ -1767,16 +1767,20 @@ async def test_the_prune_cutoff_allows_for_clock_skew_between_hosts(): @pytest.mark.asyncio -async def test_a_run_pricing_config_cannot_prune_a_row_it_did_not_scan(monkeypatch): +async def test_a_run_pricing_config_cannot_prune_a_row_it_did_not_scan(): """Staleness alone stops being evidence once two hosts hold different configuration: a row this run never considered belongs to a deployment another host is pricing from its own file, and sweeping it drops that charge.""" table = _FakeSentinelTable() table.seed("t", DAY, "dep-elsewhere", 480.0, updated_at=datetime(2020, 1, 1, tzinfo=timezone.utc)) entry = _router_entry(model_id="cfg-here", model_info=dict(_VALID_PTU)) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(entry)) - await run_scheduled_ptu_rollup(_prisma_for([], table), pod_lock_manager=_pod_lock(acquired=True), target_date=DAY) + await run_scheduled_ptu_rollup( + _prisma_for([], table), + pod_lock_manager=_pod_lock(acquired=True), + target_date=DAY, + router=_router_holding(entry), + ) assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-elsewhere") in table.rows assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "cfg-here") in table.rows @@ -1784,7 +1788,7 @@ async def test_a_run_pricing_config_cannot_prune_a_row_it_did_not_scan(monkeypat @pytest.mark.asyncio -async def test_a_deployment_deleted_from_the_table_keeps_the_day_it_was_charged(monkeypatch): +async def test_a_deployment_deleted_from_the_table_keeps_the_day_it_was_charged(): """The accepted cost of bounding the prune, driven through the sequence that produces it: charge the day while the deployment exists, remove it, run the day again. Nothing scans it now, so nothing may judge its row, and the amount it was billed stands.""" @@ -1793,18 +1797,19 @@ async def test_a_deployment_deleted_from_the_table_keeps_the_day_it_was_charged( live_row = _model_row(model_id="dep-live", model_info=ptu) doomed_row = _model_row(model_id="dep-doomed", model_info=ptu) charged_key = ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-doomed") - monkeypatch.setattr( - ptu_rollup, "_running_router", lambda: _router_holding(_router_entry(model_id="cfg", model_info=dict(ptu))) - ) + router = _router_holding(_router_entry(model_id="cfg", model_info=dict(ptu))) await run_scheduled_ptu_rollup( - _prisma_for([live_row, doomed_row], table), pod_lock_manager=_pod_lock(acquired=True), target_date=DAY + _prisma_for([live_row, doomed_row], table), + pod_lock_manager=_pod_lock(acquired=True), + target_date=DAY, + router=router, ) billed = table.rows[charged_key]["ptu_flat_cost"] table.rows[charged_key]["updated_at"] = datetime(2020, 1, 1, tzinfo=timezone.utc) await run_scheduled_ptu_rollup( - _prisma_for([live_row], table), pod_lock_manager=_pod_lock(acquired=True), target_date=DAY + _prisma_for([live_row], table), pod_lock_manager=_pod_lock(acquired=True), target_date=DAY, router=router ) assert table.rows[charged_key]["ptu_flat_cost"] == billed @@ -1843,7 +1848,7 @@ async def test_every_deployment_that_prices_is_inside_the_set_that_bounds_the_pr table, ) - loaded = await ptu_rollup._load_ptu_models(prisma) + loaded = await ptu_rollup._load_ptu_models(prisma, router=None) assert {model.model_id for model in loaded.models} <= loaded.scanned_ids assert loaded.scanned_ids == {"dep-a", "dep-b", "dep-unpriced"} @@ -1859,7 +1864,7 @@ async def test_a_priced_deployment_is_in_the_bound_even_with_an_id_the_scan_skip _FakeSentinelTable(), ) - loaded = await ptu_rollup._load_ptu_models(prisma) + loaded = await ptu_rollup._load_ptu_models(prisma, router=None) assert {model.model_id for model in loaded.models} <= loaded.scanned_ids @@ -1873,13 +1878,13 @@ async def test_the_prune_splits_the_id_set_across_statements(monkeypatch): table = _FakeSentinelTable() ptu = {"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"} deployments = [_model_row(model_id=f"dep-{n}", model_info=ptu) for n in range(4)] - monkeypatch.setattr( - ptu_rollup, "_running_router", lambda: _router_holding(_router_entry(model_id="dep-4", model_info=dict(ptu))) - ) table.seed("t", DAY, "dep-3", 480.0, updated_at=datetime(2020, 1, 1, tzinfo=timezone.utc)) await run_scheduled_ptu_rollup( - _prisma_for(deployments, table), pod_lock_manager=_pod_lock(acquired=True), target_date=DAY + _prisma_for(deployments, table), + pod_lock_manager=_pod_lock(acquired=True), + target_date=DAY, + router=_router_holding(_router_entry(model_id="dep-4", model_info=dict(ptu))), ) chunks = [call["model"]["in"] for call in table.delete_many_calls] @@ -1912,140 +1917,123 @@ def _router_holding(*entries): @pytest.mark.asyncio -async def test_a_config_declared_deployment_is_priced(monkeypatch): +async def test_a_config_declared_deployment_is_priced(): """The whole point. A PTU deployment the proxy only knows from config.yaml is not in LiteLLM_ProxyModelTable, so a DB-only scan bills the provider's reservation to nobody.""" entry = _router_entry(model_id="cfg-1", model_name="gpt-4o-ptu", model_info=dict(_VALID_PTU)) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(entry)) - loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable())) + loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable()), router=_router_holding(entry)) assert [(m.model_id, m.model_name, m.team_id) for m in loaded.models] == [("cfg-1", "gpt-4o-ptu", "t")] assert "cfg-1" in loaded.scanned_ids @pytest.mark.asyncio -async def test_a_database_backed_router_entry_is_not_counted_twice(monkeypatch): +async def test_a_database_backed_router_entry_is_not_counted_twice(): """Every deployment loaded from the table is also in the router, flagged db_model. Pricing both copies would write two charges for one reservation.""" row = _model_row(model_id="db-1", model_info=dict(_VALID_PTU)) mirrored = _router_entry(model_id="db-1", model_info={**_VALID_PTU, "db_model": True}) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(mirrored)) - - loaded = await ptu_rollup._load_ptu_models(_prisma_for([row], _FakeSentinelTable())) - - assert [m.model_id for m in loaded.models] == ["db-1"] - - -@pytest.mark.asyncio -async def test_a_router_entry_sharing_an_id_with_the_table_is_priced_once(monkeypatch): - """db_model is data the router carries rather than something this module controls, so the - id anti-join is what actually maps onto the failure: two charges under one id.""" - row = _model_row(model_id="both-1", model_info=dict(_VALID_PTU)) - unflagged = _router_entry(model_id="both-1", model_info=dict(_VALID_PTU)) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(unflagged)) - - loaded = await ptu_rollup._load_ptu_models(_prisma_for([row], _FakeSentinelTable())) - - assert [m.model_id for m in loaded.models] == ["both-1"] - - -@pytest.mark.asyncio -async def test_a_client_credential_clone_is_not_priced(monkeypatch): - """Supplying an api_key on a request mints a clone of the deployment under a fresh id, - carrying the source's PTU config. Pricing it bills one reservation per distinct caller key.""" - source = _router_entry(model_id="cfg-1", model_info=dict(_VALID_PTU)) - clone = _router_entry(model_id="cfg-1-clone", model_info={**_VALID_PTU, "original_model_id": "cfg-1"}) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(source, clone)) - - loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable())) - - assert [m.model_id for m in loaded.models] == ["cfg-1"] - - -@pytest.mark.asyncio -async def test_a_config_deployment_without_ptu_config_is_scanned_but_not_priced(monkeypatch): - """It has to stay in the scanned set or its leftover sentinel rows become unprunable.""" - entry = _router_entry(model_id="cfg-plain", model_info={"team_id": "t"}) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(entry)) - - loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable())) - - assert loaded.models == () - assert "cfg-plain" in loaded.scanned_ids - - -@pytest.mark.asyncio -async def test_no_router_in_the_process_prices_the_database_alone(monkeypatch): - """The rollup is importable and callable outside a running proxy.""" - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: None) loaded = await ptu_rollup._load_ptu_models( - _prisma_for([_model_row(model_id="db-1", model_info=dict(_VALID_PTU))], _FakeSentinelTable()) + _prisma_for([row], _FakeSentinelTable()), router=_router_holding(mirrored) ) assert [m.model_id for m in loaded.models] == ["db-1"] @pytest.mark.asyncio -async def test_a_config_deployment_is_charged_end_to_end(monkeypatch): +async def test_a_router_entry_sharing_an_id_with_the_table_is_priced_once(): + """db_model is data the router carries rather than something this module controls, so the + id anti-join is what actually maps onto the failure: two charges under one id.""" + row = _model_row(model_id="both-1", model_info=dict(_VALID_PTU)) + unflagged = _router_entry(model_id="both-1", model_info=dict(_VALID_PTU)) + + loaded = await ptu_rollup._load_ptu_models( + _prisma_for([row], _FakeSentinelTable()), router=_router_holding(unflagged) + ) + + assert [m.model_id for m in loaded.models] == ["both-1"] + + +@pytest.mark.asyncio +async def test_a_client_credential_clone_is_not_priced(): + """Supplying an api_key on a request mints a clone of the deployment under a fresh id, + carrying the source's PTU config. Pricing it bills one reservation per distinct caller key.""" + source = _router_entry(model_id="cfg-1", model_info=dict(_VALID_PTU)) + clone = _router_entry(model_id="cfg-1-clone", model_info={**_VALID_PTU, "original_model_id": "cfg-1"}) + + loaded = await ptu_rollup._load_ptu_models( + _prisma_for([], _FakeSentinelTable()), router=_router_holding(source, clone) + ) + + assert [m.model_id for m in loaded.models] == ["cfg-1"] + + +@pytest.mark.asyncio +async def test_a_config_deployment_without_ptu_config_is_scanned_but_not_priced(): + """It has to stay in the scanned set or its leftover sentinel rows become unprunable.""" + entry = _router_entry(model_id="cfg-plain", model_info={"team_id": "t"}) + + loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable()), router=_router_holding(entry)) + + assert loaded.models == () + assert "cfg-plain" in loaded.scanned_ids + + +@pytest.mark.asyncio +async def test_no_router_in_the_process_prices_the_database_alone(): + """The rollup is importable and callable outside a running proxy.""" + loaded = await ptu_rollup._load_ptu_models( + _prisma_for([_model_row(model_id="db-1", model_info=dict(_VALID_PTU))], _FakeSentinelTable()), router=None + ) + + assert [m.model_id for m in loaded.models] == ["db-1"] + + +@pytest.mark.asyncio +async def test_a_config_deployment_is_charged_end_to_end(): """Through the scheduled entry point, so the charge lands in a sentinel row rather than stopping at the loader.""" table = _FakeSentinelTable() entry = _router_entry(model_id="cfg-1", model_name="gpt-4o-ptu", model_info=dict(_VALID_PTU)) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(entry)) - await run_scheduled_ptu_rollup(_prisma_for([], table), pod_lock_manager=_pod_lock(acquired=True), target_date=DAY) + await run_scheduled_ptu_rollup( + _prisma_for([], table), + pod_lock_manager=_pod_lock(acquired=True), + target_date=DAY, + router=_router_holding(entry), + ) assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "cfg-1") in table.rows @pytest.mark.asyncio -async def test_a_stale_database_backed_router_entry_is_not_treated_as_config(monkeypatch): +async def test_a_stale_database_backed_router_entry_is_not_treated_as_config(): """The reconcile can leave a deployment on the router after its row is gone. The id anti-join cannot see that one, so the flag is what keeps it from being priced as though config.yaml had declared it.""" stale = _router_entry(model_id="db-gone", model_info={**_VALID_PTU, "db_model": True}) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(stale)) - loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable())) + loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable()), router=_router_holding(stale)) assert loaded.models == () -def test_the_router_lookup_reads_the_proxys_own_global(): - """Every other config test replaces this helper, so without one test driving the real - body a typo in the module path or the attribute name leaves the whole feature dead in - production with the suite still green.""" - import sys - import types as _types +@pytest.mark.asyncio +async def test_a_router_left_on_the_proxy_module_is_not_scanned(monkeypatch): + """A run scans the router its caller hands it and nothing else. Reading the proxy module's + global instead made every run depend on whatever else in the process had set one, which + is what a caller passing no router is asking not to happen.""" + import litellm.proxy.proxy_server as proxy_server - assert ptu_rollup._running_router() is None or "litellm.proxy.proxy_server" in sys.modules + ambient = _router_holding(_router_entry(model_id="ambient-1", model_info=dict(_VALID_PTU))) + monkeypatch.setattr(proxy_server, "llm_router", ambient, raising=False) - sentinel = object() - stub = _types.SimpleNamespace(llm_router=sentinel) - real = sys.modules.get("litellm.proxy.proxy_server") - sys.modules["litellm.proxy.proxy_server"] = stub - try: - assert ptu_rollup._running_router() is sentinel - del stub.llm_router - assert ptu_rollup._running_router() is None - finally: - if real is None: - del sys.modules["litellm.proxy.proxy_server"] - else: - sys.modules["litellm.proxy.proxy_server"] = real + loaded = await ptu_rollup._load_ptu_models(_prisma_for([], _FakeSentinelTable()), router=None) - -def test_the_router_lookup_returns_none_outside_a_proxy(): - import sys - - real = sys.modules.pop("litellm.proxy.proxy_server", None) - try: - assert ptu_rollup._running_router() is None - finally: - if real is not None: - sys.modules["litellm.proxy.proxy_server"] = real + assert loaded.models == () + assert loaded.scanned_ids == frozenset() def test_the_prune_filter_is_a_plain_dict(): @@ -2074,7 +2062,7 @@ async def test_a_run_that_scanned_nothing_issues_no_delete_statements(): @pytest.mark.asyncio -async def test_the_catch_up_pass_reaches_a_config_declared_deployment(monkeypatch): +async def test_the_catch_up_pass_reaches_a_config_declared_deployment(): """The catch-up shares the loader, so config deployments join it without being wired in. That is what prices the elapsed days of a reservation declared before today.""" table = _FakeSentinelTable() @@ -2084,9 +2072,10 @@ async def test_the_catch_up_pass_reaches_a_config_declared_deployment(monkeypatc model_id="cfg-back", model_info={"ptu_count": 100, "cost_per_ptu_per_hour": 0.02, "team_id": "t", "ptu_effective_from": started}, ) - monkeypatch.setattr(ptu_rollup, "_running_router", lambda: _router_holding(entry)) - await run_scheduled_ptu_rollup(_prisma_for([], table), pod_lock_manager=_pod_lock(acquired=True)) + await run_scheduled_ptu_rollup( + _prisma_for([], table), pod_lock_manager=_pod_lock(acquired=True), router=_router_holding(entry) + ) charged = sorted(day for (_, day, _, model) in table.rows if model == "cfg-back") yesterday = (now.date() - timedelta(days=1)).isoformat() 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 f60177a6455..19ceb3d3d1f 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 @@ -1,6 +1,7 @@ import asyncio import collections import datetime +import hashlib import json import re from datetime import timezone @@ -96,6 +97,7 @@ def _reconstruct_ui_where_from_sql(sql_query, params): msg = re.search(r"error_message' LIKE \$(\d+)", cond) sess = re.fullmatch(r"session_id LIKE \$(\d+)", cond) status = re.fullmatch(r"status = \$(\d+)", cond) + api_key_not_in = re.fullmatch(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", cond) if gte: date_bounds["gte"] = _iso(params[int(gte.group(1)) - 1]) elif lte: @@ -104,10 +106,19 @@ def _reconstruct_ui_where_from_sql(sql_query, params): where["OR"] = where.get("OR", []) + [{"multi_team": True}] elif "status = 'success'" in cond: where["OR"] = where.get("OR", []) + [{"status": "success"}] + elif cond == "LOWER(cache_hit) = 'true'": + where["cache_hit"] = "hit" + elif cond == "(cache_hit IS NULL OR LOWER(cache_hit) != 'true')": + where["cache_hit"] = "miss" elif sess: where["session_id"] = {"contains": str(params[int(sess.group(1)) - 1]).strip("%")} elif status: where["status"] = {"equals": params[int(status.group(1)) - 1]} + elif api_key_not_in: + where["api_key_not_in"] = [ + params[int(api_key_not_in.group(1)) - 1], + params[int(api_key_not_in.group(2)) - 1], + ] elif alias: metadata_conds.append( { @@ -196,6 +207,7 @@ def make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup_fn=No return MockPrismaClient() +from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME from litellm.proxy._types import ( LitellmUserRoles, Member, @@ -1256,6 +1268,140 @@ async def test_ui_view_spend_logs_with_team_id(client, monkeypatch): app.dependency_overrides.pop(ps.user_api_key_auth, None) +_HEALTH_CHECK_HASHED_API_KEY = hashlib.sha256(LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME.encode()).hexdigest() + + +def _spend_logs_with_health_check_rows(): + now = datetime.datetime.now(timezone.utc).isoformat() + return [ + { + "id": "log1", + "request_id": "req1", + "api_key": "sk-test-key", + "user": "test_user_1", + "team_id": None, + "spend": 0.05, + "startTime": now, + "model": "gpt-4", + }, + { + "id": "log2", + "request_id": "req2", + "api_key": _HEALTH_CHECK_HASHED_API_KEY, + "user": None, + "team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, + "spend": 0.0, + "startTime": now, + "model": "gpt-4", + }, + { + "id": "log3", + "request_id": "req3", + "api_key": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, + "user": None, + "team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, + "spend": 0.0, + "startTime": now, + "model": "gpt-4", + }, + ] + + +@pytest.mark.asyncio +async def test_ui_view_spend_logs_exclude_internal_health_checks(client, monkeypatch): + mock_spend_logs = _spend_logs_with_health_check_rows() + + def filter_health_checks(where): + excluded = where.get("api_key_not_in") + if excluded is None: + return mock_spend_logs + return [log for log in mock_spend_logs if log["api_key"] not in excluded] + + observed_queries = [] + + def observe_query(sql_query, params): + if 'FROM "LiteLLM_SpendLogs"' in sql_query: + observed_queries.append((sql_query, params)) + + monkeypatch.setattr( + "litellm.proxy.proxy_server.prisma_client", + make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query), + ) + app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user" + ) + + try: + start_date, end_date = _default_date_range() + response = client.get( + "/spend/logs/ui", + params={ + "exclude_internal_health_checks": "true", + "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 [row["request_id"] for row in data["data"]] == ["req1"] + + page_sql, page_params = next((sql, params) for sql, params in observed_queries if "ORDER BY" in sql) + not_in = re.search(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", page_sql) + assert not_in is not None + assert LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME not in page_sql + assert _HEALTH_CHECK_HASHED_API_KEY not in page_sql + assert { + page_params[int(not_in.group(1)) - 1], + page_params[int(not_in.group(2)) - 1], + } == {LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, _HEALTH_CHECK_HASHED_API_KEY} + finally: + app.dependency_overrides.pop(ps.user_api_key_auth, None) + + +@pytest.mark.asyncio +async def test_ui_view_spend_logs_includes_internal_health_checks_by_default(client, monkeypatch): + mock_spend_logs = _spend_logs_with_health_check_rows() + + def filter_health_checks(where): + excluded = where.get("api_key_not_in") + if excluded is None: + return mock_spend_logs + return [log for log in mock_spend_logs if log["api_key"] not in excluded] + + observed_queries = [] + + def observe_query(sql_query, params): + if 'FROM "LiteLLM_SpendLogs"' in sql_query: + observed_queries.append((sql_query, params)) + + monkeypatch.setattr( + "litellm.proxy.proxy_server.prisma_client", + make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query), + ) + app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user" + ) + + try: + start_date, end_date = _default_date_range() + response = client.get( + "/spend/logs/ui", + params={"start_date": start_date, "end_date": end_date}, + headers={"Authorization": "Bearer sk-test"}, + ) + + assert response.status_code == 200 + data = response.json() + assert data["total"] == 3 + assert [row["request_id"] for row in data["data"]] == ["req1", "req2", "req3"] + assert all("NOT IN" not in sql for sql, _ in observed_queries) + finally: + app.dependency_overrides.pop(ps.user_api_key_auth, None) + + @pytest.mark.asyncio async def test_ui_view_spend_logs_internal_user_scoped_without_user_id( client, monkeypatch @@ -2302,6 +2448,96 @@ async def test_ui_view_spend_logs_with_status(client, monkeypatch): app.dependency_overrides.pop(ps.user_api_key_auth, None) +@pytest.mark.asyncio +async def test_ui_view_spend_logs_with_cache_hit_filter(client, monkeypatch): + base = { + "api_key": "sk-test-key", + "user": "test_user_1", + "team_id": "team1", + "spend": 0.05, + "startTime": datetime.datetime.now(timezone.utc).isoformat(), + "model": "gpt-4", + "status": "success", + } + mock_spend_logs = [ + {**base, "id": "log1", "request_id": "req-hit", "cache_hit": "True"}, + {**base, "id": "log2", "request_id": "req-miss", "cache_hit": "False"}, + {**base, "id": "log3", "request_id": "req-legacy", "cache_hit": "None"}, + {**base, "id": "log4", "request_id": "req-null", "cache_hit": None}, + ] + + def filter_by_cache(where): + cache_filter = where.get("cache_hit") + if cache_filter == "hit": + return [log for log in mock_spend_logs if str(log["cache_hit"]).lower() == "true"] + if cache_filter == "miss": + return [log for log in mock_spend_logs if str(log["cache_hit"]).lower() != "true"] + return mock_spend_logs + + monkeypatch.setattr( + "litellm.proxy.proxy_server.prisma_client", + make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_cache), + ) + + 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={ + "cache_hit_filter": "hit", + "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 [row["request_id"] for row in data["data"]] == ["req-hit"] + + response = client.get( + "/spend/logs/ui", + params={ + "cache_hit_filter": "miss", + "start_date": start_date, + "end_date": end_date, + }, + headers={"Authorization": "Bearer sk-test"}, + ) + assert response.status_code == 200 + data = response.json() + assert data["total"] == 3 + assert [row["request_id"] for row in data["data"]] == ["req-miss", "req-legacy", "req-null"] + + response = client.get( + "/spend/logs/ui", + params={ + "start_date": start_date, + "end_date": end_date, + }, + headers={"Authorization": "Bearer sk-test"}, + ) + assert response.status_code == 200 + assert response.json()["total"] == 4 + + response = client.get( + "/spend/logs/ui", + params={ + "cache_hit_filter": "invalid", + "start_date": start_date, + "end_date": end_date, + }, + headers={"Authorization": "Bearer sk-test"}, + ) + assert response.status_code == 400 + finally: + app.dependency_overrides.pop(ps.user_api_key_auth, None) + + @pytest.mark.asyncio async def test_ui_view_spend_logs_with_model(client, monkeypatch): mock_spend_logs = [ diff --git a/tests/test_litellm/proxy/test_health_check_functions.py b/tests/test_litellm/proxy/test_health_check_functions.py index f2d95131e5e..fdae11d517a 100644 --- a/tests/test_litellm/proxy/test_health_check_functions.py +++ b/tests/test_litellm/proxy/test_health_check_functions.py @@ -623,5 +623,53 @@ async def test_perform_health_check_and_save_forwards_skip_disabled_background_f assert call_kwargs["health_check_skip_disabled_background_models"] is True +def test_parse_background_health_check_model_groups_unset_returns_none(): + from litellm.proxy.health_check import parse_background_health_check_model_groups + + assert parse_background_health_check_model_groups(None) is None + assert parse_background_health_check_model_groups({}) is None + assert ( + parse_background_health_check_model_groups( + {"background_health_check_model_groups": None} + ) + is None + ) + + +def test_parse_background_health_check_model_groups_list_returns_frozenset(): + from litellm.proxy.health_check import parse_background_health_check_model_groups + + parsed = parse_background_health_check_model_groups( + {"background_health_check_model_groups": ["prod-openai", "prod-claude"]} + ) + assert parsed == frozenset({"prod-openai", "prod-claude"}) + + +@pytest.mark.parametrize("bad_value", ["prod-openai", 42, {"a": 1}, [1, 2], [None]]) +def test_parse_background_health_check_model_groups_malformed_raises(bad_value): + from litellm.proxy.health_check import parse_background_health_check_model_groups + + with pytest.raises(ValueError, match="must be a list of model group names"): + parse_background_health_check_model_groups( + {"background_health_check_model_groups": bad_value} + ) + + +def test_filter_deployments_to_model_groups(): + from litellm.proxy.health_check import filter_deployments_to_model_groups + + model_list = [ + {"model_name": "prod-openai", "model_info": {"id": "a"}}, + {"model_name": "internal-claude", "model_info": {"id": "b"}}, + {"model_name": "prod-openai", "model_info": {"id": "c"}}, + ] + + assert filter_deployments_to_model_groups(model_list, None) == tuple(model_list) + assert filter_deployments_to_model_groups( + model_list, frozenset({"prod-openai"}) + ) == (model_list[0], model_list[2]) + assert filter_deployments_to_model_groups(model_list, frozenset()) == () + + if __name__ == "__main__": pytest.main([__file__]) diff --git a/tests/test_litellm/proxy/test_lazy_openapi_snapshot.py b/tests/test_litellm/proxy/test_lazy_openapi_snapshot.py index 79330b0e3a6..f9ef98bc474 100644 --- a/tests/test_litellm/proxy/test_lazy_openapi_snapshot.py +++ b/tests/test_litellm/proxy/test_lazy_openapi_snapshot.py @@ -1,8 +1,9 @@ +import json import sys from types import ModuleType, SimpleNamespace from litellm.proxy._lazy_features import LazyFeature -from litellm.proxy._lazy_openapi_snapshot import _normalize_operation_ids +from litellm.proxy._lazy_openapi_snapshot import SnapshotResult, _normalize_operation_ids, main def test_generate_snapshot_uses_shared_operation_id_reservations(monkeypatch): @@ -61,7 +62,7 @@ def test_generate_snapshot_uses_shared_operation_id_reservations(monkeypatch): monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy_server_module) monkeypatch.setattr("fastapi.openapi.utils.get_openapi", fake_get_openapi) - fragments = _lazy_openapi_snapshot.generate_snapshot() + fragments = _lazy_openapi_snapshot.generate_snapshot().fragments assert fragments["feature-a"]["paths"]["/feature-a/items"]["get"]["operationId"] == "shared_operation_id_get" assert fragments["feature-b"]["paths"]["/feature-b/items"]["get"]["operationId"] == "shared_operation_id_get_2" @@ -106,7 +107,7 @@ def test_generate_snapshot_registers_transitively_imported_modules(monkeypatch): monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy_server_module) monkeypatch.setattr("fastapi.openapi.utils.get_openapi", fake_get_openapi) - fragments = _lazy_openapi_snapshot.generate_snapshot() + fragments = _lazy_openapi_snapshot.generate_snapshot().fragments assert fragments["transitive"]["paths"]["/transitive/items"]["get"]["tags"] == ["transitive"] assert "/v1/{param}/deep/leaf" in fragments["transitive"]["paths"] @@ -144,3 +145,66 @@ def test_normalize_operation_ids_preserves_custom_ids(): operations = paths["/proxy/{endpoint}"] assert operations["get"]["operationId"] == "custom_operation" assert operations["post"]["operationId"] == "custom_operation" + + +def test_generate_snapshot_reports_features_whose_import_fails(monkeypatch): + from litellm.proxy import _lazy_openapi_snapshot + + fake_app = SimpleNamespace(title="LiteLLM test", version="0.0.0", routes=[]) + + fake_module = ModuleType("fake_importable_feature") + monkeypatch.setitem(sys.modules, "fake_importable_feature", fake_module) + + def register_fn(app, module): + app.routes.append(SimpleNamespace(path="/importable/items")) + + fake_lazy_features_module = ModuleType("litellm.proxy._lazy_features") + fake_lazy_features_module.LAZY_FEATURES = [ + LazyFeature( + name="importable", + module_path="fake_importable_feature", + path_prefixes=("/importable",), + register_fn=register_fn, + ), + LazyFeature( + name="broken", + module_path="litellm.proxy.this_module_does_not_exist", + path_prefixes=("/broken",), + ), + ] + monkeypatch.setitem(sys.modules, "litellm.proxy._lazy_features", fake_lazy_features_module) + + def fake_get_openapi(title, version, routes): + return {"paths": {route.path: {"get": {"operationId": "importable_get"}} for route in routes}} + + fake_proxy_server_module = ModuleType("litellm.proxy.proxy_server") + fake_proxy_server_module.app = fake_app + fake_proxy_server_module.ensure_unique_openapi_operation_ids = lambda schema, reserved_operation_ids: schema + monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy_server_module) + monkeypatch.setattr("fastapi.openapi.utils.get_openapi", fake_get_openapi) + + result = _lazy_openapi_snapshot.generate_snapshot() + + assert result.skipped == ("broken",) + assert sorted(result.fragments) == ["importable"] + + +def test_main_refuses_to_write_a_snapshot_missing_skipped_features(tmp_path, capsys): + snapshot_file = tmp_path / "snapshot.json" + result = SnapshotResult(fragments={"importable": {"paths": {}, "components": {"schemas": {}}}}, skipped=("broken",)) + + assert main(snapshot_file, generate=lambda: result) == 1 + assert not snapshot_file.exists() + assert "broken" in capsys.readouterr().err + + +def test_main_writes_sorted_snapshot_when_every_feature_loads(tmp_path): + snapshot_file = tmp_path / "snapshot.json" + fragments = { + "zeta": {"paths": {"/z": {}}, "components": {"schemas": {}}}, + "alpha": {"paths": {}, "components": {"schemas": {}}}, + } + + assert main(snapshot_file, generate=lambda: SnapshotResult(fragments=fragments, skipped=())) == 0 + assert json.loads(snapshot_file.read_text()) == fragments + assert snapshot_file.read_text() == json.dumps(fragments, indent=2, sort_keys=True) + "\n" diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py index 50ef6f29ec2..503cf40244e 100644 --- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py +++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py @@ -234,6 +234,40 @@ async def test_add_litellm_data_to_request_parses_string_metadata(): assert updated_data["metadata"]["generation_name"] == "gen123" +@pytest.mark.asyncio +async def test_key_otel_service_name_outranks_team_metadata_merge(): + from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request + + request_mock = MagicMock(spec=Request) + request_mock.url = MagicMock() + request_mock.url.path = "/v1/chat/completions" + request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions" + request_mock.method = "POST" + request_mock.query_params = {} + request_mock.headers = {"Content-Type": "application/json"} + request_mock.client = MagicMock() + request_mock.client.host = "127.0.0.1" + + user_api_key_dict = UserAPIKeyAuth( + api_key="hashed-key", + metadata={"otel_service_name": "key-svc"}, + team_metadata={"otel_service_name": "team-svc", "other_setting": "team-val"}, + ) + + updated_data = await add_litellm_data_to_request( + data={"model": "gpt-3.5-turbo"}, + request=request_mock, + user_api_key_dict=user_api_key_dict, + proxy_config=MagicMock(), + general_settings={}, + version="test-version", + ) + + auth_metadata = updated_data["metadata"]["user_api_key_auth_metadata"] + assert auth_metadata["otel_service_name"] == "key-svc" + assert auth_metadata["other_setting"] == "team-val" + + @pytest.mark.asyncio async def test_stamped_auth_object_reflects_header_derived_identity(): """ diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py index f51648faf80..2c8ae9f0370 100644 --- a/tests/test_litellm/proxy/test_proxy_server.py +++ b/tests/test_litellm/proxy/test_proxy_server.py @@ -11245,6 +11245,35 @@ async def test_ptu_rollup_job_registered_at_startup(monkeypatch): assert scheduler.get_job(PTU_ROLLUP_JOB_ID) is not None +@pytest.mark.asyncio +async def test_ptu_rollup_job_hands_the_rollup_the_proxys_router(monkeypatch): + """The rollup prices PTU deployments declared in config.yaml, which only the router + knows about. It takes the router as an argument, so nothing but this call site puts the + proxy's own router in front of it: without it that half of the feature is dead.""" + monkeypatch.delenv("STORE_MODEL_IN_DB", raising=False) + from litellm.proxy.spend_tracking import ptu_flat_cost_rollup + from litellm.proxy.spend_tracking.ptu_feature_flag import PTU_COST_ATTRIBUTION_ENV_VAR + from litellm.proxy.spend_tracking.ptu_flat_cost_rollup import PTU_ROLLUP_JOB_ID + + monkeypatch.setenv(PTU_COST_ATTRIBUTION_ENV_VAR, "true") + calls = [] + monkeypatch.setattr( + ptu_flat_cost_rollup, + "run_scheduled_ptu_rollup", + AsyncMock(side_effect=lambda *args, **kwargs: calls.append(kwargs)), + ) + + scheduler = await _run_scheduled_background_jobs() + + import litellm.proxy.proxy_server as ps + + router = MagicMock() + monkeypatch.setattr(ps, "llm_router", router) + await scheduler.get_job(PTU_ROLLUP_JOB_ID).func() + + assert [call["router"] for call in calls] == [router] + + @pytest.mark.asyncio async def test_ptu_rollup_job_not_registered_without_opt_in(monkeypatch): """Without LITELLM_ENABLE_PTU_COST_ATTRIBUTION the rollup never runs, so no sentinel row diff --git a/tests/test_litellm/router_utils/test_health_check_allowed_fails_integration.py b/tests/test_litellm/router_utils/test_health_check_allowed_fails_integration.py index 64239f33966..6effbc5fa7f 100644 --- a/tests/test_litellm/router_utils/test_health_check_allowed_fails_integration.py +++ b/tests/test_litellm/router_utils/test_health_check_allowed_fails_integration.py @@ -502,6 +502,68 @@ class TestHealthCheckFilterBypassWithPolicy: ) assert len(result) == 2 + def _make_scoped_router_with_unhealthy(self, policy) -> Router: + import time + + from litellm.caching.caching import DualCache + from litellm.router_utils.health_state_cache import DeploymentHealthCache + + router = Router( + model_list=[ + _make_model("bad-listed"), + _make_model("ok-listed"), + _make_model("bad-unlisted", "gpt-5"), + ], + allowed_fails_policy=policy, + enable_health_check_routing=True, + background_health_check_model_groups=["gpt-4"], + ) + cache = DualCache() + health_cache = DeploymentHealthCache(cache=cache, staleness_threshold=60.0) + health_cache.set_deployment_health_states( + { + model_id: { + "is_healthy": False, + "timestamp": time.time(), + "reason": "test", + } + for model_id in ("bad-listed", "bad-unlisted") + } + ) + router.health_state_cache = health_cache + return router + + def test_filter_with_policy_still_applies_to_listed_groups(self): + """A model-group allowlist keeps the filter active for listed groups even with a policy set.""" + router = self._make_scoped_router_with_unhealthy( + AllowedFailsPolicy(AuthenticationErrorAllowedFails=3) + ) + deployments = [ + _make_model("bad-listed"), + _make_model("ok-listed"), + _make_model("bad-unlisted", "gpt-5"), + ] + + result = router._filter_health_check_unhealthy_deployments(deployments) + assert [d["model_info"]["id"] for d in result] == ["ok-listed", "bad-unlisted"] + + @pytest.mark.asyncio + async def test_async_filter_with_policy_still_applies_to_listed_groups(self): + """Async version: listed groups stay filtered with a policy set, unlisted stay untouched.""" + router = self._make_scoped_router_with_unhealthy( + AllowedFailsPolicy(TimeoutErrorAllowedFails=2) + ) + deployments = [ + _make_model("bad-listed"), + _make_model("ok-listed"), + _make_model("bad-unlisted", "gpt-5"), + ] + + result = await router._async_filter_health_check_unhealthy_deployments( + deployments + ) + assert [d["model_info"]["id"] for d in result] == ["ok-listed", "bad-unlisted"] + class TestAllDeploymentsInCooldownSafetyNet: """ diff --git a/tests/test_litellm/router_utils/test_health_state_cache.py b/tests/test_litellm/router_utils/test_health_state_cache.py index 1af61e899be..ffd031f9b7d 100644 --- a/tests/test_litellm/router_utils/test_health_state_cache.py +++ b/tests/test_litellm/router_utils/test_health_state_cache.py @@ -111,3 +111,84 @@ def test_malformed_state_entries_are_skipped(health_cache): health_cache.set_deployment_health_states(states) result = health_cache.get_unhealthy_deployment_ids() assert result == {"deploy-1"} + + +def test_set_merges_states_from_scoped_writers(health_cache): + """A writer covering one scope must not erase another scope's fresh states.""" + now = time.time() + health_cache.set_deployment_health_states( + {"listed-bad": {"is_healthy": False, "timestamp": now, "reason": "check_failed"}} + ) + health_cache.set_deployment_health_states( + {"other-ok": {"is_healthy": True, "timestamp": now, "reason": ""}} + ) + assert health_cache.get_unhealthy_deployment_ids() == {"listed-bad"} + + +def test_set_prunes_expired_entries(health_cache, cache): + """Entries older than 1.5x the staleness threshold are dropped on write.""" + expired_time = time.time() - 100 # threshold 60s, prune horizon 90s + health_cache.set_deployment_health_states( + {"gone": {"is_healthy": False, "timestamp": expired_time, "reason": "check_failed"}} + ) + now = time.time() + health_cache.set_deployment_health_states( + {"fresh": {"is_healthy": False, "timestamp": now, "reason": "check_failed"}} + ) + stored = cache.get_cache(key=DeploymentHealthCache.CACHE_KEY) + assert set(stored.keys()) == {"fresh"} + + +class _SharedRedisFake: + """Shared get/set key-value store standing in for the Redis layer of a DualCache.""" + + def __init__(self): + self.store = {} + self.fail_get = False + + def get_cache(self, key, parent_otel_span=None, **kwargs): + if self.fail_get: + return None # RedisCache.get_cache swallows connection errors and returns None + return self.store.get(key) + + def set_cache(self, key, value, **kwargs): + self.store[key] = value + + +def test_scoped_writers_on_shared_redis_preserve_each_other(): + """Pods with different allowlists share one Redis entry; each merge must keep the peer's scope.""" + redis_fake = _SharedRedisFake() + pod_a = DeploymentHealthCache(cache=DualCache(redis_cache=redis_fake), staleness_threshold=60.0) + pod_b = DeploymentHealthCache(cache=DualCache(redis_cache=redis_fake), staleness_threshold=60.0) + pod_a.set_deployment_health_states( + {"prod-bad": {"is_healthy": False, "timestamp": time.time(), "reason": "check_failed"}} + ) + pod_b.set_deployment_health_states( + {"internal-bad": {"is_healthy": False, "timestamp": time.time(), "reason": "timeout"}} + ) + pod_a.set_deployment_health_states( + {"prod-bad": {"is_healthy": False, "timestamp": time.time(), "reason": "check_failed"}} + ) + assert set(redis_fake.store[DeploymentHealthCache.CACHE_KEY]) == {"prod-bad", "internal-bad"} + assert pod_a.get_unhealthy_deployment_ids() == {"prod-bad", "internal-bad"} + + +def test_failed_redis_read_falls_back_to_local_copy(): + """A swallowed Redis GET error must not make a writer erase peer scopes it already saw.""" + redis_fake = _SharedRedisFake() + pod_a = DeploymentHealthCache(cache=DualCache(redis_cache=redis_fake), staleness_threshold=60.0) + pod_b = DeploymentHealthCache(cache=DualCache(redis_cache=redis_fake), staleness_threshold=60.0) + pod_a.set_deployment_health_states( + {"prod-bad": {"is_healthy": False, "timestamp": time.time(), "reason": "check_failed"}} + ) + pod_b.set_deployment_health_states( + {"internal-bad": {"is_healthy": False, "timestamp": time.time(), "reason": "timeout"}} + ) + pod_a.set_deployment_health_states( + {"prod-bad": {"is_healthy": False, "timestamp": time.time(), "reason": "check_failed"}} + ) + redis_fake.fail_get = True + pod_a.set_deployment_health_states( + {"prod-bad": {"is_healthy": False, "timestamp": time.time(), "reason": "check_failed"}} + ) + assert set(redis_fake.store[DeploymentHealthCache.CACHE_KEY]) == {"prod-bad", "internal-bad"} diff --git a/tests/test_litellm/router_utils/test_router_health_check_routing.py b/tests/test_litellm/router_utils/test_router_health_check_routing.py index b87a39ac1de..46ed679f746 100644 --- a/tests/test_litellm/router_utils/test_router_health_check_routing.py +++ b/tests/test_litellm/router_utils/test_router_health_check_routing.py @@ -43,7 +43,12 @@ def _make_health_cache( class TestFilterHealthCheckUnhealthyDeployments: """Test the sync filter method.""" - def _make_router_like(self, enable: bool, health_cache: DeploymentHealthCache): + def _make_router_like( + self, + enable: bool, + health_cache: DeploymentHealthCache, + model_groups: frozenset[str] | None = None, + ): """Create a minimal object that behaves like Router for filter testing.""" class FakeRouter: @@ -51,6 +56,7 @@ class TestFilterHealthCheckUnhealthyDeployments: self.enable_health_check_routing = enable self.health_state_cache = health_cache self.allowed_fails_policy = None + self.background_health_check_model_groups = model_groups # Import the actual method and bind it from litellm.router import Router @@ -115,11 +121,50 @@ class TestFilterHealthCheckUnhealthyDeployments: result = router._filter_health_check_unhealthy_deployments(deployments) assert len(result) == 2 + def test_filter_scoped_to_listed_model_groups(self): + """With an allowlist, only deployments in listed groups are filtered on health.""" + health_cache = _make_health_cache(unhealthy_ids={"bad-listed", "bad-unlisted"}) + router = self._make_router_like( + enable=True, health_cache=health_cache, model_groups=frozenset({"prod"}) + ) + + deployments = [ + _make_deployment("bad-listed", model_name="prod"), + _make_deployment("ok-listed", model_name="prod"), + _make_deployment("bad-unlisted", model_name="other"), + _make_deployment("ok-unlisted", model_name="other"), + ] + result = router._filter_health_check_unhealthy_deployments(deployments) + assert [d["model_info"]["id"] for d in result] == [ + "ok-listed", + "bad-unlisted", + "ok-unlisted", + ] + + def test_filter_unscoped_when_model_groups_unset(self): + """Without an allowlist, unhealthy deployments in every group are filtered.""" + health_cache = _make_health_cache(unhealthy_ids={"bad-listed", "bad-unlisted"}) + router = self._make_router_like(enable=True, health_cache=health_cache) + + deployments = [ + _make_deployment("bad-listed", model_name="prod"), + _make_deployment("ok-listed", model_name="prod"), + _make_deployment("bad-unlisted", model_name="other"), + _make_deployment("ok-unlisted", model_name="other"), + ] + result = router._filter_health_check_unhealthy_deployments(deployments) + assert [d["model_info"]["id"] for d in result] == ["ok-listed", "ok-unlisted"] + class TestAsyncFilterHealthCheckUnhealthyDeployments: """Test the async filter method.""" - def _make_router_like(self, enable: bool, health_cache: DeploymentHealthCache): + def _make_router_like( + self, + enable: bool, + health_cache: DeploymentHealthCache, + model_groups: frozenset[str] | None = None, + ): from litellm.router import Router class FakeRouter: @@ -127,6 +172,7 @@ class TestAsyncFilterHealthCheckUnhealthyDeployments: self.enable_health_check_routing = enable self.health_state_cache = health_cache self.allowed_fails_policy = None + self.background_health_check_model_groups = model_groups fake = FakeRouter() fake._async_filter_health_check_unhealthy_deployments = ( @@ -168,6 +214,29 @@ class TestAsyncFilterHealthCheckUnhealthyDeployments: ) assert len(result) == 2 # safety net + @pytest.mark.asyncio + async def test_async_filter_scoped_to_listed_model_groups(self): + """Async version: only deployments in listed groups are filtered on health.""" + health_cache = _make_health_cache(unhealthy_ids={"bad-listed", "bad-unlisted"}) + router = self._make_router_like( + enable=True, health_cache=health_cache, model_groups=frozenset({"prod"}) + ) + + deployments = [ + _make_deployment("bad-listed", model_name="prod"), + _make_deployment("ok-listed", model_name="prod"), + _make_deployment("bad-unlisted", model_name="other"), + _make_deployment("ok-unlisted", model_name="other"), + ] + result = await router._async_filter_health_check_unhealthy_deployments( + healthy_deployments=deployments + ) + assert [d["model_info"]["id"] for d in result] == [ + "ok-listed", + "bad-unlisted", + "ok-unlisted", + ] + class TestBuildDeploymentHealthStates: """Test the build_deployment_health_states function.""" diff --git a/tests/test_litellm/test_anthropic_sonnet_1hr_cache_pricing.py b/tests/test_litellm/test_anthropic_sonnet_1hr_cache_pricing.py index f534b431508..11fcdf31dfc 100644 --- a/tests/test_litellm/test_anthropic_sonnet_1hr_cache_pricing.py +++ b/tests/test_litellm/test_anthropic_sonnet_1hr_cache_pricing.py @@ -87,3 +87,56 @@ def test_anthropic_sonnet_1hr_cache_write_pricing( ), f"{model_key}: long-context 1hr/5min ratio is {ratio_lc}, expected 1.6" else: assert "cache_creation_input_token_cost_above_1hr_above_200k_tokens" not in info + + +CLAUDE_3_EXPECTED = [ + ("claude-3-haiku-20240307", 5e-07), + ("claude-3-opus-20240229", 3e-05), +] + + +@pytest.mark.parametrize("model_key, expected_1hr", CLAUDE_3_EXPECTED) +def test_claude_3_1hr_cache_write_pricing(model_data, model_key, expected_1hr): + """Haiku 3 and Opus 3 both carried Sonnet's 6e-06 1hr rate, overbilling Haiku 3 + 1-hour cache writes 12x and underbilling Opus 3 5x.""" + info = model_data[model_key] + + assert info["cache_creation_input_token_cost_above_1hr"] == expected_1hr + + +@pytest.mark.parametrize("model_key, expected_1hr", CLAUDE_3_EXPECTED) +def test_backup_matches_main_for_claude_3_1hr_cache_write(model_key, expected_1hr): + json_path = os.path.join( + os.path.dirname(__file__), + "../../litellm/model_prices_and_context_window_backup.json", + ) + with open(json_path) as f: + backup = json.load(f) + + assert ( + backup[model_key]["cache_creation_input_token_cost_above_1hr"] == expected_1hr + ) + + +def test_first_party_anthropic_1hr_cache_writes_are_2x_base_input(model_data): + """Anthropic charges 1-hour cache writes at 2x base input for every first-party + model, so any entry that drifts off that multiple is a copy-paste error.""" + offenders = tuple( + ( + model_key, + info["input_cost_per_token"], + info["cache_creation_input_token_cost_above_1hr"], + ) + for model_key, info in model_data.items() + if isinstance(info, dict) + and info.get("litellm_provider") == "anthropic" + and info.get("input_cost_per_token") + and info.get("cache_creation_input_token_cost_above_1hr") + and abs( + info["cache_creation_input_token_cost_above_1hr"] + - 2 * info["input_cost_per_token"] + ) + > 1e-12 + ) + + assert offenders == (), f"1hr cache write is not 2x base input for: {offenders}" diff --git a/tests/test_litellm/test_check_licenses.py b/tests/test_litellm/test_check_licenses.py index 4d72f185a25..1218e44fade 100644 --- a/tests/test_litellm/test_check_licenses.py +++ b/tests/test_litellm/test_check_licenses.py @@ -12,6 +12,8 @@ import os import sys from pathlib import Path +import requests + _CODE_COVERAGE_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)), "..", "code_coverage_tests" ) @@ -122,6 +124,75 @@ def test_get_license_returns_none_on_request_failure(monkeypatch): assert checker.get_package_license_from_pypi("pkg", "1.0.0") is None +def test_get_license_retries_connection_error_then_resolves_license(): + responses = iter( + ( + requests.ConnectionError("connection reset"), + requests.ConnectionError("connection reset"), + _FakeResponse({"info": {"license_expression": "MIT"}}), + ) + ) + calls = [] + sleeps = [] + + def _fake_get(url, timeout=None): + calls.append((url, timeout)) + response = next(responses) + if isinstance(response, Exception): + raise response + return response + + checker = check_licenses.LicenseChecker( + config_file=_LICCHECK_INI, + http_get=_fake_get, + sleep=sleeps.append, + ) + + assert checker.get_package_license_from_pypi("pkg", "1.0.0") == "MIT" + assert len(calls) == 3 + assert len(sleeps) == 2 + + +def test_get_license_does_not_retry_not_found_http_error(): + response = requests.Response() + response.status_code = 404 + calls = [] + sleeps = [] + + def _fake_get(url, timeout=None): + calls.append((url, timeout)) + raise requests.HTTPError("not found", response=response) + + checker = check_licenses.LicenseChecker( + config_file=_LICCHECK_INI, + http_get=_fake_get, + sleep=sleeps.append, + ) + + assert checker.get_package_license_from_pypi("pkg", "1.0.0") is None + assert len(calls) == 1 + assert sleeps == [] + + +def test_get_license_returns_none_after_connection_retry_limit(): + calls = [] + sleeps = [] + + def _fake_get(url, timeout=None): + calls.append((url, timeout)) + raise requests.ConnectionError("connection reset") + + checker = check_licenses.LicenseChecker( + config_file=_LICCHECK_INI, + http_get=_fake_get, + sleep=sleeps.append, + ) + + assert checker.get_package_license_from_pypi("pkg", "1.0.0") is None + assert len(calls) == 3 + assert len(sleeps) == 2 + + # -------------------------------------------------------------------------- # is_license_acceptable: SPDX identifiers and compound expressions # -------------------------------------------------------------------------- diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py index 8fce9ba080c..0c99d128e14 100644 --- a/tests/test_litellm/test_cost_calculator.py +++ b/tests/test_litellm/test_cost_calculator.py @@ -343,6 +343,31 @@ def test_transcription_cost_uses_token_pricing(_local_model_cost_map): assert pytest.approx(cost, rel=1e-6) == expected_cost +def test_transcription_token_pricing_is_provider_aware(_local_model_cost_map): + """Regression: the token-priced transcription path hardcoded provider openai, + so gemini transcription models raised "This model isn't mapped yet".""" + from litellm import completion_cost + + usage = Usage( + prompt_tokens=200, + completion_tokens=10, + total_tokens=210, + prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1, audio_tokens=199), + ) + response = TranscriptionResponse(text="demo text") + response.usage = usage + + cost = completion_cost( + completion_response=response, + model="gemini/gemini-3.5-transcribe", + custom_llm_provider="gemini", + call_type="atranscription", + ) + + expected_cost = (199 * 2e-06) + (1 * 2e-06) + (10 * 1.2e-05) + assert pytest.approx(cost, rel=1e-6) == expected_cost + + def test_transcription_cost_falls_back_to_duration(_local_model_cost_map): from litellm import completion_cost diff --git a/tests/test_litellm/test_fireworks_serverless_model_costs.py b/tests/test_litellm/test_fireworks_serverless_model_costs.py new file mode 100644 index 00000000000..0458af0da0e --- /dev/null +++ b/tests/test_litellm/test_fireworks_serverless_model_costs.py @@ -0,0 +1,86 @@ +""" +Validate the Fireworks AI Serverless entry added for #37274 exists in +`model_prices_and_context_window.json` and that the bare Fireworks model ID +resolves through `get_model_info`. + +Pricing as published at https://docs.fireworks.ai/serverless/pricing +(USD per 1M tokens, uncached input / cached input / output): + + accounts/fireworks/models/deepseek-v4-pro-0813 -> $1.32 / $0.044 / $3.96 +""" + +import json +import os + +import pytest + +import litellm +from litellm.utils import get_model_info + + +@pytest.fixture(scope="module", autouse=True) +def _local_model_cost_map(): + """ + Point litellm at the bundled cost map for the duration of this module + only. ``mp.undo()`` restores both the environment variable and + ``litellm.model_cost`` so nothing leaks into later tests. + """ + mp = pytest.MonkeyPatch() + mp.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + mp.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) + get_model_info.cache_clear() + yield + mp.undo() + get_model_info.cache_clear() + + +NEW_ENTRIES = { + "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813": { + "input_cost_per_token": 1.32e-06, + "cache_read_input_token_cost": 4.4e-08, + "output_cost_per_token": 3.96e-06, + "max_input_tokens": 1048576, + "max_output_tokens": 131072, + }, +} + + +@pytest.fixture(scope="module") +def model_data(): + json_path = os.path.join( + os.path.dirname(__file__), "../../model_prices_and_context_window.json" + ) + with open(json_path) as f: + return json.load(f) + + +def test_fireworks_serverless_entries_exist(model_data): + """The new prefixed entry carries the pricing and metadata from #37274.""" + for key, expected in NEW_ENTRIES.items(): + assert key in model_data, f"{key} is missing from model_prices_and_context_window.json" + entry = model_data[key] + for field, value in expected.items(): + assert entry[field] == pytest.approx(value), f"{key}.{field}" + assert entry["litellm_provider"] == "fireworks_ai" + assert entry["mode"] == "chat" + assert entry["supports_function_calling"] is True + assert entry["supports_vision"] is False + + +def test_bare_fireworks_ids_resolve_through_prefixed_entries(): + """Bare IDs from #37274 resolve via the provider-prefix lookup path.""" + for bare_id, prefixed_key in [ + ( + "accounts/fireworks/models/deepseek-v4-pro-0813", + "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813", + ), + ]: + info = get_model_info(model=bare_id, custom_llm_provider="fireworks_ai") + expected = NEW_ENTRIES[prefixed_key] + assert info.get("key") == prefixed_key + assert info["litellm_provider"] == "fireworks_ai" + assert info["input_cost_per_token"] == pytest.approx(expected["input_cost_per_token"]) + assert info["cache_read_input_token_cost"] == pytest.approx(expected["cache_read_input_token_cost"]) + assert info["output_cost_per_token"] == pytest.approx(expected["output_cost_per_token"]) + assert info["max_input_tokens"] == expected["max_input_tokens"] + assert info["max_output_tokens"] == expected["max_output_tokens"] diff --git a/tests/test_litellm/test_register_model_custom_pricing.py b/tests/test_litellm/test_register_model_custom_pricing.py index e3f6a1a0f40..39f498b4e58 100644 --- a/tests/test_litellm/test_register_model_custom_pricing.py +++ b/tests/test_litellm/test_register_model_custom_pricing.py @@ -435,6 +435,151 @@ def test_register_model_warns_when_no_builtin_match_for_cache_pricing(caplog): litellm.model_cost.pop(registered_key, None) +def test_register_model_no_warning_without_custom_pricing(caplog): + """LIT-6318: an entry with no custom pricing (e.g. router deployment + metadata) never drives cost calculation, so registering it under an + unmatched key must not emit the missing-cache-pricing warning. + """ + import logging + + from litellm._logging import verbose_logger + + registered_key = "azure/lit6318-deployment-without-pricing" + litellm.model_cost.pop(registered_key, None) + + try: + with caplog.at_level(logging.WARNING, logger=verbose_logger.name): + litellm.register_model( + { + registered_key: { + "litellm_provider": "azure", + "base_model": "azure/text-embedding-3-large", + } + } + ) + + assert not any("register_model" in record.message for record in caplog.records), ( + "entry without custom pricing must register silently" + ) + finally: + litellm.model_cost.pop(registered_key, None) + + +def test_register_model_no_warning_for_tiered_pricing_without_cache_costs(caplog): + """LIT-6318: tiered pricing bills cache reads at the tier's input rate when + cache costs are omitted, so a tiered entry must not trigger the + cache-defaults-to-0 warning. + """ + import logging + + from litellm._logging import verbose_logger + + registered_key = "bedrock/lit6318-tiered-priced-model" + litellm.model_cost.pop(registered_key, None) + + try: + with caplog.at_level(logging.WARNING, logger=verbose_logger.name): + litellm.register_model( + { + registered_key: { + "litellm_provider": "bedrock", + "tiered_pricing": [ + { + "range": [0, 200000], + "input_cost_per_token": 1e-06, + "output_cost_per_token": 5e-06, + } + ], + } + } + ) + + assert not any("register_model" in record.message for record in caplog.records), ( + "tiered pricing entry must register silently" + ) + finally: + litellm.model_cost.pop(registered_key, None) + + +def test_router_deployment_without_custom_pricing_registers_silently(caplog): + """LIT-6318: the router registers every deployment under its hashed id and + its backend key. Deployments without custom pricing are costed at request + time from the underlying model name, so startup must not warn about them. + """ + import logging + + from litellm import Router + from litellm._logging import verbose_logger + + deployment_model = "azure/lit6318-my-deployment-name" + deployment_id = "lit6318-no-pricing-deployment" + snapshot = _snapshot_model_cost_entries([deployment_model, deployment_id]) + + try: + with caplog.at_level(logging.WARNING, logger=verbose_logger.name): + Router( + model_list=[ + { + "model_name": "indexing", + "litellm_params": { + "model": deployment_model, + "api_base": "https://example.openai.azure.com", + "api_key": "fake-key", + }, + "model_info": { + "id": deployment_id, + "base_model": "azure/text-embedding-3-large", + }, + } + ] + ) + + register_warnings = [record.message for record in caplog.records if "register_model" in record.message] + assert not register_warnings, register_warnings + finally: + _restore_model_cost_entries(snapshot) + + +def test_router_custom_priced_deployment_warning_names_model_not_hash(caplog): + """LIT-6318: when a custom-priced deployment genuinely lacks cache pricing + and no built-in entry matches, the warning must name the deployment's + model rather than its opaque hashed id. + """ + import logging + + from litellm import Router + from litellm._logging import verbose_logger + + deployment_model = "bedrock/lit6318-totally-made-up-model" + deployment_id = "lit6318-custom-priced-deployment-hash" + snapshot = _snapshot_model_cost_entries([deployment_model, deployment_id]) + + try: + with caplog.at_level(logging.WARNING, logger=verbose_logger.name): + Router( + model_list=[ + { + "model_name": "made-up", + "litellm_params": { + "model": deployment_model, + "aws_region_name": "us-east-1", + "input_cost_per_token": 1e-06, + "output_cost_per_token": 5e-06, + }, + "model_info": {"id": deployment_id}, + } + ] + ) + + register_warnings = [record.message for record in caplog.records if "register_model" in record.message] + assert register_warnings, "expected a warning for missing cache pricing" + for message in register_warnings: + assert deployment_id not in message, message + assert deployment_model in message, message + finally: + _restore_model_cost_entries(snapshot) + + def test_register_model_router_add_deployment_custom_pricing_applies(): """End-to-end regression for https://github.com/BerriAI/litellm/issues/28336. diff --git a/tests/test_litellm/test_together_ai_model_metadata.py b/tests/test_litellm/test_together_ai_model_metadata.py index fbeb0c35fca..bf35f459bb6 100644 --- a/tests/test_litellm/test_together_ai_model_metadata.py +++ b/tests/test_litellm/test_together_ai_model_metadata.py @@ -16,10 +16,8 @@ SERVERLESS_CHAT_MODELS: Final = ( "together_ai/moonshotai/Kimi-K3", "together_ai/zai-org/GLM-5.2", "together_ai/zai-org/GLM-5.3-Flash", - "together_ai/deepseek-ai/DeepSeek-V4-Pro", "together_ai/deepseek-ai/DeepSeek-V4-Pro-0813", "together_ai/deepseek-ai/DeepSeek-V4-Flash-0731", - "together_ai/moonshotai/Kimi-K2.7-Code", "together_ai/MiniMaxAI/MiniMax-M3", "together_ai/thinkingmachines/Inkling", "together_ai/thinkingmachines/Inkling-Small", @@ -28,20 +26,22 @@ SERVERLESS_CHAT_MODELS: Final = ( "together_ai/Qwen/Qwen3.7-Plus", "together_ai/Qwen/Qwen3.6-Plus", "together_ai/Qwen/Qwen3.5-9B", - "together_ai/nvidia/nemotron-3-ultra-550b-a55b", "together_ai/meta-models/Muse-Glimmer-30B", "together_ai/google/gemma-4-31B-it", - "together_ai/pearl-ai/gemma-4-31b-it", - "together_ai/google/gemma-3n-E4B-it", "together_ai/arize-ai/qwen-2-1.5b-instruct", "together_ai/Prism-ML/Ternary-Bonsai-27B", - "together_ai/meta-llama/Llama-Guard-4-12B", "together_ai/openai/gpt-oss-120b", "together_ai/openai/gpt-oss-20b", "together_ai/meta-llama/Llama-3.3-70B-Instruct-Turbo", ) DEPRECATED_MODELS: Final = { + "together_ai/nvidia/nemotron-3-ultra-550b-a55b": "2026-08-27", + "together_ai/pearl-ai/gemma-4-31b-it": "2026-08-27", + "together_ai/deepseek-ai/DeepSeek-V4-Pro": "2026-08-27", + "together_ai/moonshotai/Kimi-K2.7-Code": "2026-08-27", + "together_ai/google/gemma-3n-E4B-it": "2026-08-25", + "together_ai/meta-llama/Llama-Guard-4-12B": "2026-08-25", "together_ai/Qwen/Qwen3-235B-A22B-Instruct-2507-tput": "2026-07-10", "together_ai/Qwen/Qwen3.5-397B-A17B": "2026-06-29", "together_ai/Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "2026-06-04", diff --git a/tests/test_litellm/types/test_mcp.py b/tests/test_litellm/types/test_mcp.py new file mode 100644 index 00000000000..5450ec4aa48 --- /dev/null +++ b/tests/test_litellm/types/test_mcp.py @@ -0,0 +1,87 @@ +"""Tests for the shared MCP header primitives. + +``same_header`` / ``has_header`` / ``without_header`` are the one owner of "is this the credential's +header", used by both MCP stacks and the upstream-credential resolver. They live here rather than in +either stack because a second implementation is exactly how an injected header came to shadow a +resolved credential on one path and not the other. +""" + +import pytest + +from litellm.types.mcp import ( + credential_redirect_hook, + crosses_origin, + has_header, + same_header, + without_header, +) + + +@pytest.mark.parametrize( + "a,b,expected", + [ + ("Authorization", "authorization", True), + ("ESB-OAuth", "esb-oauth", True), + ("esb-oauth", "esb-oauth", True), + ("esb-oauth", "esb_oauth", False), + ("esb-oauth", "Authorization", False), + ], +) +def test_header_names_compare_case_insensitively(a: str, b: str, expected: bool) -> None: + # RFC 7230 3.2. Every consumer of a credential slot routes through this, so a case-sensitive + # comparison anywhere would let an injected header shadow a resolved credential. + assert same_header(a, b) is expected + + +def test_without_header_drops_every_casing_and_keeps_the_rest() -> None: + headers = {"ESB-OAuth": "injected", "esb-oauth": "also injected", "X-Trace": "keep"} + assert without_header(headers, "esb-oauth") == {"X-Trace": "keep"} + + +def test_without_header_collapses_to_none_when_nothing_remains() -> None: + assert without_header({"Authorization": "Bearer x"}, "AUTHORIZATION") is None + assert without_header(None, "esb-oauth") is None + assert without_header({}, "esb-oauth") is None + + +def test_has_header_matches_any_casing() -> None: + assert has_header({"ESB-OAuth": "v"}, "esb-oauth") is True + assert has_header({"X-Other": "v"}, "esb-oauth") is False + assert has_header(None, "esb-oauth") is False + + +@pytest.mark.parametrize( + "target,expected", + [ + ("https://upstream.example.com/other", False), # same origin + ("https://upstream.example.com:443/other", False), # explicit default port + ("https://attacker.example.com/collect", True), # different host + ("http://upstream.example.com/collect", True), # scheme downgrade, same host + ("https://upstream.example.com:8443/other", True), # different port, same host + ("https://sub.upstream.example.com/x", True), # different host + ], +) +def test_origin_is_scheme_host_and_port_not_host_alone(target: str, expected: bool) -> None: + assert crosses_origin("https://upstream.example.com/mcp", target) is expected + + +def test_an_https_upgrade_of_the_same_host_is_not_crossing() -> None: + # HTTP clients exempt this when deciding to keep Authorization, so a credential slot that did + # not would lose the credential on every such redirect. + assert crosses_origin("http://upstream.example.com/mcp", "https://upstream.example.com/x") is False + assert crosses_origin("http://upstream.example.com/mcp", "http://upstream.example.com/x") is False + + +@pytest.mark.asyncio +async def test_the_hook_drops_the_slot_only_once_the_origin_changes() -> None: + import httpx + + hook = credential_redirect_hook("https://upstream.example.com/mcp", "esb-oauth") + + same = httpx.Request("GET", "https://upstream.example.com/other", headers={"esb-oauth": "Bearer x"}) + await hook(same) + assert same.headers["esb-oauth"] == "Bearer x" + + foreign = httpx.Request("GET", "https://attacker.example.com/x", headers={"esb-oauth": "Bearer x"}) + await hook(foreign) + assert "esb-oauth" not in foreign.headers diff --git a/ui/Dockerfile b/ui/Dockerfile index 0d184b74493..24140093270 100644 --- a/ui/Dockerfile +++ b/ui/Dockerfile @@ -3,7 +3,7 @@ # UI container — Next.js static export served by nginx. ARG UI_BUILD_IMAGE=node:24.19-alpine3.24@sha256:d32cdf619f63fe0471182d08996dd516c6275bb5fd31ae06e55a570bd9e1ad43 -ARG NGINX_VERSION=1.27-alpine +ARG NGINX_VERSION=1.31-alpine # ---------- builder ---------- FROM ${UI_BUILD_IMAGE} AS builder diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx index dc1223264bb..1de4e697f64 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx @@ -1106,7 +1106,7 @@ export function TeamGuardrailsTab({ accessToken }: TeamGuardrailsTabProps) { > - + {GUARDRAIL_MODES.map((mode) => ( {mode.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CategoryTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CategoryTable.tsx index fa40ce6ab54..f012923d32f 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CategoryTable.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CategoryTable.tsx @@ -64,7 +64,7 @@ const CategoryTable: React.FC = ({ - + {SEVERITY_ITEMS.map((item) => ( {item.label} @@ -93,7 +93,7 @@ const CategoryTable: React.FC = ({ - + {ACTION_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CompetitorIntentConfiguration.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CompetitorIntentConfiguration.tsx index 8445495246d..0632ec87f34 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CompetitorIntentConfiguration.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CompetitorIntentConfiguration.tsx @@ -194,7 +194,7 @@ const CompetitorIntentConfiguration: React.FC - + {INTENT_TYPES.map((type) => ( {type.label} @@ -268,7 +268,7 @@ const CompetitorIntentConfiguration: React.FC - + {COMPETITOR_COMPARISON_POLICIES.map((policy) => ( {policy.label} @@ -292,7 +292,7 @@ const CompetitorIntentConfiguration: React.FC - + {POSSIBLE_COMPETITOR_COMPARISON_POLICIES.map((policy) => ( {policy.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/ContentCategoryConfiguration.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/ContentCategoryConfiguration.tsx index 1924133a6cc..f2226a3bc6e 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/ContentCategoryConfiguration.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/ContentCategoryConfiguration.tsx @@ -199,7 +199,7 @@ const ContentCategoryConfiguration: React.FC - + {ACTION_ITEMS.map((item) => ( {item.value} @@ -224,7 +224,7 @@ const ContentCategoryConfiguration: React.FC - + {SEVERITY_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CustomPatternModal.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CustomPatternModal.tsx index 2ead171d5e4..68eb7e138ab 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CustomPatternModal.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/CustomPatternModal.tsx @@ -70,7 +70,7 @@ const CustomPatternModal: React.FC = ({ - + {ACTION_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordModal.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordModal.tsx index 504f35973fd..bf1b49dabd0 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordModal.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordModal.tsx @@ -60,7 +60,7 @@ const KeywordModal: React.FC = ({ - + {ACTION_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordTable.tsx index 5c7e3ef3ab8..5b69b04955f 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordTable.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/KeywordTable.tsx @@ -38,7 +38,7 @@ const KeywordTable: React.FC = ({ keywords, onActionChange, o - + {ACTION_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternModal.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternModal.tsx index 4caa47217fe..aeeadedfbf1 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternModal.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternModal.tsx @@ -114,7 +114,7 @@ const PatternModal: React.FC = ({ - + {ACTION_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternTable.tsx index 6dd266f07a0..f4e87119d7b 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternTable.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/PatternTable.tsx @@ -58,7 +58,7 @@ const PatternTable: React.FC = ({ patterns, onActionChange, o - + {ACTION_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/custom_code/CustomCodeModal.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/custom_code/CustomCodeModal.tsx index 77bac8bb0aa..a69824f32d3 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/custom_code/CustomCodeModal.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/custom_code/CustomCodeModal.tsx @@ -556,7 +556,7 @@ const CustomCodeModal: React.FC = ({ visible, onClose, onS - + STANDARD {TEMPLATE_ITEMS.map((template) => ( diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/pii_components.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/pii_components.tsx index 5f8e833af8d..0de7eb1c9ce 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/pii_components.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/pii_components.tsx @@ -179,7 +179,7 @@ export const PiiEntityList: React.FC = ({ - + {actions.map((action) => ( diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/tool_permission/ToolPermissionRulesEditor.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/tool_permission/ToolPermissionRulesEditor.tsx index 8fe2bf5bf21..c154d102314 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/tool_permission/ToolPermissionRulesEditor.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/tool_permission/ToolPermissionRulesEditor.tsx @@ -280,7 +280,7 @@ const ToolPermissionRulesEditor: React.FC = ({ v - + {DECISION_ITEMS.map((item) => ( {item.label} @@ -313,7 +313,7 @@ const ToolPermissionRulesEditor: React.FC = ({ v - + {DECISION_ITEMS.map((item) => ( {item.label} @@ -350,7 +350,7 @@ const ToolPermissionRulesEditor: React.FC = ({ v - + {ON_DISALLOWED_ITEMS.map((item) => ( {item.label} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/IdJagFormFields.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/IdJagFormFields.tsx index df1d8d3436a..70d1bc40c18 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/IdJagFormFields.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/IdJagFormFields.tsx @@ -3,6 +3,7 @@ import React from "react"; import { SimpleTooltip } from "@/components/ui/tooltip"; import { MountedFormField } from "@/components/common_components/MountedFormField"; +import UpstreamTokenHeaderField from "./UpstreamTokenHeaderField"; import { requiredRule } from "@/components/common_components/formRules"; import { MultiSelect } from "@/components/shared/MultiSelect"; import { PasswordInput } from "@/components/shared/PasswordInput"; @@ -205,6 +206,7 @@ const IdJagFormFields: React.FC = ({ isEditing = false }) > {(control) => } + ); }; diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.test.tsx index 21bb2801e8c..9316cfa077c 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.test.tsx @@ -286,4 +286,42 @@ describe("OAuthFormFields", () => { }); }); }); + + describe("token header field", () => { + it("renders on the M2M flow", () => { + render( + + + , + ); + expect(screen.getByPlaceholderText("Authorization")).toBeInTheDocument(); + }); + + it("renders on the interactive flow", () => { + render( + + + , + ); + expect(screen.getByPlaceholderText("Authorization")).toBeInTheDocument(); + }); + + it("submits its value under credentials.upstream_token_header", async () => { + const onFinish = vi.fn(); + render( + + + , + ); + fireEvent.change(screen.getByPlaceholderText("Authorization"), { target: { value: "esb-oauth" } }); + fireEvent.click(screen.getByText("Submit")); + await waitFor(() => { + expect(onFinish).toHaveBeenCalledWith( + expect.objectContaining({ + credentials: expect.objectContaining({ upstream_token_header: "esb-oauth" }), + }), + ); + }); + }); + }); }); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsx index 76d667039d4..41817f8c916 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsx @@ -11,6 +11,7 @@ import { OAUTH_FLOW } from "@/components/mcp_tools/types"; import { MountedFormField } from "@/components/common_components/MountedFormField"; import { requiredRule } from "@/components/common_components/formRules"; import TokenEndpointAuthMethodField from "./TokenEndpointAuthMethodField"; +import UpstreamTokenHeaderField from "./UpstreamTokenHeaderField"; import { numberControl, parsesAsJson, @@ -175,6 +176,7 @@ const OAuthFormFields: React.FC = ({ {(control) => } + ) : ( <> @@ -237,6 +239,7 @@ const OAuthFormFields: React.FC = ({ {(control) => } + = ({ isEdi /> )} + ); }; diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/UpstreamTokenHeaderField.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/UpstreamTokenHeaderField.tsx new file mode 100644 index 00000000000..154d55c8cb4 --- /dev/null +++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/UpstreamTokenHeaderField.tsx @@ -0,0 +1,31 @@ +import { Info } from "lucide-react"; +import React from "react"; +import { SimpleTooltip } from "@/components/ui/tooltip"; +import { Input } from "@/components/ui/input"; + +import { MountedFormField } from "@/components/common_components/MountedFormField"; +import { textControl } from "./mcpFieldRules"; + +const UpstreamTokenHeaderField: React.FC = () => ( + + Token Header (optional) + + + + + } + name={["credentials", "upstream_token_header"]} + > + {(control) => ( + + )} + +); + +export default UpstreamTokenHeaderField; diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/editServerPayload.differential.cases.ts b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/editServerPayload.differential.cases.ts index c350ac085b6..ef8f728a609 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/editServerPayload.differential.cases.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/editServerPayload.differential.cases.ts @@ -255,13 +255,28 @@ export const CASES: readonly DifferentialCase[] = [ }, // --- credentials filtering --- - // ADMIN_CONFIG_CREDENTIAL_KEYS is exactly ["upstream_resource"], so only that key - // takes the blank-to-explicit-null branch. A blank client_id is dropped instead. + // Only a key in ADMIN_CONFIG_CREDENTIAL_KEYS takes the blank-to-explicit-null branch, which is + // what makes it clearable: the backend merge preserves an omitted key forever. A blank client_id + // is dropped instead. { label: "blank upstream_resource becomes an explicit null", values: { ...ROOT, auth_type: "oauth2", credentials: { upstream_resource: "", client_secret: "keep" } }, ui: {}, }, + { + label: "blank upstream_token_header becomes an explicit null", + values: { ...ROOT, auth_type: "oauth2", credentials: { upstream_token_header: "", client_secret: "keep" } }, + ui: {}, + }, + { + label: "a set upstream_token_header rides the credentials blob", + values: { + ...ROOT, + auth_type: "oauth2", + credentials: { upstream_token_header: "esb-oauth", client_secret: "keep" }, + }, + ui: {}, + }, { label: "blank non-admin credential is dropped, not nulled", values: { ...ROOT, auth_type: "oauth2", credentials: { client_id: "", client_secret: "keep", scopes: [] } }, diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.test.ts index dd9c8db6d30..13aec81d9e8 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.test.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.test.ts @@ -262,7 +262,14 @@ describe("edit root: exact mounted set per auth configuration", () => { ...PERMS, "delegate_auth_to_upstream", ], - credentials: ["client_id", "client_secret", "token_endpoint_auth_method", "scopes", "upstream_resource"], + credentials: [ + "client_id", + "client_secret", + "token_endpoint_auth_method", + "scopes", + "upstream_resource", + "upstream_token_header", + ], }, ); }); @@ -286,7 +293,14 @@ describe("edit root: exact mounted set per auth configuration", () => { ...PERMS, "delegate_auth_to_upstream", ], - credentials: ["client_id", "client_secret", "scopes", "upstream_resource", "token_endpoint_auth_method"], + credentials: [ + "client_id", + "client_secret", + "scopes", + "upstream_resource", + "token_endpoint_auth_method", + "upstream_token_header", + ], }, ); }); @@ -306,7 +320,7 @@ describe("edit root: exact mounted set per auth configuration", () => { "env_vars", ...PERMS, ], - credentials: ["client_id", "client_secret", "scopes"], + credentials: ["client_id", "client_secret", "scopes", "upstream_token_header"], }, ); }); @@ -324,7 +338,7 @@ describe("edit root: exact mounted set per auth configuration", () => { "env_vars", ...PERMS, ], - credentials: ["client_id", "client_secret", "scopes"], + credentials: ["client_id", "client_secret", "scopes", "upstream_token_header"], }, ); }); @@ -344,6 +358,7 @@ describe("edit root: exact mounted set per auth configuration", () => { ...PERMS, ], credentials: [ + "upstream_token_header", "id_jag_resource_token_endpoint", "client_id", "client_secret", @@ -434,7 +449,14 @@ describe("create root: exact mounted set per configuration", () => { ...PERMS, "delegate_auth_to_upstream", ], - credentials: ["client_id", "client_secret", "scopes", "upstream_resource", "token_endpoint_auth_method"], + credentials: [ + "client_id", + "client_secret", + "scopes", + "upstream_resource", + "token_endpoint_auth_method", + "upstream_token_header", + ], }, ); }); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.ts b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.ts index 22f0146afc9..af9cbb58b2b 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mountedServerFields.ts @@ -24,6 +24,7 @@ const OAUTH_M2M_CREDENTIALS = [ "token_endpoint_auth_method", "scopes", "upstream_resource", + "upstream_token_header", ] as const; const OAUTH_INTERACTIVE_CREDENTIALS = [ @@ -32,6 +33,7 @@ const OAUTH_INTERACTIVE_CREDENTIALS = [ "scopes", "upstream_resource", "token_endpoint_auth_method", + "upstream_token_header", ] as const; const OAUTH_INTERACTIVE_ROOT = [ @@ -44,6 +46,7 @@ const OAUTH_INTERACTIVE_ROOT = [ ] as const; const ID_JAG_CREDENTIALS = [ + "upstream_token_header", "id_jag_resource_token_endpoint", "client_id", "client_secret", @@ -100,7 +103,7 @@ const authSubtreeCredentials = ({ authType, oauthFlowType }: AuthSubtreeGates): ]; } if (authType === AUTH_TYPE.OAUTH2_TOKEN_EXCHANGE) { - return [...authValue, "client_id", "client_secret", "scopes"]; + return [...authValue, "client_id", "client_secret", "scopes", "upstream_token_header"]; } if (authType === AUTH_TYPE.OAUTH2_ID_JAG) { return [...authValue, ...ID_JAG_CREDENTIALS]; diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersPanel.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersPanel.test.tsx index 9ec551bc227..8c683f230e0 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersPanel.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersPanel.test.tsx @@ -107,6 +107,33 @@ const mockDeploymentsPage = () => { modelInfoCall.mockResolvedValue(pageOf(DEPLOYMENTS)); }; +// Oldest-first, as the proxy returns them, and two more than the ten-row first page holds. +const BULK_ROUTER_NAMES = [ + "router-01-oldest", + ...Array.from({ length: 10 }, (_, i) => `router-${i + 2}`), + "router-12-newest", +]; + +const A_FULL_PAGE_AND_TWO_MORE = Array.from({ length: 12 }, (_, index) => ({ + model_name: BULK_ROUTER_NAMES[index], + litellm_params: { + model: "auto_router/complexity_router", + complexity_router_config: { tiers: {}, classifier_type: "heuristic" }, + }, + model_info: { + id: `bulk-${index + 1}`, + db_model: true, + created_at: `2026-08-${String(index + 1).padStart(2, "0")}T00:00:00.000000+00:00`, + }, +})); + +/** Row order as rendered, header row dropped. */ +const routerNamesInOrder = () => + screen + .getAllByRole("row") + .slice(1) + .map((row) => row.querySelector("span.text-sm.font-medium")?.textContent ?? ""); + const renderPanel = (canModify = true) => renderWithProviders( { await screen.findByText("config-router"); expect(screen.queryByTestId("auto-router-actions-auto-4")).not.toBeInTheDocument(); }); + + // /v2/model/info returns an unordered model_list, and created_at is absent on config routers + // and on non-enterprise proxies, so both halves of the order have to be pinned here. + it("orders newest first, then the undated routers by name", async () => { + renderPanel(); + + await screen.findByText("tri-tier-router"); + + expect(routerNamesInOrder()).toEqual([ + "tri-tier-router", // 2026-07-28 + "support-router", // 2026-07-27 + "adaptive-router", // undated, sorts after every dated row, then by name + "config-router", + ]); + }); + + // The reported bug: the newest router was rendered last, so it landed on page 2 and read + // as never created. + it("puts a just-created router on the first page of a list longer than one page", async () => { + modelInfoCall.mockResolvedValue(pageOf(A_FULL_PAGE_AND_TWO_MORE)); + + renderPanel(); + + expect(await screen.findByRole("button", { name: "router-12-newest" })).toBeInTheDocument(); + // Page one holds the ten newest, so the two oldest are the ones pushed off it. + expect(screen.queryByRole("button", { name: "router-01-oldest" })).not.toBeInTheDocument(); + expect(routerNamesInOrder()[0]).toBe("router-12-newest"); + }); }); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTable.tsx index 943388f8535..2102f5e55d9 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTable.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTable.tsx @@ -1,7 +1,7 @@ "use client"; import { SortingState } from "@tanstack/react-table"; -import { useMemo, useState } from "react"; +import { useMemo } from "react"; import { DataTable } from "@/components/shared/DataTable"; import { AutoRouterIcon } from "@/components/shared/table_cells"; @@ -19,6 +19,11 @@ interface AutoRoutersTableProps { const PAGE_SIZE_OPTIONS = [10, 25, 50]; +const DEFAULT_SORTING: SortingState = [ + { id: "createdAt", desc: true }, + { id: "name", desc: false }, +]; + function EmptyState({ canModify }: { canModify: boolean }) { return (
@@ -42,8 +47,6 @@ export function AutoRoutersTable({ onRouterClick, onDeleteClick, }: AutoRoutersTableProps) { - const [sorting, setSorting] = useState([]); - const columns = useMemo( () => getAutoRoutersTableColumns({ canModify, onRouterClick, onDeleteClick }), [canModify, onRouterClick, onDeleteClick], @@ -55,8 +58,7 @@ export function AutoRoutersTable({ columns={columns} getRowId={(router) => router.id} sortingMode="client" - sorting={sorting} - onSortingChange={setSorting} + defaultSorting={DEFAULT_SORTING} paginationMode="client" pageSizeOptions={PAGE_SIZE_OPTIONS} isLoading={isLoading} diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTableColumns.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTableColumns.tsx index 995ba634c34..4a99062988f 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTableColumns.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/AutoRoutersTableColumns.tsx @@ -155,6 +155,7 @@ export const getAutoRoutersTableColumns = ({ size: 150, enableSorting: true, sortingFn: "datetime", + sortUndefined: "last", cell: ({ row }) => , }, ...(canModify diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/autoRouterRows.ts b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/autoRouterRows.ts index a8111ddb02d..bbdf4697315 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/autoRouterRows.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/AutoRouters/autoRouterRows.ts @@ -30,7 +30,8 @@ export interface AutoRouterRow { editBlockedReason: EditBlockedReason | null; targets: string[]; defaultModel: string | null; - createdAt: string | null; + /** `undefined`, not `null`: the table's `sortUndefined` pin only matches `undefined` */ + createdAt: string | undefined; deployment: AutoRouterDeployment; } @@ -113,7 +114,7 @@ export const toAutoRouterRow = ( canEdit: canEdit && mayActOnRow, canDelete: canDelete && mayActOnRow, editBlockedReason, - createdAt: info.created_at ?? null, + createdAt: info.created_at ?? undefined, defaultModel: (params[strategy.defaultModelKey] as string | null | undefined) ?? null, deployment, ...PRESENTERS[strategy.kind](asRecord(params[strategy.configKey])), diff --git a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsx b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsx index 9d447090381..8f24e47340c 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/CreateVectorStore.tsx @@ -342,7 +342,7 @@ const CreateVectorStore: React.FC = ({ accessToken, onSu - + {providerItems.map((item) => ( diff --git a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/VectorStoreForm.tsx b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/VectorStoreForm.tsx index be0954a7d24..9d78b727768 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/VectorStoreForm.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/VectorStoreForm.tsx @@ -298,7 +298,7 @@ const VectorStoreForm: React.FC = ({ }} - + {Object.entries(VectorStoreProviders).map(([providerEnum, providerDisplayName]) => ( = ({ }} - + {Object.entries(Providers) .filter(([providerEnum]) => providerEnum === "Bedrock") .map(([providerEnum, providerDisplayName]) => ( diff --git a/ui/litellm-dashboard/src/autorouter_presets.json b/ui/litellm-dashboard/src/autorouter_presets.json index aff6f09da04..41107e88b8c 100644 --- a/ui/litellm-dashboard/src/autorouter_presets.json +++ b/ui/litellm-dashboard/src/autorouter_presets.json @@ -1,13 +1,16 @@ { "anthropic_family": { "label": "Anthropic Family", - "description": "Routes across the Claude model family: Haiku for simple queries, Sonnet for medium, Opus for complex and reasoning-heavy requests.", + "description": "Routes across the Claude model family: Haiku for simple queries, Sonnet for medium, Opus for complex, Opus at high thinking for reasoning.", "complexity_router_config": { "tiers": { "SIMPLE": ["claude-haiku-4-5"], "MEDIUM": ["claude-sonnet-5"], "COMPLEX": ["claude-opus-5"], - "REASONING": ["claude-fable-5"] + "REASONING": ["claude-opus-5"] + }, + "tier_model_configs": { + "REASONING": [{ "model_name": "claude-opus-5", "litellm_params": { "reasoning_effort": "high" } }] }, "classifier_type": "heuristic", "escalation_keywords": ["LITELLM ESCALATE"], diff --git a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx index c5924bdc959..6afdd1dbcfb 100644 --- a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx +++ b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx @@ -592,6 +592,28 @@ describe("AddAutoRouterTab", () => { }); }); + // Every step between the bundled JSON and the payload drops these params silently. + it("carries a preset's per-tier reasoning effort through to the create payload", async () => { + const user = userEvent.setup(); + mockFetchAvailableModels.mockResolvedValue(ALL_FAMILY_MODELS); + + renderWithProviders(); + await waitForPresetEnabled("Anthropic Family"); + await selectTemplate("Anthropic Family"); + + await user.type(screen.getByPlaceholderText(/smart_router/i), "anthropic-router"); + await user.click(screen.getByRole("button", { name: /add auto router/i })); + + await waitFor(() => expect(handleAddAutoRouterSubmit).toHaveBeenCalled()); + expect(vi.mocked(handleAddAutoRouterSubmit).mock.calls.at(-1)?.[0]).toMatchObject({ + complexity_router_config: { + tier_model_configs: { + REASONING: [{ model_name: "claude-opus-5", litellm_params: { reasoning_effort: "high" } }], + }, + }, + }); + }); + // Bugbot-found bug: submitBlockedReason disables the button for this, but Form's onFinish // (wired to the same handler as the button) fires whenever the form itself is submitted, // independent of the button's own disabled state. Without submitRecommendedRouter re-checking diff --git a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx b/ui/litellm-dashboard/src/components/mcp_tools/types.tsx index 67e51ab23aa..bc14e7a87ec 100644 --- a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx +++ b/ui/litellm-dashboard/src/components/mcp_tools/types.tsx @@ -151,7 +151,7 @@ const DECLARED_APP_CREDENTIAL_KEYS = ["client_id", "client_secret"] as const; // would destroy admin input), but it must stay OUT of the declared-app set: whether an app exists is // a distinct question that gates the "app may not match upstream" warning, and a server using dynamic // client registration can set a resource indicator while having no app at all. -export const ADMIN_CONFIG_CREDENTIAL_KEYS = ["upstream_resource"] as const; +export const ADMIN_CONFIG_CREDENTIAL_KEYS = ["upstream_resource", "upstream_token_header"] as const; // Minted token material the oauth2 authorize path writes beside the app keys; stripped from restored // snapshots and from any credentials that transit to the temp-session preview so a stale token never diff --git a/ui/litellm-dashboard/src/components/networking.test.ts b/ui/litellm-dashboard/src/components/networking.test.ts index f12a52a0bcf..cd22935a66f 100644 --- a/ui/litellm-dashboard/src/components/networking.test.ts +++ b/ui/litellm-dashboard/src/components/networking.test.ts @@ -459,6 +459,64 @@ describe("teamInfoCall", () => { }); }); +describe("uiSpendLogsCall exclude_internal_health_checks serialization", () => { + const originalFetch = global.fetch; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + global.fetch = originalFetch; + }); + + const mockOkFetch = () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: vi.fn().mockResolvedValue({ data: [], total: 0, page: 1, page_size: 50, total_pages: 0 }), + } as any); + global.fetch = mockFetch as any; + return mockFetch; + }; + + const callWith = (params: Parameters[0]["params"]) => + Networking.uiSpendLogsCall({ + accessToken: "token", + start_date: "2026-01-01 00:00:00", + end_date: "2026-01-02 00:00:00", + params, + }); + + const lastUrl = (mockFetch: ReturnType) => { + const [url] = mockFetch.mock.calls.at(-1) ?? []; + return new URL(url as string, "http://example.com"); + }; + + it("appends exclude_internal_health_checks=true when the toggle is on", async () => { + const mockFetch = mockOkFetch(); + + await callWith({ exclude_internal_health_checks: true }); + + expect(lastUrl(mockFetch).searchParams.get("exclude_internal_health_checks")).toBe("true"); + }); + + it("omits exclude_internal_health_checks when the toggle is off", async () => { + const mockFetch = mockOkFetch(); + + await callWith({ exclude_internal_health_checks: false }); + + expect(lastUrl(mockFetch).searchParams.has("exclude_internal_health_checks")).toBe(false); + }); + + it("omits exclude_internal_health_checks when the param is absent", async () => { + const mockFetch = mockOkFetch(); + + await callWith({}); + + expect(lastUrl(mockFetch).searchParams.has("exclude_internal_health_checks")).toBe(false); + }); +}); + describe("sessionSpendLogsCall", () => { const originalFetch = global.fetch; diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx index 5b6d70b4771..032429ba8ed 100644 --- a/ui/litellm-dashboard/src/components/networking.tsx +++ b/ui/litellm-dashboard/src/components/networking.tsx @@ -2002,6 +2002,7 @@ interface UiSpendLogsParams { user_id?: string; end_user?: string; status_filter?: string; + cache_hit_filter?: string; /** Filter by model name (e.g. "gpt-4") */ model?: string; /** Filter by model ID (litellm model deployment id) */ @@ -2013,6 +2014,7 @@ interface UiSpendLogsParams { sort_order?: "asc" | "desc"; min_spend?: number; max_spend?: number; + exclude_internal_health_checks?: boolean; } interface UiSpendLogsCallOptions { @@ -2047,6 +2049,8 @@ export const uiSpendLogsCall = async ({ if (value == null) continue; if (key === "min_spend" || key === "max_spend") { queryParams.append(key, value.toString()); + } else if (typeof value === "boolean") { + if (value) queryParams.append(key, "true"); } else if (typeof value === "string" && value !== "") { queryParams.append(key, String(value)); } diff --git a/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.test.tsx b/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.test.tsx index d36b414b726..310b5363b0b 100644 --- a/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.test.tsx +++ b/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.test.tsx @@ -142,6 +142,154 @@ describe("PaginatedSearchSelect", () => { expect(onValueChange).toHaveBeenCalledWith("alias-beta"); }); + it("keeps the typed query when a refreshed page of options arrives while a value is selected", async () => { + const user = userEvent.setup(); + const onSearchChange = vi.fn(); + + function ServerBacked() { + const [search, setSearch] = useState(""); + const [value, setValue] = useState("alias-alpha"); + const freshlyBuiltOptions = OPTIONS.filter((option) => option.label.includes(search)).map((option) => ({ + ...option, + })); + return ( + { + onSearchChange(query); + setSearch(query); + }} + onLoadMore={vi.fn()} + /> + ); + } + render(); + + const input = screen.getByRole("combobox"); + await user.click(input); + await user.type(input, "gamma"); + + await waitFor(() => expect(onSearchChange).toHaveBeenLastCalledWith("gamma")); + await waitFor(() => expect(input).toHaveValue("gamma")); + expect(await screen.findByText("gamma-key")).toBeInTheDocument(); + }); + + it("shows the selection again after the popup closes with the query abandoned", async () => { + const user = userEvent.setup(); + renderSelect({ value: "alias-alpha" }); + + const input = screen.getByRole("combobox"); + await user.click(input); + expect(input).toHaveValue(""); + + await user.type(input, "gamma"); + await user.keyboard("{Escape}"); + + await waitFor(() => expect(input).toHaveValue("alias-alpha")); + }); + + it("puts the unfiltered page back when a typed query is abandoned", async () => { + const user = userEvent.setup(); + const onSearchChange = vi.fn(); + renderSelect({ onSearchChange }); + + const input = screen.getByRole("combobox"); + await user.click(input); + await user.type(input, "gamma"); + await waitFor(() => expect(onSearchChange).toHaveBeenCalledWith("gamma")); + + await user.keyboard("{Escape}"); + + await waitFor(() => expect(onSearchChange).toHaveBeenLastCalledWith("")); + }); + + it("puts the unfiltered page back once an option found by typing is picked", async () => { + const user = userEvent.setup(); + const onSearchChange = vi.fn(); + renderSelect({ onSearchChange }); + + const input = screen.getByRole("combobox"); + await user.click(input); + await user.type(input, "gamma"); + await waitFor(() => expect(onSearchChange).toHaveBeenCalledWith("gamma")); + + await user.click(await screen.findByText("gamma-key")); + + await waitFor(() => expect(onSearchChange).toHaveBeenLastCalledWith("")); + }); + + it("keeps the first character when typing is what opened the list", async () => { + const user = userEvent.setup(); + const onSearchChange = vi.fn(); + renderSelect({ onSearchChange }); + + await user.tab(); + await user.keyboard("gamma"); + + expect(screen.getByRole("combobox")).toHaveValue("gamma"); + await waitFor(() => expect(onSearchChange).toHaveBeenLastCalledWith("gamma")); + }); + + it("keeps showing a picked option's label after it drops out of the loaded page", async () => { + const user = userEvent.setup(); + + function Refetching() { + const [options, setOptions] = useState([{ label: "Beta Team", value: "team-2" }]); + const [value, setValue] = useState(""); + return ( + <> + + + + ); + } + render(); + + await user.click(screen.getByRole("combobox")); + await user.click(await screen.findByText("Beta Team")); + await user.click(screen.getByRole("button", { name: "refetch" })); + + expect(screen.getByRole("combobox")).toHaveValue("Beta Team"); + }); + + it("starts a fresh query when typing lands after the selected label", async () => { + const user = userEvent.setup(); + const onSearchChange = vi.fn(); + renderSelect({ onSearchChange, value: "alias-alpha" }); + + const input = screen.getByRole("combobox") as HTMLInputElement; + input.focus(); + input.setSelectionRange(input.value.length, input.value.length); + await user.keyboard("gamma"); + + expect(input).toHaveValue("gamma"); + await waitFor(() => expect(onSearchChange).toHaveBeenLastCalledWith("gamma")); + }); + + it("starts a fresh query when typing lands inside the selected label", async () => { + const user = userEvent.setup(); + const onSearchChange = vi.fn(); + renderSelect({ onSearchChange, value: "alias-alpha" }); + + const input = screen.getByRole("combobox") as HTMLInputElement; + input.focus(); + input.setSelectionRange(3, 3); + await user.keyboard("g"); + + expect(input).toHaveValue("g"); + await waitFor(() => expect(onSearchChange).toHaveBeenLastCalledWith("g")); + }); + it("surfaces loading and fetching-more affordances", async () => { const user = userEvent.setup(); const { unmount } = render( diff --git a/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsx b/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsx index 6966c669187..bb1730941a6 100644 --- a/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsx +++ b/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsx @@ -1,7 +1,7 @@ "use client"; import { Loader2 } from "lucide-react"; -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import { Combobox, @@ -35,6 +35,19 @@ interface PaginatedSearchSelectProps { "aria-describedby"?: string; } +const typedInsertion = (previous: string, next: string): string => { + let start = 0; + while (start < previous.length && start < next.length && previous[start] === next[start]) start++; + let end = 0; + while ( + end < previous.length - start && + end < next.length - start && + previous[previous.length - 1 - end] === next[next.length - 1 - end] + ) + end++; + return next.slice(start, next.length - end); +}; + export function PaginatedSearchSelect({ options, value, @@ -54,10 +67,15 @@ export function PaginatedSearchSelect({ "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy, }: PaginatedSearchSelectProps) { + const [pickedOption, setPickedOption] = useState(null); + const selected = useMemo(() => { if (value === undefined || value === "") return null; - return options.find((option) => option.value === value) ?? { label: value, value }; - }, [options, value]); + return ( + options.find((option) => option.value === value) ?? + (pickedOption?.value === value ? pickedOption : { label: value, value }) + ); + }, [options, value, pickedOption]); const items = useMemo(() => { if (selected === null) return options; @@ -66,14 +84,24 @@ export function PaginatedSearchSelect({ }, [options, selected]); const pagination = { onSearchChange, onLoadMore, hasNextPage, isFetchingNextPage }; - const { handleInputValueChange, handleScroll } = usePaginatedCombobox(pagination); + const { typedQuery, handleInputValueChange, handleOpenChange, handleScroll } = usePaginatedCombobox(pagination); return ( onValueChange(item?.value ?? "")} - onInputValueChange={(next, eventDetails) => handleInputValueChange(next, eventDetails.reason)} + inputValue={typedQuery ?? selected?.label ?? ""} + onValueChange={(item: SearchSelectOption | null) => { + setPickedOption(item); + onValueChange(item?.value ?? ""); + }} + onInputValueChange={(next, eventDetails) => + handleInputValueChange( + typedQuery === null ? typedInsertion(selected?.label ?? "", next) : next, + eventDetails.reason, + ) + } + onOpenChange={(nextOpen, eventDetails) => handleOpenChange(nextOpen, eventDetails.reason)} isItemEqualToValue={(a: SearchSelectOption, b: SearchSelectOption) => a.value === b.value} itemToStringLabel={(item: SearchSelectOption) => item.label} filter={null} diff --git a/ui/litellm-dashboard/src/components/shared/usePaginatedCombobox.ts b/ui/litellm-dashboard/src/components/shared/usePaginatedCombobox.ts index 75171d7d75f..3a51d97cd44 100644 --- a/ui/litellm-dashboard/src/components/shared/usePaginatedCombobox.ts +++ b/ui/litellm-dashboard/src/components/shared/usePaginatedCombobox.ts @@ -1,7 +1,7 @@ "use client"; import { useDebouncedCallback } from "@tanstack/react-pacer/debouncer"; -import type { UIEvent } from "react"; +import { useState, type UIEvent } from "react"; import { DEBOUNCE_WAIT_MS } from "@/utils/debounceConstants"; @@ -23,12 +23,27 @@ export function usePaginatedCombobox({ isFetchingNextPage, }: PaginatedComboboxCallbacks) { const debouncedSearch = useDebouncedCallback(onSearchChange, { wait: DEBOUNCE_WAIT_MS }); + const [typedQuery, setTypedQuery] = useState(null); const handleInputValueChange = (next: string, reason: string) => { - if (!SEARCH_REASONS.has(reason)) return; + if (!SEARCH_REASONS.has(reason)) { + setTypedQuery(null); + return; + } + setTypedQuery(next); debouncedSearch(next); }; + const handleOpenChange = (open: boolean, reason: string) => { + if (!open) { + if (typedQuery) debouncedSearch(""); + setTypedQuery(null); + return; + } + const openedByTyping = SEARCH_REASONS.has(reason); + if (!openedByTyping) setTypedQuery(""); + }; + const handleScroll = (event: UIEvent) => { const target = event.currentTarget; if (target.scrollHeight === 0) return; @@ -38,5 +53,5 @@ export function usePaginatedCombobox({ } }; - return { handleInputValueChange, handleScroll }; + return { typedQuery, handleInputValueChange, handleOpenChange, handleScroll }; } diff --git a/ui/litellm-dashboard/src/components/ui/select.test.tsx b/ui/litellm-dashboard/src/components/ui/select.test.tsx index 15dd266d38c..308b5ecec3b 100644 --- a/ui/litellm-dashboard/src/components/ui/select.test.tsx +++ b/ui/litellm-dashboard/src/components/ui/select.test.tsx @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; const ENVIRONMENTS = [ @@ -63,3 +64,40 @@ describe("SelectValue label resolution", () => { expect(screen.getByTestId("trigger")).toHaveTextContent("Any environment"); }); }); + +function renderOpenableSelect(contentProps?: React.ComponentProps) { + return render( + , + ); +} + +describe("SelectContent anchoring", () => { + it("anchors to the edge of the trigger rather than over it by default", async () => { + const user = userEvent.setup(); + renderOpenableSelect(); + + await user.click(screen.getByTestId("trigger")); + + expect(await screen.findByTestId("content")).toHaveAttribute("data-align-trigger", "false"); + }); + + it("still lets a caller opt into item-aligned anchoring", async () => { + const user = userEvent.setup(); + renderOpenableSelect({ alignItemWithTrigger: true }); + + await user.click(screen.getByTestId("trigger")); + + expect(await screen.findByTestId("content")).toHaveAttribute("data-align-trigger", "true"); + }); +}); diff --git a/ui/litellm-dashboard/src/components/ui/select.tsx b/ui/litellm-dashboard/src/components/ui/select.tsx index 3c3f8c81c66..814695d3418 100644 --- a/ui/litellm-dashboard/src/components/ui/select.tsx +++ b/ui/litellm-dashboard/src/components/ui/select.tsx @@ -49,7 +49,7 @@ function SelectContent({ sideOffset = 4, align = "center", alignOffset = 0, - alignItemWithTrigger = true, + alignItemWithTrigger = false, ...props }: SelectPrimitive.Popup.Props & Pick) { diff --git a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx index 7cd339f1d48..cb7836d603f 100644 --- a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx @@ -23,6 +23,8 @@ interface LogsTableToolbarProps { onSelectedTimeIntervalChange: (value: { value: number; unit: string }) => void; isLiveTail: boolean; onIsLiveTailChange: (value: boolean) => void; + excludeInternalHealthChecks: boolean; + onExcludeInternalHealthChecksChange: (value: boolean) => void; onResetToFirstPage: () => void; onResetFilters: () => void; } @@ -38,6 +40,8 @@ export function LogsTableToolbar({ onSelectedTimeIntervalChange, isLiveTail, onIsLiveTailChange, + excludeInternalHealthChecks, + onExcludeInternalHealthChecksChange, onResetToFirstPage, onResetFilters, }: LogsTableToolbarProps) { @@ -125,6 +129,15 @@ export function LogsTableToolbar({
+
+ Hide Health Checks + +
+ diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.test.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.test.tsx index 893d6219e64..5d96f2637cd 100644 --- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.test.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.test.tsx @@ -69,6 +69,7 @@ describe("RequestLogsFilters", () => { for (const label of [ "Team ID", "Status", + "Cache", "Key Alias", "User ID", "End User", @@ -259,4 +260,37 @@ describe("RequestLogsFilters", () => { expect(await screen.findByText(label)).toBeInTheDocument(); }); + + it.each([ + ["", "All Requests"], + ["hit", "Cache Hit"], + ["miss", "Cache Miss"], + ])("shows the human label on the Cache trigger for %s", async (cacheState, label) => { + renderFilters(cacheState === "" ? {} : { [LOG_FILTER_IDS.CACHE_STATUS]: cacheState }); + + expect(await screen.findByText(label)).toBeInTheDocument(); + }); + + it.each([ + ["Cache Hit", "hit"], + ["Cache Miss", "miss"], + ])("selecting %s sets the cache filter to %s", async (label, expected) => { + const user = userEvent.setup(); + const { set } = renderFilters(); + + await user.click(await screen.findByText("All Requests")); + await user.click(await screen.findByRole("option", { name: label })); + + expect(set).toHaveBeenCalledWith(LOG_FILTER_IDS.CACHE_STATUS, expected); + }); + + it("selecting All Requests clears the cache filter", async () => { + const user = userEvent.setup(); + const { set } = renderFilters({ [LOG_FILTER_IDS.CACHE_STATUS]: "hit" }); + + await user.click(await screen.findByText("Cache Hit")); + await user.click(await screen.findByRole("option", { name: "All Requests" })); + + expect(set).toHaveBeenCalledWith(LOG_FILTER_IDS.CACHE_STATUS, undefined); + }); }); diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.tsx index af6a6d1f178..69257a6f52d 100644 --- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsFilters.tsx @@ -31,6 +31,12 @@ const STATUS_FILTER_ITEMS = [ { value: "success", label: "Success" }, { value: "failure", label: "Failure" }, ] as const; + +const CACHE_FILTER_ITEMS = [ + { value: ALL_VALUE, label: "All Requests" }, + { value: "hit", label: "Cache Hit" }, + { value: "miss", label: "Cache Miss" }, +] as const; const PAGE_SIZE = 50; const asString = (value: unknown): string => (typeof value === "string" ? value : ""); @@ -328,6 +334,27 @@ export function RequestLogsFilters({ get, set, teams, logsWindow }: RequestLogsF + + + + { }); }); + describe("hide health checks", () => { + const toggle = () => screen.getByRole("switch", { name: "Hide Health Checks" }); + + it("defaults to showing health checks and refetches without them from page 1 when toggled on", async () => { + const user = userEvent.setup(); + renderPanel(); + + await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled()); + expect(lastCall()?.params?.exclude_internal_health_checks).toBe(false); + expect(toggle()).not.toBeChecked(); + + await user.click(toggle()); + + await waitFor(() => expect(lastCall()?.params?.exclude_internal_health_checks).toBe(true)); + expect(lastCall()?.page).toBe(1); + expect(toggle()).toBeChecked(); + expect(sessionStorage.getItem("excludeInternalHealthChecks")).toBe("true"); + }); + + it("restores the persisted toggle from sessionStorage", async () => { + sessionStorage.setItem("excludeInternalHealthChecks", "true"); + renderPanel(); + + await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled()); + expect(lastCall()?.params?.exclude_internal_health_checks).toBe(true); + expect(toggle()).toBeChecked(); + }); + + it("falls back to showing health checks when the persisted value is malformed", async () => { + sessionStorage.setItem("excludeInternalHealthChecks", "{not json"); + renderPanel(); + + await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled()); + expect(lastCall()?.params?.exclude_internal_health_checks).toBe(false); + expect(toggle()).not.toBeChecked(); + }); + }); + describe("live tail", () => { it("shows the auto-refresh banner on the first page and hides it once stopped", async () => { const user = userEvent.setup(); diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx index b6f61cb3c6b..52ea78abf5e 100644 --- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx @@ -72,6 +72,14 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID, sessionStorage.setItem("isLiveTail", JSON.stringify(isLiveTail)); }, [isLiveTail]); + const [excludeInternalHealthChecks, setExcludeInternalHealthChecks] = useState( + () => sessionStorage.getItem("excludeInternalHealthChecks") === "true", + ); + + useEffect(() => { + sessionStorage.setItem("excludeInternalHealthChecks", JSON.stringify(excludeInternalHealthChecks)); + }, [excludeInternalHealthChecks]); + const { logsQuery, filteredLogs, allTeams } = useLogFilterLogic({ accessToken, token, @@ -80,6 +88,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID, columnFilters, activeTab: isActive ? "request logs" : "inactive", isLiveTail, + excludeInternalHealthChecks, startTime, endTime, pagination, @@ -219,6 +228,14 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID, setPagination((previous) => ({ ...previous, pageIndex: 0 })); }, []); + const handleExcludeInternalHealthChecksChange = useCallback( + (value: boolean) => { + setExcludeInternalHealthChecks(value); + resetToFirstPage(); + }, + [resetToFirstPage], + ); + const handleResetFilters = useCallback(() => { setColumnFilters([]); setStartTime(moment().subtract(24, "hours").format("YYYY-MM-DDTHH:mm")); @@ -313,6 +330,8 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID, onSelectedTimeIntervalChange={setSelectedTimeInterval} isLiveTail={isLiveTail} onIsLiveTailChange={setIsLiveTail} + excludeInternalHealthChecks={excludeInternalHealthChecks} + onExcludeInternalHealthChecksChange={handleExcludeInternalHealthChecksChange} onResetToFirstPage={resetToFirstPage} onResetFilters={handleResetFilters} /> diff --git a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsx b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsx index 26c5bda1593..1b738db097d 100644 --- a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsx @@ -47,6 +47,7 @@ const defaultProps = { columnFilters: [] as ColumnFiltersState, activeTab: "request logs", isLiveTail: false, + excludeInternalHealthChecks: false, startTime: "2025-01-01T00:00:00", endTime: "2025-01-01T23:59:59", pagination: FIRST_PAGE, @@ -82,6 +83,8 @@ describe("useLogFilterLogic", () => { { id: LOG_FILTER_IDS.SESSION_ID, value: "sess-1", param: "session_id" }, { id: LOG_FILTER_IDS.END_USER, value: "end-user-1", param: "end_user" }, { id: LOG_FILTER_IDS.STATUS, value: "failure", param: "status_filter" }, + { id: LOG_FILTER_IDS.CACHE_STATUS, value: "hit", param: "cache_hit_filter" }, + { id: LOG_FILTER_IDS.CACHE_STATUS, value: "miss", param: "cache_hit_filter" }, { id: LOG_FILTER_IDS.MODEL_ID, value: "model-uuid-1", param: "model_id" }, { id: LOG_FILTER_IDS.PUBLIC_MODEL_OR_SEARCH_TOOL, value: "gpt-4o", param: "model" }, { id: LOG_FILTER_IDS.KEY_ALIAS, value: "alias-1", param: "key_alias" }, @@ -152,6 +155,7 @@ describe("useLogFilterLogic", () => { ["pagination", { pagination: { pageIndex: 1, pageSize: 50 } }], ["startTime", { startTime: "2025-02-02T00:00:00" }], ["columnFilters", { columnFilters: [{ id: LOG_FILTER_IDS.TEAM_ID, value: "team-2" }] }], + ["excludeInternalHealthChecks", { excludeInternalHealthChecks: true }], ])("refetches when %s changes", async (_label, nextProps) => { const { rerender } = renderHook((props: HookOverrides) => useLogFilterLogic({ ...defaultProps, ...props }), { wrapper, @@ -164,6 +168,22 @@ describe("useLogFilterLogic", () => { }); }); + describe("hide health checks toggle", () => { + it("passes exclude_internal_health_checks when the toggle is on", async () => { + renderFilterHook({ excludeInternalHealthChecks: true }); + + await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled()); + expect(lastCallParams()?.params).toMatchObject({ exclude_internal_health_checks: true }); + }); + + it("passes exclude_internal_health_checks as false when the toggle is off", async () => { + renderFilterHook(); + + await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled()); + expect(lastCallParams()?.params).toMatchObject({ exclude_internal_health_checks: false }); + }); + }); + describe("query enablement", () => { it("does not query when the request logs tab is inactive", async () => { renderFilterHook({ activeTab: "audit logs" }); diff --git a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx index 474f51e93b3..3b8d96596de 100644 --- a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx @@ -20,6 +20,7 @@ export interface PaginatedResponse { export const LOG_FILTER_IDS = { TEAM_ID: "team_id", STATUS: "status", + CACHE_STATUS: "cache_hit", KEY_ALIAS: "key_alias", END_USER: "end_user", ERROR_CODE: "error_code", @@ -35,6 +36,7 @@ export const LOG_FILTER_IDS = { export const LOG_FILTER_LABELS: Record = { [LOG_FILTER_IDS.TEAM_ID]: "Team ID", [LOG_FILTER_IDS.STATUS]: "Status", + [LOG_FILTER_IDS.CACHE_STATUS]: "Cache", [LOG_FILTER_IDS.KEY_ALIAS]: "Key Alias", [LOG_FILTER_IDS.USER_ID]: "User ID", [LOG_FILTER_IDS.END_USER]: "End User", @@ -101,6 +103,7 @@ export function useLogFilterLogic({ columnFilters, activeTab, isLiveTail, + excludeInternalHealthChecks, startTime, endTime, pagination, @@ -114,6 +117,7 @@ export function useLogFilterLogic({ columnFilters: ColumnFiltersState; activeTab: string; isLiveTail: boolean; + excludeInternalHealthChecks: boolean; startTime: string; endTime: string; pagination: PaginationState; @@ -137,6 +141,7 @@ export function useLogFilterLogic({ columnFilters, sortBy, sortOrder, + excludeInternalHealthChecks, ], queryFn: async () => { if (!accessToken || !token || !userRole || !userID) { @@ -167,6 +172,7 @@ export function useLogFilterLogic({ user_id: userIdFilter, end_user: getFilterValue(columnFilters, LOG_FILTER_IDS.END_USER), status_filter: getFilterValue(columnFilters, LOG_FILTER_IDS.STATUS), + cache_hit_filter: getFilterValue(columnFilters, LOG_FILTER_IDS.CACHE_STATUS), model_id: getFilterValue(columnFilters, LOG_FILTER_IDS.MODEL_ID), model: getFilterValue(columnFilters, LOG_FILTER_IDS.PUBLIC_MODEL_OR_SEARCH_TOOL), key_alias: getFilterValue(columnFilters, LOG_FILTER_IDS.KEY_ALIAS), @@ -174,6 +180,7 @@ export function useLogFilterLogic({ error_message: getFilterValue(columnFilters, LOG_FILTER_IDS.ERROR_MESSAGE), sort_by: sortBy, sort_order: sortOrder, + exclude_internal_health_checks: excludeInternalHealthChecks, }, }); }, diff --git a/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts b/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts index a2d23473fb9..02f39c5344c 100644 --- a/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts +++ b/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts @@ -99,6 +99,36 @@ describe("autorouter_presets", () => { ); }); + // Opus serves both tiers, so the effort is all that separates them and losing it fails silently. + it("pins the anthropic preset's reasoning tier to Opus at high thinking", () => { + const config = getPresetByKey("anthropic_family")!.complexity_router_config; + expect(config.tiers.COMPLEX).toEqual(["claude-opus-5"]); + expect(config.tiers.REASONING).toEqual(["claude-opus-5"]); + expect(config.tier_model_configs).toEqual({ + REASONING: [{ model_name: "claude-opus-5", litellm_params: { reasoning_effort: "high" } }], + }); + }); + + // serializeTierModelConfigs filters on the tier's models, so a stray name drops silently. + it("never names a model in tier_model_configs that its own tier does not hold", () => { + for (const preset of getAllPresets()) { + const { tiers, tier_model_configs: configs } = preset.complexity_router_config; + for (const [tier, entries] of Object.entries(configs ?? {})) { + for (const entry of entries) { + expect(tiers[tier as keyof typeof tiers] ?? [], `${preset.key}.${tier}`).toContain(entry.model_name); + } + } + } + }); + + it("prefills the anthropic preset's effort through to tier_model_params", () => { + const preset = getPresetByKey("anthropic_family")!; + const prefill = buildPresetPrefill(preset.complexity_router_config, groupsOnly(getRequiredModelsInPreset(preset))); + expect(prefill.complexityRouterConfig.tier_model_params).toEqual({ + REASONING: { "claude-opus-5": { reasoning_effort: "high" } }, + }); + }); + it("pins the gemini preset to concrete model ids, never Google's hot-swapping -latest aliases", () => { const gemini = getPresetByKey("gemini_family")!; const config = gemini.complexity_router_config; diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index 5e5ff63e9ed..03a4d1142f8 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -21,6 +21,52 @@ export interface paths { patch?: never; trace?: never; }; + "/.well-known/jwks.json": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Jwks Json + * @description JSON Web Key Set endpoint. + * + * Returns the RSA public key used by MCPJWTSigner to sign outbound MCP tokens. + * MCP servers and gateways use this endpoint to verify liteLLM-issued JWTs. + * + * Returns an empty key set if MCPJWTSigner is not configured. + */ + get: operations["jwks_json__well_known_jwks_json_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/litellm-cli-auth": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Native Client Auth Discovery + * @description The versioned contract a native client (``lite login --pkce``, or a CLI in any other + * language) reads to sign a user in through the browser and obtain a proxy credential. + */ + get: operations["native_client_auth_discovery__well_known_litellm_cli_auth_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/.well-known/litellm-ui-config": { parameters: { query?: never; @@ -38,6 +84,241 @@ export interface paths { patch?: never; trace?: never; }; + "/.well-known/oauth-authorization-server": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Authorization Server Mcp + * @description OAuth authorization server discovery endpoint. + * + * Supports both legacy pattern (/{server_name}) and root endpoint. + */ + get: operations["oauth_authorization_server_mcp__well_known_oauth_authorization_server_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-authorization-server/mcp": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Authorization Server Aggregate + * @description OAuth authorization server discovery for the aggregate /mcp endpoint, the RFC 8414 + * path-inserted form for a client that treats {base}/mcp as its authorization base URL. + * + * The single-segment /mcp is reserved for the aggregate so the discovery chain stays + * consistent: the aggregate protected-resource document advertises {base}/mcp as its + * authorization server, so the document served here must have issuer {base}/mcp. A server + * literally named ``mcp`` therefore does not take this route; it keeps its standard + * two-segment discovery at /.well-known/oauth-authorization-server/mcp/mcp. Letting the + * per-server row win here instead would serve an issuer of {base} against a resource that + * advertised {base}/mcp, which fails the RFC 8414 issuer check and breaks the front door. + */ + get: operations["oauth_authorization_server_aggregate__well_known_oauth_authorization_server_mcp_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-authorization-server/mcp/{mcp_server_name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Authorization Server Mcp Standard + * @description OAuth authorization server discovery endpoint using standard MCP URL pattern. + * + * Standard pattern: /mcp/{server_name} + * Discovery path: /.well-known/oauth-authorization-server/mcp/{server_name} + */ + get: operations["oauth_authorization_server_mcp_standard__well_known_oauth_authorization_server_mcp__mcp_server_name__get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-authorization-server/{mcp_server_name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Authorization Server Mcp + * @description OAuth authorization server discovery endpoint. + * + * Supports both legacy pattern (/{server_name}) and root endpoint. + */ + get: operations["oauth_authorization_server_mcp__well_known_oauth_authorization_server__mcp_server_name__get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-authorization-server/{mcp_server_name}/mcp": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Authorization Server Legacy + * @description OAuth authorization server discovery for legacy /{server_name}/mcp pattern. + */ + get: operations["oauth_authorization_server_legacy__well_known_oauth_authorization_server__mcp_server_name__mcp_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-protected-resource": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Protected Resource Mcp + * @description OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern. + * + * Legacy pattern: /{server_name}/mcp + * Discovery path: /.well-known/oauth-protected-resource/{server_name}/mcp + * + * This endpoint is kept for backward compatibility. New integrations should + * use the standard MCP pattern (/mcp/{server_name}) instead. + */ + get: operations["oauth_protected_resource_mcp__well_known_oauth_protected_resource_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-protected-resource/mcp": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Protected Resource Aggregate + * @description OAuth protected resource discovery for the aggregate /mcp endpoint. + * + * The single-segment ``/mcp`` path does not collide with any per-server PRM pattern + * (those are two-segment: ``/mcp/{server}`` or ``/{server}/mcp``), so this unambiguously + * describes the aggregate resource. + */ + get: operations["oauth_protected_resource_aggregate__well_known_oauth_protected_resource_mcp_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-protected-resource/mcp/{mcp_server_name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Protected Resource Mcp Standard + * @description OAuth protected resource discovery endpoint using standard MCP URL pattern. + * + * Standard pattern: /mcp/{server_name} + * Discovery path: /.well-known/oauth-protected-resource/mcp/{server_name} + * + * This endpoint is compliant with MCP specification and works with standard + * MCP clients like mcp-inspector and VSCode Copilot. + */ + get: operations["oauth_protected_resource_mcp_standard__well_known_oauth_protected_resource_mcp__mcp_server_name__get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-protected-resource/{mcp_server_name}/mcp": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Oauth Protected Resource Mcp + * @description OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern. + * + * Legacy pattern: /{server_name}/mcp + * Discovery path: /.well-known/oauth-protected-resource/{server_name}/mcp + * + * This endpoint is kept for backward compatibility. New integrations should + * use the standard MCP pattern (/mcp/{server_name}) instead. + */ + get: operations["oauth_protected_resource_mcp__well_known_oauth_protected_resource__mcp_server_name__mcp_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/openid-configuration": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Openid Configuration */ + get: operations["openid_configuration__well_known_openid_configuration_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/a2a/{agent_id}": { parameters: { query?: never; @@ -760,6 +1041,48 @@ export interface paths { patch?: never; trace?: never; }; + "/authorize": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Authorize */ + get: operations["authorize_authorize_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/authorize/complete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Authorize Complete + * @description Finish an aggregate connect flow: mint the gateway authorization code for the + * signed-in user and hand it back to the DCR client, by 303 redirect (default) or, for + * a loopback client on a different machine, as a copyable callback URL + * (``delivery=manual``). POST plus the per-flow HttpOnly cookie set at /authorize; an + * anonymous or bad-flow request just 400s. The native-client consent page adds + * ``decision`` (approve or deny) and the ``team_id`` the credential is attributed to. + */ + post: operations["authorize_complete_authorize_complete_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/auto_router/benchmarks": { parameters: { query?: never; @@ -1535,6 +1858,37 @@ export interface paths { patch?: never; trace?: never; }; + "/callback": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Callback + * @description OAuth 2.0 authorization response handler for MCP loopback clients. + * + * Accepts either: + * + * - A successful authorization response (``code`` + ``state``), which is + * forwarded back to the validated client ``redirect_uri`` with the + * original (un-wrapped) ``state``. + * - An error response (``error``[+``error_description``/``error_uri``]), per + * RFC 6749 §4.1.2.1. When ``state`` is present and decodes to a trusted + * ``redirect_uri``, the error params are propagated back to the client so + * its OAuth library can surface them. Otherwise we render an HTML error + * page so the user is not left on an opaque 422 / blank screen. + */ + get: operations["callback_callback_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/callbacks/configs": { parameters: { query?: never; @@ -1677,6 +2031,8 @@ export interface paths { * the same name already exists it returns 409 Conflict; use * PUT /claude-code/plugins/{plugin_name} to update an existing plugin. * + * Requires a proxy admin API key. + * * Parameters: * - name: Plugin name (kebab-case) * - source: Git source reference (github, url, or git-subdir format) @@ -1741,6 +2097,8 @@ export interface paths { * Returns 404 if no plugin with the given name exists; use * POST /claude-code/plugins to create a new plugin. * + * Requires a proxy admin API key. + * * Parameters: * - plugin_name: Name of the plugin to update (path parameter) * - source: Git source reference (github, url, or git-subdir format) @@ -1772,6 +2130,8 @@ export interface paths { * Delete Plugin * @description Delete a plugin from the marketplace. * + * Requires a proxy admin API key. + * * Parameters: * - plugin_name: The name of the plugin to delete */ @@ -1794,6 +2154,8 @@ export interface paths { * Disable Plugin * @description Disable a plugin without deleting it. * + * Requires a proxy admin API key. + * * Parameters: * - plugin_name: The name of the plugin to disable */ @@ -1817,6 +2179,8 @@ export interface paths { * Enable Plugin * @description Enable a disabled plugin. * + * Requires a proxy admin API key. + * * Parameters: * - plugin_name: The name of the plugin to enable */ @@ -7886,6 +8250,8 @@ export interface paths { * "mcp_info": { * "server_name": "zapier", * "logo_url": "https://www.zapier.com/logo.png", + * "server_id": "a1b2c3d4-...", + * "alias": "zapier_prod", * } * } * ], @@ -9062,6 +9428,30 @@ export interface paths { patch?: never; trace?: never; }; + "/openai/v1/realtime/transcription_sessions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Create Realtime Transcription Session + * @description Create an ephemeral Realtime transcription session + * (POST /v1/realtime/transcription_sessions) for the WebRTC/WebSocket flow. + * + * Mirrors the client_secrets route but targets the transcription_sessions + * endpoint and encrypts the ephemeral key returned under `client_secret.value`. + */ + post: operations["create_realtime_transcription_session_openai_v1_realtime_transcription_sessions_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/openai/v1/responses": { parameters: { query?: never; @@ -10220,7 +10610,10 @@ export interface paths { * @description List all policies from the database and config.yaml. Optionally filter by version_status. * * Config-defined policies are returned with definition_location "config" and are treated - * as production versions. On a name conflict with a DB policy, only the DB policy is returned. + * as production versions. On a name conflict with a production DB policy, only the DB policy + * is returned, mirroring runtime resolution where only production DB versions override config. + * A draft or published DB version does not hide the config policy, since the config version + * is still the one being enforced. * * Query params: * - version_status: Optional. One of "draft", "published", "production". @@ -11840,6 +12233,47 @@ export interface paths { patch?: never; trace?: never; }; + "/realtime/transcription_sessions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Create Realtime Transcription Session + * @description Create an ephemeral Realtime transcription session + * (POST /v1/realtime/transcription_sessions) for the WebRTC/WebSocket flow. + * + * Mirrors the client_secrets route but targets the transcription_sessions + * endpoint and encrypts the ephemeral key returned under `client_secret.value`. + */ + post: operations["create_realtime_transcription_session_realtime_transcription_sessions_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/register": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Register Client */ + post: operations["register_client_register_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/reload/anthropic_beta_headers": { parameters: { query?: never; @@ -12079,6 +12513,28 @@ export interface paths { patch?: never; trace?: never; }; + "/revoke": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Revoke Endpoint + * @description RFC 7009 revocation for the gateway's refresh tokens (``lite logout``): 200 for a known + * client whatever the token's state, 503 when the shared single-use record cannot be written; + * access tokens expire on their own. + */ + post: operations["revoke_endpoint_revoke_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/robots.txt": { parameters: { query?: never; @@ -15130,6 +15586,32 @@ export interface paths { patch?: never; trace?: never; }; + "/token": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Token Endpoint + * @description Accept the authorization code from client and exchange it for OAuth token. + * Supports PKCE flow by forwarding code_verifier to upstream provider. + * + * 1. Call the token endpoint with PKCE parameters + * 2. Store the user's token in the db - and generate a LiteLLM virtual key + * 3. Return the token + * 4. Return a virtual key in this response + */ + post: operations["token_endpoint_token_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/toolset/{toolset_name}/mcp": { parameters: { query?: never; @@ -15990,27 +16472,25 @@ export interface paths { path?: never; cookie?: never; }; - /** a2a_registration */ - get: { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description OK */ - 200: { - headers: { - [name: string]: unknown; - }; - content?: never; - }; - }; - }; + get?: never; put?: never; - post?: never; + /** + * Discover Agent Card + * @description Fetch the upstream agent's well-known card so the UI can show the admin + * which skills/capabilities the agent exposes. + * + * Only proxy admins can call this — the UI uses it during agent registration, + * and we don't want arbitrary keys probing internal URLs. + * + * Example: + * ```bash + * curl -X POST "http://localhost:4000/v1/a2a/discover" \ + * -H "Authorization: Bearer " \ + * -H "Content-Type: application/json" \ + * -d '{"url": "https://upstream-agent.example.com"}' + * ``` + */ + post: operations["discover_agent_card_v1_a2a_discover_post"]; delete?: never; options?: never; head?: never; @@ -16110,30 +16590,30 @@ export interface paths { * -H "Content-Type: application/json" \ * -d '{ * "agent_name": "my-custom-agent", - * "agent_card_params": { - * "protocolVersion": "1.0", - * "name": "Hello World Agent", - * "description": "Just a hello world agent", - * "url": "http://localhost:9999/", - * "version": "1.0.0", - * "defaultInputModes": ["text"], - * "defaultOutputModes": ["text"], - * "capabilities": { - * "streaming": true - * }, - * "skills": [ - * { - * "id": "hello_world", - * "name": "Returns hello world", - * "description": "just returns hello world", - * "tags": ["hello world"], - * "examples": ["hi", "hello world"] - * } - * ] + * "agent_card_params": { + * "protocolVersion": "1.0", + * "name": "Hello World Agent", + * "description": "Just a hello world agent", + * "url": "http://localhost:9999/", + * "version": "1.0.0", + * "defaultInputModes": ["text"], + * "defaultOutputModes": ["text"], + * "capabilities": { + * "streaming": true * }, - * "litellm_params": { - * "make_public": true - * } + * "skills": [ + * { + * "id": "hello_world", + * "name": "Returns hello world", + * "description": "just returns hello world", + * "tags": ["hello world"], + * "examples": ["hi", "hello world"] + * } + * ] + * }, + * "litellm_params": { + * "make_public": true + * } * }' * ``` */ @@ -16203,7 +16683,7 @@ export interface paths { * * Example Request: * ```bash - * curl -X GET "http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000" \ + * curl -X GET "http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000" \ * -H "Authorization: Bearer " * ``` */ @@ -16214,28 +16694,26 @@ export interface paths { * * Example Request: * ```bash - * curl -X PUT "http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000" \ + * curl -X PUT "http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000" \ * -H "Authorization: Bearer " \ * -H "Content-Type: application/json" \ * -d '{ - * "agent": { - * "agent_name": "updated-agent", - * "agent_card_params": { - * "protocolVersion": "1.0", - * "name": "Updated Agent", - * "description": "Updated description", - * "url": "http://localhost:9999/", - * "version": "1.1.0", - * "defaultInputModes": ["text"], - * "defaultOutputModes": ["text"], - * "capabilities": { - * "streaming": true - * }, - * "skills": [] + * "agent_name": "updated-agent", + * "agent_card_params": { + * "protocolVersion": "1.0", + * "name": "Updated Agent", + * "description": "Updated description", + * "url": "http://localhost:9999/", + * "version": "1.1.0", + * "defaultInputModes": ["text"], + * "defaultOutputModes": ["text"], + * "capabilities": { + * "streaming": true * }, - * "litellm_params": { - * "make_public": false - * } + * "skills": [] + * }, + * "litellm_params": { + * "make_public": false * } * }' * ``` @@ -16248,7 +16726,7 @@ export interface paths { * * Example Request: * ```bash - * curl -X DELETE "http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000" \ + * curl -X DELETE "http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000" \ * -H "Authorization: Bearer " * ``` * @@ -16268,28 +16746,26 @@ export interface paths { * * Example Request: * ```bash - * curl -X PUT "http://localhost:4000/agents/123e4567-e89b-12d3-a456-426614174000" \ + * curl -X PATCH "http://localhost:4000/v1/agents/123e4567-e89b-12d3-a456-426614174000" \ * -H "Authorization: Bearer " \ * -H "Content-Type: application/json" \ * -d '{ - * "agent": { - * "agent_name": "updated-agent", - * "agent_card_params": { - * "protocolVersion": "1.0", - * "name": "Updated Agent", - * "description": "Updated description", - * "url": "http://localhost:9999/", - * "version": "1.1.0", - * "defaultInputModes": ["text"], - * "defaultOutputModes": ["text"], - * "capabilities": { - * "streaming": true - * }, - * "skills": [] + * "agent_name": "updated-agent", + * "agent_card_params": { + * "protocolVersion": "1.0", + * "name": "Updated Agent", + * "description": "Updated description", + * "url": "http://localhost:9999/", + * "version": "1.1.0", + * "defaultInputModes": ["text"], + * "defaultOutputModes": ["text"], + * "capabilities": { + * "streaming": true * }, - * "litellm_params": { - * "make_public": false - * } + * "skills": [] + * }, + * "litellm_params": { + * "make_public": false * } * }' * ``` @@ -17306,17 +17782,27 @@ export interface paths { path?: never; cookie?: never; }; - get?: never; + /** + * Index List + * @description List all vector store indexes. Proxy admin only. + * + * ```bash + * curl -L -X GET 'http://0.0.0.0:4000/v1/indexes' -H 'Authorization: Bearer sk-1234' + * ``` + */ + get: operations["index_list_v1_indexes_get"]; put?: never; /** * Index Create * @description Create an index. Just writes the index to the database. * * ```bash - * curl -L -X POST 'http://0.0.0.0:4000/indexes/create' -H 'Content-Type: application/json' -H 'Authorization: Bearer sk-1234' -H 'LiteLLM-Beta: indexes_beta=v1' -d '{ + * curl -L -X POST 'http://0.0.0.0:4000/v1/indexes' -H 'Content-Type: application/json' -H 'Authorization: Bearer sk-1234' -d '{ * "index_name": "dall-e-3", - * "vector_store_index": "real-index-name", - * "vector_store_name": "azure-ai-search" + * "litellm_params": { + * "vector_store_index": "real-index-name", + * "vector_store_name": "azure-ai-search" + * } * }' * ``` */ @@ -17687,6 +18173,34 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/mcp/server/{server_id}/user-env-vars": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get Mcp User Env Vars + * @description Return the calling user's per-user MCP env var status for this server. + */ + get: operations["get_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_get"]; + put?: never; + /** + * Store Mcp User Env Vars + * @description Store the calling user's per-user MCP env var values for this server. Submitted values are merged over any previously stored values, so you only send the fields you want to set or change; a variable omitted (or sent empty) keeps its stored value. Use DELETE to clear all stored values. + */ + post: operations["store_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_post"]; + /** + * Clear Mcp User Env Vars + * @description Clear the calling user's per-user MCP env var values for this server. + */ + delete: operations["clear_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_delete"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/mcp/tools": { parameters: { query?: never; @@ -17779,6 +18293,26 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/mcp/user-env-vars/status": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List Mcp User Env Var Status + * @description Per-user MCP env var status across every server the user can access. Used by the dashboard to highlight servers with missing per-user vars. + */ + get: operations["list_mcp_user_env_var_status_v1_mcp_user_env_vars_status_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/memory": { parameters: { query?: never; @@ -18301,6 +18835,30 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/realtime/transcription_sessions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Create Realtime Transcription Session + * @description Create an ephemeral Realtime transcription session + * (POST /v1/realtime/transcription_sessions) for the WebRTC/WebSocket flow. + * + * Mirrors the client_secrets route but targets the transcription_sessions + * endpoint and encrypts the ephemeral key returned under `client_secret.value`. + */ + post: operations["create_realtime_transcription_session_v1_realtime_transcription_sessions_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/rerank": { parameters: { query?: never; @@ -19687,25 +20245,118 @@ export interface paths { path?: never; cookie?: never; }; - /** gemini_agents */ - get: { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description OK */ - 200: { - headers: { - [name: string]: unknown; - }; - content?: never; - }; - }; + /** + * List Gemini Agents + * @description List all custom agents on the Gemini side. + * + * Pass per-request Gemini credentials via the JSON-encoded + * ``litellm_params_template`` query parameter. Flat query parameters + * (e.g. ``?api_key=AIza...``) are intentionally ignored — see + * ``_merge_query_params_into_data`` for the rationale. + * + * ```bash + * curl "http://localhost:4000/v1beta/agents?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D" \ + * -H "Authorization: Bearer sk-..." + * ``` + */ + get: operations["list_gemini_agents_v1beta_agents_get"]; + put?: never; + /** + * Create Gemini Agent + * @description Create a named custom agent on the Gemini side. + * + * Example: + * ```bash + * curl -X POST "http://localhost:4000/v1beta/agents" \ + * -H "Authorization: Bearer sk-..." \ + * -H "Content-Type: application/json" \ + * -d '{ + * "name": "my-custom-slides-agent", + * "base_agent": "waverunner", + * "instructions": "You are a helpful assistant that creates slides.", + * "base_environment": { + * "type": "remote", + * "sources": [ + * {"type": "gcs", "source": "gs://eap-templates/slides-skill", + * "target": "/.agents/skills/slides-skill"} + * ] + * } + * }' + * ``` + */ + post: operations["create_gemini_agent_v1beta_agents_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1beta/agents/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; + /** + * Get Gemini Agent + * @description Get a specific custom agent by name. + * + * Pass per-request Gemini credentials via the JSON-encoded + * ``litellm_params_template`` query parameter. Flat query parameters + * (e.g. ``?api_key=AIza...``) are intentionally ignored — see + * ``_merge_query_params_into_data`` for the rationale. + * + * ```bash + * curl "http://localhost:4000/v1beta/agents/my-custom-slides-agent?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D" \ + * -H "Authorization: Bearer sk-..." + * ``` + */ + get: operations["get_gemini_agent_v1beta_agents__name__get"]; + put?: never; + post?: never; + /** + * Delete Gemini Agent + * @description Delete a custom agent by name. + * + * Pass per-request Gemini credentials via the JSON-encoded + * ``litellm_params_template`` query parameter. Flat query parameters + * (e.g. ``?api_key=AIza...``) are intentionally ignored — see + * ``_merge_query_params_into_data`` for the rationale. + * + * ```bash + * curl -X DELETE "http://localhost:4000/v1beta/agents/my-custom-slides-agent?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D" \ + * -H "Authorization: Bearer sk-..." + * ``` + */ + delete: operations["delete_gemini_agent_v1beta_agents__name__delete"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1beta/agents/{name}/versions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List Gemini Agent Versions + * @description List versions of a custom agent. + * + * Pass per-request Gemini credentials via the JSON-encoded + * ``litellm_params_template`` query parameter. Flat query parameters + * (e.g. ``?api_key=AIza...``) are intentionally ignored — see + * ``_merge_query_params_into_data`` for the rationale. + * + * ```bash + * curl "http://localhost:4000/v1beta/agents/my-custom-slides-agent/versions?litellm_params_template=%7B%22api_key%22%3A%22AIza...%22%7D" \ + * -H "Authorization: Bearer sk-..." + * ``` + */ + get: operations["list_gemini_agent_versions_v1beta_agents__name__versions_get"]; put?: never; post?: never; delete?: never; @@ -21086,6 +21737,23 @@ export interface paths { patch: operations["watsonx_proxy_route_watsonx__endpoint__patch"]; trace?: never; }; + "/{mcp_server_name}/authorize": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Authorize */ + get: operations["authorize__mcp_server_name__authorize_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/{mcp_server_name}/mcp": { parameters: { query?: never; @@ -21172,6 +21840,49 @@ export interface paths { patch: operations["dynamic_mcp_route__mcp_server_name__mcp_patch"]; trace?: never; }; + "/{mcp_server_name}/register": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Register Client */ + post: operations["register_client__mcp_server_name__register_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/{mcp_server_name}/token": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Token Endpoint + * @description Accept the authorization code from client and exchange it for OAuth token. + * Supports PKCE flow by forwarding code_verifier to upstream provider. + * + * 1. Call the token endpoint with PKCE parameters + * 2. Store the user's token in the db - and generate a LiteLLM virtual key + * 3. Return the token + * 4. Return a virtual key in this response + */ + post: operations["token_endpoint__mcp_server_name__token_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/{provider}/v1/batches": { parameters: { query?: never; @@ -21705,6 +22416,15 @@ export interface components { /** Url */ url?: string; }; + /** AgentKeySummary */ + AgentKeySummary: { + /** Key Alias */ + key_alias?: string | null; + /** Key Name */ + key_name?: string | null; + /** Token */ + token: string; + }; /** AgentMakePublicResponse */ AgentMakePublicResponse: { /** Message */ @@ -21755,6 +22475,8 @@ export interface components { created_by?: string | null; /** Extra Headers */ extra_headers?: string[] | null; + /** Keys */ + keys?: components["schemas"]["AgentKeySummary"][] | null; /** Litellm Params */ litellm_params?: { [key: string]: unknown; @@ -22174,7 +22896,7 @@ export interface components { routing_decision: components["schemas"]["StandardLoggingRoutingDecision"]; }; /** BaseLitellmParams */ - "BaseLitellmParams-Input": { + BaseLitellmParams: { /** * Additional Provider Specific Params * @description Additional provider-specific parameters for generic guardrail APIs @@ -22254,7 +22976,7 @@ export interface components { extra_headers?: string[] | null; /** * Fail On Error - * @description Whether to fail the request if Model Armor encounters an error + * @description Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it. * @default true */ fail_on_error: boolean | null; @@ -22288,186 +23010,22 @@ export interface components { * @description Optional field if guardrail requires a 'model' parameter */ model?: string | null; + /** + * On Sensitive Data + * @description Action to take when sensitive data is detected. 'block' raises an exception (default behavior). 'route' reroutes the request to the model specified in sensitive_data_route_to_model. + */ + on_sensitive_data?: ("block" | "route") | null; /** * On Violation * @description For /v1/realtime sessions: 'warn' speaks the violation message and continues; 'end_session' speaks the message and closes the connection. */ on_violation?: ("warn" | "end_session") | null; /** - * Pangea Input Recipe - * @description Recipe for input (LLM request) - */ - pangea_input_recipe?: string | null; - /** - * Pangea Output Recipe - * @description Recipe for output (LLM response) - */ - pangea_output_recipe?: string | null; - /** - * Pattern Redaction Format - * @description Format string for pattern redaction (use {pattern_name} placeholder) - */ - pattern_redaction_format?: string | null; - /** - * Patterns - * @description List of patterns (prebuilt or custom regex) to detect - */ - patterns?: components["schemas"]["ContentFilterPattern"][] | null; - /** - * Realtime Violation Message - * @description The message the bot speaks aloud when a /v1/realtime guardrail fires. Falls back to violation_message_template if not set. - */ - realtime_violation_message?: string | null; - /** - * Severity Threshold - * @description Minimum severity to block (high, medium, low) - */ - severity_threshold?: string | null; - /** - * Skip System Message In Guardrail - * @description When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting. - */ - skip_system_message_in_guardrail?: boolean | null; - /** - * Template Id - * @description The ID of your Model Armor template - */ - template_id?: string | null; - /** - * Unreachable Fallback - * @description Behavior when a guardrail endpoint is unreachable due to network errors. NOTE: This is currently only implemented by guardrail='generic_guardrail_api'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed. - * @default fail_closed - * @enum {string} - */ - unreachable_fallback: "fail_closed" | "fail_open"; - /** - * Violation Message Template - * @description Custom message when a guardrail blocks an action. Supports placeholders like {tool_name}, {rule_id}, and {default_message}. - */ - violation_message_template?: string | null; - } & { - [key: string]: unknown; - }; - /** BaseLitellmParams */ - "BaseLitellmParams-Output": { - /** - * Additional Provider Specific Params - * @description Additional provider-specific parameters for generic guardrail APIs - */ - additional_provider_specific_params?: { - [key: string]: unknown; - } | null; - /** - * Api Base - * @description Base URL for the guardrail service API - */ - api_base?: string | null; - /** - * Api Endpoint - * @description Optional custom API endpoint for Model Armor - */ - api_endpoint?: string | null; - /** - * Api Key - * @description API key for the guardrail service - */ - api_key?: string | null; - /** - * Blocked Words - * @description List of blocked words with individual actions - */ - blocked_words?: components["schemas"]["BlockedWord"][] | null; - /** - * Blocked Words File - * @description Path to YAML file containing blocked_words list - */ - blocked_words_file?: string | null; - /** - * Categories - * @description List of prebuilt categories to enable (harmful_*, bias_*) - */ - categories?: components["schemas"]["ContentFilterCategoryConfig"][] | null; - /** @description Threshold configuration for Lakera guardrail categories */ - category_thresholds?: components["schemas"]["LakeraCategoryThresholds"] | null; - /** - * Credentials - * @description Path to Google Cloud credentials JSON file or JSON string - */ - credentials?: string | null; - /** - * Custom Code - * @description Python-like code containing the apply_guardrail function for custom guardrail logic - */ - custom_code?: string | null; - /** - * Default On - * @description Whether the guardrail is enabled by default - */ - default_on?: boolean | null; - /** - * Detect Secrets Config - * @description Configuration for detect-secrets guardrail - */ - detect_secrets_config?: { - [key: string]: unknown; - } | null; - /** - * End Session After N Fails - * @description For /v1/realtime sessions: automatically close the session after this many guardrail violations. - */ - end_session_after_n_fails?: number | null; - /** - * Experimental Use Latest Role Message Only - * @description When True, guardrails only receive the latest message for the relevant role (e.g., newest user input pre-call, newest assistant output post-call) + * Only Scan New Messages + * @description When True, the guardrail only scans messages that have not already been scanned earlier in the same session (identified by litellm_session_id / session_id). Message content is hashed per session and cached; only the diff (new or edited messages) is sent to the guardrail provider on follow-up calls. Falls back to a full scan when the request has no session id or the cache is unavailable. Intended for blocking/detection guardrails; not applied when mask_request_content is set. * @default false */ - experimental_use_latest_role_message_only: boolean | null; - /** - * Extra Headers - * @description Header names to forward from the client request to the guardrail (e.g. x-request-id). Only these headers' values are sent; others may be omitted or sent as [present]. Used by generic_guardrail_api (similar to MCP extra_headers). - */ - extra_headers?: string[] | null; - /** - * Fail On Error - * @description Whether to fail the request if Model Armor encounters an error - * @default true - */ - fail_on_error: boolean | null; - /** - * Guard Name - * @description Name of the guardrail in guardrails.ai - */ - guard_name?: string | null; - /** - * Keyword Redaction Tag - * @description Tag to use for keyword redaction - */ - keyword_redaction_tag?: string | null; - /** - * Location - * @description Google Cloud location/region (e.g., us-central1) - */ - location?: string | null; - /** - * Mask Request Content - * @description Will mask request content if guardrail makes any changes - */ - mask_request_content?: boolean | null; - /** - * Mask Response Content - * @description Will mask response content if guardrail makes any changes - */ - mask_response_content?: boolean | null; - /** - * Model - * @description Optional field if guardrail requires a 'model' parameter - */ - model?: string | null; - /** - * On Violation - * @description For /v1/realtime sessions: 'warn' speaks the violation message and continues; 'end_session' speaks the message and closes the connection. - */ - on_violation?: ("warn" | "end_session") | null; + only_scan_new_messages: boolean | null; /** * Pangea Input Recipe * @description Recipe for input (LLM request) @@ -22493,6 +23051,27 @@ export interface components { * @description The message the bot speaks aloud when a /v1/realtime guardrail fires. Falls back to violation_message_template if not set. */ realtime_violation_message?: string | null; + /** + * Run In Parallel + * @description When True, this pre_call or post_call guardrail runs concurrently with other opted-in guardrails of the same hook, after the sequential guardrails have run. Use only for block-only guardrails that inspect and reject; do not enable it for guardrails that modify the request or response (e.g. PII masking or sensitive-data routing), since parallel runs share one snapshot and their mutations would race. + */ + run_in_parallel?: boolean | null; + /** + * Sanitize Error Detail + * @description For guardrail='model_armor': omit the raw Model Armor response from caller-facing errors and logs by default. Set False to restore verbose output. + * @default true + */ + sanitize_error_detail: boolean | null; + /** + * Scan Only Tool Results + * @description When True, unified guardrails only evaluate tool results, the untrusted data an agent feeds back into the model, and skip system, user, and assistant content. Intended for agent harnesses whose own prompt scaffolding is trusted but often trips prompt-attack detectors. + */ + scan_only_tool_results?: boolean | null; + /** + * Sensitive Data Route To Model + * @description Model to route requests to when sensitive data is detected and on_sensitive_data='route'. This is typically an on-premise model for data privacy. The routing decision persists for the entire session. + */ + sensitive_data_route_to_model?: string | null; /** * Severity Threshold * @description Minimum severity to block (high, medium, low) @@ -22500,17 +23079,39 @@ export interface components { severity_threshold?: string | null; /** * Skip System Message In Guardrail - * @description When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting. + * @description When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting. For Anthropic /v1/messages, the flag applies only to the trusted top-level system prompt. In-sequence system entries are untrusted client input and remain in texts and structured_messages. */ skip_system_message_in_guardrail?: boolean | null; + /** + * Skip Tool Message In Guardrail + * @description When True, unified guardrails skip tool-role messages when building evaluation inputs (texts and structured_messages). When False, tool messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_tool_message_in_guardrail setting. + */ + skip_tool_message_in_guardrail?: boolean | null; + /** + * Skip Unscannable Attachments + * @description Implemented by guardrail='model_armor'. When True, attachment references that carry no inline bytes (file_id, gs://, or http(s) URLs) pass through unscanned instead of blocking, while fail_on_error still governs real Model Armor API errors. Default False blocks them. + * @default false + */ + skip_unscannable_attachments: boolean | null; + /** + * Sticky Session Routing + * @description When True (default), after sensitive data is detected and routed, all subsequent requests in the same session will continue routing to the same model. + * @default true + */ + sticky_session_routing: boolean | null; /** * Template Id * @description The ID of your Model Armor template */ template_id?: string | null; + /** + * Timeout + * @description Per-request timeout for the guardrail provider API call (seconds). Accepts int, float, or numeric string; coerced to float on load. Each guardrail handler chooses its own default when unset. + */ + timeout?: number | null; /** * Unreachable Fallback - * @description Behavior when a guardrail endpoint is unreachable due to network errors. NOTE: This is currently only implemented by guardrail='generic_guardrail_api'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed. + * @description Behavior when a guardrail endpoint is unreachable due to network errors. Implemented by guardrail='generic_guardrail_api', 'akto', 'vigil_guard', 'repelloai', 'headroom', and 'compresr'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed. * @default fail_closed * @enum {string} */ @@ -22525,6 +23126,56 @@ export interface components { }; /** BaseModel */ BaseModel: Record; + /** + * BedrockChecksConfigModel + * @description Inline `checks` config for the resource-less Bedrock InvokeGuardrailChecks API. + * + * Include only the checks you want to run; at least one must be set. + */ + BedrockChecksConfigModel: { + contentFilter?: components["schemas"]["BedrockChecksContentFilterModel"] | null; + promptAttack?: components["schemas"]["BedrockChecksPromptAttackModel"] | null; + sensitiveInformation?: components["schemas"]["BedrockChecksSensitiveInformationModel"] | null; + }; + /** BedrockChecksContentFilterCategoryItem */ + BedrockChecksContentFilterCategoryItem: { + /** + * Category + * @enum {string} + */ + category: "VIOLENCE" | "HATE" | "SEXUAL" | "MISCONDUCT" | "INSULTS"; + }; + /** BedrockChecksContentFilterModel */ + BedrockChecksContentFilterModel: { + /** Categories */ + categories: components["schemas"]["BedrockChecksContentFilterCategoryItem"][]; + }; + /** BedrockChecksPromptAttackCategoryItem */ + BedrockChecksPromptAttackCategoryItem: { + /** + * Category + * @enum {string} + */ + category: "JAILBREAK" | "PROMPT_INJECTION" | "PROMPT_LEAKAGE"; + }; + /** BedrockChecksPromptAttackModel */ + BedrockChecksPromptAttackModel: { + /** Categories */ + categories: components["schemas"]["BedrockChecksPromptAttackCategoryItem"][]; + }; + /** BedrockChecksSensitiveInformationEntityItem */ + BedrockChecksSensitiveInformationEntityItem: { + /** + * Type + * @enum {string} + */ + type: "ADDRESS" | "AGE" | "AWS_ACCESS_KEY" | "AWS_SECRET_KEY" | "CA_HEALTH_NUMBER" | "CA_SOCIAL_INSURANCE_NUMBER" | "CREDIT_DEBIT_CARD_CVV" | "CREDIT_DEBIT_CARD_EXPIRY" | "CREDIT_DEBIT_CARD_NUMBER" | "DRIVER_ID" | "EMAIL" | "INTERNATIONAL_BANK_ACCOUNT_NUMBER" | "IP_ADDRESS" | "LICENSE_PLATE" | "MAC_ADDRESS" | "NAME" | "PASSWORD" | "PHONE" | "PIN" | "SWIFT_CODE" | "UK_NATIONAL_HEALTH_SERVICE_NUMBER" | "UK_NATIONAL_INSURANCE_NUMBER" | "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER" | "URL" | "USERNAME" | "US_BANK_ACCOUNT_NUMBER" | "US_BANK_ROUTING_NUMBER" | "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER" | "US_PASSPORT_NUMBER" | "US_SOCIAL_SECURITY_NUMBER" | "VEHICLE_IDENTIFICATION_NUMBER"; + }; + /** BedrockChecksSensitiveInformationModel */ + BedrockChecksSensitiveInformationModel: { + /** Entities */ + entities: components["schemas"]["BedrockChecksSensitiveInformationEntityItem"][]; + }; /** BlockKeyRequest */ BlockKeyRequest: { /** Key */ @@ -22604,12 +23255,20 @@ export interface components { /** File */ file: string; }; + /** Body_authorize_complete_authorize_complete_post */ + Body_authorize_complete_authorize_complete_post: { + /** Decision */ + decision?: string | null; + /** Delivery */ + delivery?: string | null; + /** Flow */ + flow: string; + /** Team Id */ + team_id?: string | null; + }; /** Body_convert_prompt_file_to_json_utils_dotprompt_json_converter_post */ Body_convert_prompt_file_to_json_utils_dotprompt_json_converter_post: { - /** - * File - * Format: binary - */ + /** File */ file: string; }; /** Body_create_file__provider__v1_files_post */ @@ -22717,6 +23376,13 @@ export interface components { /** Mask[] */ "mask[]"?: string[] | null; }; + /** Body_revoke_endpoint_revoke_post */ + Body_revoke_endpoint_revoke_post: { + /** Client Id */ + client_id: string; + /** Token */ + token: string; + }; /** Body_test_model_connection_health_test_connection_post */ Body_test_model_connection_health_test_connection_post: { /** @@ -22739,6 +23405,48 @@ export interface components { [key: string]: unknown; }; }; + /** Body_token_endpoint__mcp_server_name__token_post */ + Body_token_endpoint__mcp_server_name__token_post: { + /** Client Id */ + client_id: string; + /** Client Secret */ + client_secret?: string | null; + /** Code */ + code?: string; + /** Code Verifier */ + code_verifier?: string; + /** Grant Type */ + grant_type: string; + /** Redirect Uri */ + redirect_uri?: string; + /** Refresh Token */ + refresh_token?: string | null; + /** Resource */ + resource?: string | null; + /** Scope */ + scope?: string | null; + }; + /** Body_token_endpoint_token_post */ + Body_token_endpoint_token_post: { + /** Client Id */ + client_id: string; + /** Client Secret */ + client_secret?: string | null; + /** Code */ + code?: string; + /** Code Verifier */ + code_verifier?: string; + /** Grant Type */ + grant_type: string; + /** Redirect Uri */ + redirect_uri?: string; + /** Refresh Token */ + refresh_token?: string | null; + /** Resource */ + resource?: string | null; + /** Scope */ + scope?: string | null; + }; /** Body_upload_logo_upload_logo_post */ Body_upload_logo_upload_logo_post: { /** File */ @@ -23656,6 +24364,8 @@ export interface components { }; /** ChatCompletionToolParam */ ChatCompletionToolParam: { + /** Allowed Callers */ + allowed_callers?: string[]; cache_control?: components["schemas"]["ChatCompletionCachedContent"]; function: components["schemas"]["ChatCompletionToolParamFunctionChunk"]; /** Type */ @@ -23738,6 +24448,86 @@ export interface components { } & { [key: string]: unknown; }; + /** + * CiscoAIDefenseGuardrailConfigModelOptionalParams + * @description Optional parameters for the Cisco AI Defense guardrail. + */ + CiscoAIDefenseGuardrailConfigModelOptionalParams: { + /** + * Enabled Rules + * @description Explicit list of Cisco AI Defense rules to evaluate. If omitted, the policies configured for the API key in the Cisco AI Defense UI are used. + */ + enabled_rules?: components["schemas"]["CiscoAIDefenseRule"][] | null; + /** + * Fallback On Error + * @description Behaviour when the Cisco AI Defense API is unavailable: 'allow' proceeds without scanning (high availability), 'block' rejects the request (maximum security). + * @default block + */ + fallback_on_error: ("allow" | "block") | null; + /** + * Inspect Path + * @description Override for the inspection endpoint path. Defaults to /api/v1/inspect/chat when inspection_type='chat' and /api/v1/inspect/mcp when inspection_type='mcp'. + */ + inspect_path?: string | null; + /** + * Inspection Type + * @description Which Cisco AI Defense inspection surface to use. 'chat' scans LLM model conversations via /api/v1/inspect/chat. 'mcp' scans MCP tool calls via /api/v1/inspect/mcp. Each guardrail instance targets exactly one surface; configure two guardrails to scan both chat and MCP traffic. + * @default chat + * @enum {string} + */ + inspection_type: "chat" | "mcp"; + /** + * Integration Profile Id + * @description Integration profile id to apply (advanced). + */ + integration_profile_id?: string | null; + /** + * Integration Profile Version + * @description Integration profile version to apply (advanced). + */ + integration_profile_version?: string | null; + /** + * Integration Tenant Id + * @description Integration tenant id to apply (advanced). + */ + integration_tenant_id?: string | null; + /** + * Integration Type + * @description Integration type to apply (advanced). + */ + integration_type?: string | null; + /** + * On Flagged Action + * @description Action to take when Cisco AI Defense flags content. 'block' raises an HTTPException; 'monitor' logs the detection and lets the request continue. + * @default block + */ + on_flagged_action: string | null; + /** + * Timeout + * @description Timeout (seconds) for Cisco AI Defense API calls (1-60). + * @default 10 + */ + timeout: number | null; + } & { + [key: string]: unknown; + }; + /** + * CiscoAIDefenseRule + * @description A single rule to enable for Cisco AI Defense inspection. + */ + CiscoAIDefenseRule: { + /** + * Entity Types + * @description Optional list of entity types for the rule (e.g. 'Email Address', 'Phone Number'). Applies to rules such as PII, PCI, and PHI. + */ + entity_types?: string[] | null; + /** + * Rule Name + * @description The canonical Cisco AI Defense rule name to evaluate. + * @enum {string} + */ + rule_name: "Code Detection" | "Harassment" | "Hate Speech" | "PCI" | "PHI" | "PII" | "Prompt Injection" | "Profanity" | "Sexual Content & Exploitation" | "Social Division & Polarization" | "Violence & Public Safety Threats"; + }; /** CitationsObject */ CitationsObject: { /** Enabled */ @@ -24088,6 +24878,11 @@ export interface components { * @description If True, a user's personal max_budget is enforced on every request they make, including requests made with a team-scoped key. Defaults to False, where a team-scoped key is governed only by the team and team-member budgets and the key owner's personal max_budget does not apply (see GitHub issue #12905). */ apply_user_budget_to_team_keys?: boolean | null; + /** + * Background Health Check Model Groups + * @description Opt-in allowlist of model group names for background health checks and health-check routing. When set, the background loop probes only deployments whose model_name is listed, and enable_health_check_routing filters unhealthy deployments only within the listed groups; every other group, including newly added deployments, is skipped and keeps its configured routing strategy. When unset, all deployments participate (opt out per deployment via model_info.disable_background_health_check). + */ + background_health_check_model_groups?: string[] | null; /** * Background Health Checks * @description run health checks in background @@ -25177,6 +25972,43 @@ export interface components { } & { [key: string]: unknown; }; + /** DiscoverAgentRequest */ + DiscoverAgentRequest: { + /** + * @description How to locate the upstream card. ``well_known_fallback`` for pure A2A agents (try standard paths); ``langgraph_platform`` for LangGraph Platform deployments where the card is shared across assistants and disambiguated by a query parameter. + * @default well_known_fallback + */ + discovery_mode: components["schemas"]["DiscoveryMode"]; + /** + * Params + * @description Mode-specific parameters. ``langgraph_platform`` requires ``{'assistant_id': }``. ``well_known_fallback`` ignores this. + */ + params?: { + [key: string]: unknown; + } | null; + /** + * Url + * @description Base URL of the upstream agent. Behavior depends on ``discovery_mode``: ``well_known_fallback`` (default) tries /.well-known/agent-card.json, /.well-known/agent.json, /agent.json under this URL in order; ``langgraph_platform`` hits ``/.well-known/agent-card.json?assistant_id=`` instead. + */ + url: string; + }; + /** DiscoverAgentResponse */ + DiscoverAgentResponse: { + /** Agent Card */ + agent_card: { + [key: string]: unknown; + }; + /** Url */ + url: string; + }; + /** + * DiscoveryMode + * @description How to locate the upstream agent card. + * + * String-valued so it serializes cleanly over JSON / Pydantic. + * @enum {string} + */ + DiscoveryMode: "well_known_fallback" | "langgraph_platform"; /** * DistinctTagResponse * @description Response for distinct user agent tags @@ -25961,6 +26793,8 @@ export interface components { images?: string[]; /** Model */ model?: string | null; + /** Stream Holdback Chars */ + stream_holdback_chars?: number[]; /** Structured Messages */ structured_messages?: (components["schemas"]["ChatCompletionUserMessage"] | components["schemas"]["ChatCompletionAssistantMessage"] | components["schemas"]["ChatCompletionToolMessage"] | components["schemas"]["ChatCompletionSystemMessage"] | components["schemas"]["ChatCompletionFunctionMessage"] | components["schemas"]["ChatCompletionDeveloperMessage"])[]; /** Texts */ @@ -25994,53 +26828,6 @@ export interface components { /** Starttime */ startTime?: string | null; }; - /** - * GraySwanGuardrailConfigModelOptionalParams - * @description Optional parameters for the Gray Swan guardrail. - */ - GraySwanGuardrailConfigModelOptionalParams: { - /** - * Categories - * @description Default Gray Swan category definitions to send with each request. - */ - categories?: { - [key: string]: string; - } | null; - /** - * Fail Open - * @description If true (default), errors contacting Gray Swan are logged and the request proceeds. If false, errors propagate and block the request. - * @default true - */ - fail_open: boolean | null; - /** - * Guardrail Timeout - * @description Timeout in seconds for calling the Gray Swan guardrail service. - * @default 30 - */ - guardrail_timeout: number | null; - /** - * On Flagged Action - * @description Action when a violation is detected: 'block' rejects the call (400 error), 'monitor' logs only, 'passthrough' replaces response content with violation message (200 status). - * @default passthrough - */ - on_flagged_action: string | null; - /** - * Policy Id - * @description Gray Swan policy identifier to apply during monitoring. - */ - policy_id?: string | null; - /** - * Reasoning Mode - * @description Gray Swan reasoning mode override. Accepted values: 'off', 'hybrid', 'thinking'. - */ - reasoning_mode?: string | null; - /** - * Violation Threshold - * @description Threshold between 0 and 1 at which Gray Swan violations trigger the configured action. - * @default 0.5 - */ - violation_threshold: number | null; - }; /** Guardrail */ Guardrail: { /** Created At */ @@ -26073,7 +26860,7 @@ export interface components { } | null; /** Guardrail Name */ guardrail_name: string; - litellm_params?: components["schemas"]["BaseLitellmParams-Output"] | null; + litellm_params?: components["schemas"]["BaseLitellmParams"] | null; /** Updated At */ updated_at?: string | null; }; @@ -26273,6 +27060,17 @@ export interface components { index_name: string; litellm_params: components["schemas"]["IndexCreateLiteLLMParams"]; }; + /** IndexListResponse */ + IndexListResponse: { + /** Data */ + data: components["schemas"]["LiteLLM_ManagedVectorStoreIndex"][]; + /** + * Object + * @default list + * @constant + */ + object: "list"; + }; /** InputAudio */ InputAudio: { /** Data */ @@ -27060,8 +27858,10 @@ export interface components { approval_status: string | null; /** Args */ args?: string[]; + /** Audience */ + audience?: string | null; /** Auth Type */ - auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token") | null; + auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token" | "oauth2_token_exchange" | "oauth2_id_jag" | "true_passthrough" | "oauth_delegate") | null; /** Authorization Url */ authorization_url?: string | null; /** @@ -27075,17 +27875,28 @@ export interface components { byok_description?: string[]; /** Command */ command?: string | null; + /** Connected App Reachable */ + connected_app_reachable?: boolean | null; /** Created At */ created_at?: string | null; /** Created By */ created_by?: string | null; credentials?: components["schemas"]["MCPCredentials"] | null; + /** Dcr Bridge */ + dcr_bridge?: boolean | null; + /** + * Delegate Auth To Upstream + * @default false + */ + delegate_auth_to_upstream: boolean; /** Description */ description?: string | null; /** Env */ env?: { [key: string]: string; }; + /** Env Vars */ + env_vars?: components["schemas"]["MCPEnvVar"][] | null; /** Extra Headers */ extra_headers?: string[]; /** Has User Credential */ @@ -27099,14 +27910,25 @@ export interface components { * @default false */ is_byok: boolean; + /** Issuer */ + issuer?: string | null; /** Last Health Check */ last_health_check?: string | null; + /** Max Concurrent Requests */ + max_concurrent_requests?: number | null; /** Mcp Access Groups */ mcp_access_groups?: string[]; /** Mcp Info */ mcp_info?: { [key: string]: unknown; } | null; + /** Oauth2 Flow */ + oauth2_flow?: ("client_credentials" | "authorization_code") | null; + /** + * Oauth Passthrough + * @default false + */ + oauth_passthrough: boolean; /** Registration Url */ registration_url?: string | null; /** Review Notes */ @@ -27131,6 +27953,8 @@ export interface components { * @default unknown */ status: ("healthy" | "unhealthy" | "unknown") | null; + /** Subject Token Type */ + subject_token_type?: string | null; /** Submitted At */ submitted_at?: string | null; /** Submitted By */ @@ -27139,6 +27963,12 @@ export interface components { teams?: { [key: string]: string | null; }[]; + /** Timeout */ + timeout?: number | null; + /** Token Exchange Endpoint */ + token_exchange_endpoint?: string | null; + /** Token Exchange Profile */ + token_exchange_profile?: string | null; /** Token Url */ token_url?: string | null; /** Tool Name To Description */ @@ -27193,6 +28023,29 @@ export interface components { /** Vector Store Name */ vector_store_name?: string | null; }; + /** + * LiteLLM_ManagedVectorStoreIndex + * @description LiteLLM managed vector store index object - this is is the object stored in the database + */ + LiteLLM_ManagedVectorStoreIndex: { + /** Created At */ + created_at?: string | null; + /** Created By */ + created_by?: string | null; + /** Id */ + id: string; + /** Index Info */ + index_info?: { + [key: string]: unknown; + } | null; + /** Index Name */ + index_name: string; + litellm_params: components["schemas"]["IndexCreateLiteLLMParams"]; + /** Updated At */ + updated_at?: string | null; + /** Updated By */ + updated_by?: string | null; + }; /** * LiteLLM_ManagedVectorStoreListResponse * @description Response format for listing vector stores @@ -27215,31 +28068,31 @@ export interface components { /** LiteLLM_ManagedVectorStoresTable */ LiteLLM_ManagedVectorStoresTable: { /** Created At */ - created_at: string | null; + created_at?: string | null; /** Custom Llm Provider */ custom_llm_provider: string; /** Litellm Credential Name */ - litellm_credential_name: string | null; + litellm_credential_name?: string | null; /** Litellm Params */ - litellm_params: { + litellm_params?: { [key: string]: unknown; } | null; /** Team Id */ - team_id: string | null; + team_id?: string | null; /** Updated At */ - updated_at: string | null; + updated_at?: string | null; /** User Id */ - user_id: string | null; + user_id?: string | null; /** Vector Store Description */ - vector_store_description: string | null; + vector_store_description?: string | null; /** Vector Store Id */ vector_store_id: string; /** Vector Store Metadata */ - vector_store_metadata: { + vector_store_metadata?: { [key: string]: unknown; } | null; /** Vector Store Name */ - vector_store_name: string | null; + vector_store_name?: string | null; }; /** LiteLLM_MemoryRow */ LiteLLM_MemoryRow: { @@ -28536,7 +29389,7 @@ export interface components { anonymize_input?: boolean | null; /** * Api Base - * @description Base URL for the Lakera AI API + * @description Regional base URL for the Cisco AI Defense Inspection API. Defaults to https://us.api.inspect.aidefense.security.cisco.com. Supported regions: us (us-west-2), ap (ap-ne-1), eu (eu-central-1). The environment variable `CISCO_AI_DEFENSE_API_BASE` is consulted as a fallback. The endpoint path is derived from inspection_type (/api/v1/inspect/chat for 'chat', /api/v1/inspect/mcp for 'mcp'). */ api_base?: string | null; /** @@ -28551,7 +29404,7 @@ export interface components { api_id?: string | null; /** * Api Key - * @description API key for the Lakera AI service + * @description API key for the Cisco AI Defense inspection endpoint. If not provided, the `CISCO_AI_DEFENSE_API_KEY` environment variable is used. Sent in the `X-Cisco-AI-Defense-API-Key` header. Both the chat and MCP endpoints use this key. */ api_key?: string | null; /** @@ -28575,6 +29428,11 @@ export interface components { * @description Custom assertions to validate against the output. Each assertion is a string describing a condition. */ assertions?: string[] | null; + /** + * Asset Id + * @description Repello asset ID whose dashboard policies are enforced. Required; the guardrail raises at init if it is missing. + */ + asset_id?: string | null; /** * Async Mode * @description Set to True to request asynchronous analysis (sets `plr_async` header). Defaults to provider behaviour when omitted. @@ -28684,6 +29542,14 @@ export interface components { categories?: components["schemas"]["ContentFilterCategoryConfig"][] | null; /** @description Threshold configuration for Lakera guardrail categories */ category_thresholds?: components["schemas"]["LakeraCategoryThresholds"] | null; + /** @description Inline safeguards for the resource-less InvokeGuardrailChecks API (contentFilter / promptAttack / sensitiveInformation). When set, the guardrail calls InvokeGuardrailChecks instead of ApplyGuardrail and no guardrailIdentifier is required. Mutually exclusive with guardrailIdentifier. */ + checks?: components["schemas"]["BedrockChecksConfigModel"] | null; + /** + * Chunk Budget Chars + * @description ApplyGuardrail: batch size, in characters, used to re-send content after AWS has rejected a request as too large. Requests AWS accepts are always sent in a single call, so this has no effect until a rejection happens. Defaults to 25,000; a batch AWS still rejects is bisected automatically, so this value only trades round trips against batch size and cannot fail a request on its own. + * @default 25000 + */ + chunk_budget_chars: number; /** * Confidence Threshold * @description Only block or mask when detection confidence >= this value; below threshold, allow or log_only. @@ -28697,6 +29563,12 @@ export interface components { config?: { [key: string]: unknown; } | null; + /** + * Content Filter Threshold + * @description InvokeGuardrailChecks: block when any contentFilter severityScore >= this value (scores are in [0,1]). Set to null to make the content filter detect-only (logged, never blocks). + * @default 0.5 + */ + content_filter_threshold: number | null; /** * Content Moderation Check * @description Enable content moderation to check for harmful content (harassment, hate speech, etc.). @@ -28712,6 +29584,11 @@ export interface components { * @description Python-like code containing the apply_guardrail function for custom guardrail logic */ custom_code?: string | null; + /** + * Deepkeep Firewall Id + * @description The DeepKeep Firewall ID to use for guardrail evaluation. If not provided, the `DEEPKEEP_FIREWALL_ID` environment variable is checked. + */ + deepkeep_firewall_id?: string | null; /** * Default Action * @description Fallback decision when no rule matches @@ -28789,7 +29666,7 @@ export interface components { extra_headers?: string[] | null; /** * Fail On Error - * @description Whether to fail the request if Model Armor encounters an error + * @description Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it. * @default true */ fail_on_error: boolean | null; @@ -28908,7 +29785,7 @@ export interface components { mode: string | string[] | components["schemas"]["Mode"]; /** * Model - * @description Optional field if guardrail requires a 'model' parameter + * @description Model name forwarded to the headroom /v1/compress endpoint. */ model?: string | null; /** @@ -28935,13 +29812,24 @@ export interface components { * @default monitor */ on_flagged_action: string | null; + /** + * On Sensitive Data + * @description Action to take when sensitive data is detected. 'block' raises an exception (default behavior). 'route' reroutes the request to the model specified in sensitive_data_route_to_model. + */ + on_sensitive_data?: ("block" | "route") | null; /** * On Violation * @description For /v1/realtime sessions: 'warn' speaks the violation message and continues; 'end_session' speaks the message and closes the connection. */ on_violation?: ("warn" | "end_session") | null; + /** + * Only Scan New Messages + * @description When True, the guardrail only scans messages that have not already been scanned earlier in the same session (identified by litellm_session_id / session_id). Message content is hashed per session and cached; only the diff (new or edited messages) is sent to the guardrail provider on follow-up calls. Falls back to a full scan when the request has no session id or the cache is unavailable. Intended for blocking/detection guardrails; not applied when mask_request_content is set. + * @default false + */ + only_scan_new_messages: boolean | null; /** @description Optional parameters for the guardrail */ - optional_params?: components["schemas"]["GraySwanGuardrailConfigModelOptionalParams"] | null; + optional_params?: components["schemas"]["CiscoAIDefenseGuardrailConfigModelOptionalParams"] | null; /** * Output Parse Pii * @description When True, LiteLLM will replace the masked text with the original text in the response @@ -28983,6 +29871,12 @@ export interface components { * @description Enable PII (Personally Identifiable Information) detection. */ pii_check?: boolean | null; + /** + * Pii Confidence Threshold + * @description InvokeGuardrailChecks: block when any sensitiveInformation confidenceScore >= this value (scores are in [0,1]). Set to null to make PII detection detect-only. + * @default 0.5 + */ + pii_confidence_threshold: number | null; /** * Pii Entities Config * @description Configuration for PII entity types and actions @@ -29005,6 +29899,16 @@ export interface components { * @description XecGuard policies to apply on each scan. Select one or more of the built-in default policies; if none are selected, the guardrail defaults to System Prompt Enforcement + Harmful Content Protection. */ policy_names?: string[] | null; + /** + * Post Checkpoint Id + * @description Post-checkpoint ID for the Ovalix Tracker service. + */ + post_checkpoint_id?: string | null; + /** + * Pre Checkpoint Id + * @description Pre-checkpoint ID for the Ovalix Tracker service. + */ + pre_checkpoint_id?: string | null; /** * Presidio Ad Hoc Recognizers * @description Path to a JSON file containing ad-hoc recognizers for Presidio @@ -29053,6 +29957,12 @@ export interface components { * @description Project ID for the Lakera AI project */ project_id?: string | null; + /** + * Prompt Attack Threshold + * @description InvokeGuardrailChecks: block when any promptAttack severityScore >= this value (scores are in [0,1]). Set to null to make prompt-attack detection detect-only. + * @default 0.5 + */ + prompt_attack_threshold: number | null; /** * Prompt Injections * @description Enable prompt injection detection. Default check if no evaluation_id and no other checks are specified. @@ -29068,6 +29978,22 @@ export interface components { * @description Ordered allow/deny rules. Patterns use regex for tool names/types and optional regex constraints on tool arguments. */ rules?: components["schemas"]["ToolPermissionRule"][] | null; + /** + * Run In Parallel + * @description When True, this pre_call or post_call guardrail runs concurrently with other opted-in guardrails of the same hook, after the sequential guardrails have run. Use only for block-only guardrails that inspect and reject; do not enable it for guardrails that modify the request or response (e.g. PII masking or sensitive-data routing), since parallel runs share one snapshot and their mutations would race. + */ + run_in_parallel?: boolean | null; + /** + * Sanitize Error Detail + * @description For guardrail='model_armor': omit the raw Model Armor response from caller-facing errors and logs by default. Set False to restore verbose output. + * @default true + */ + sanitize_error_detail: boolean | null; + /** + * Scan Only Tool Results + * @description When True, unified guardrails only evaluate tool results, the untrusted data an agent feeds back into the model, and skip system, user, and assistant content. Intended for agent harnesses whose own prompt scaffolding is trusted but often trips prompt-attack detectors. + */ + scan_only_tool_results?: boolean | null; /** * Send User Api Key Alias * @description Whether to send user_API_key_alias in headers @@ -29086,29 +30012,86 @@ export interface components { * @default false */ send_user_api_key_user_id: boolean | null; + /** + * Sensitive Data Route To Model + * @description Model to route requests to when sensitive data is detected and on_sensitive_data='route'. This is typically an on-premise model for data privacy. The routing decision persists for the entire session. + */ + sensitive_data_route_to_model?: string | null; /** * Severity Threshold * @description Minimum severity to block (high, medium, low) */ severity_threshold?: string | null; + /** + * Singulr Api Base + * @description The Singulr API base URL. Get base URL from Singulr Platform. + */ + singulr_api_base?: string | null; + /** + * Singulr Api Key + * @description The Singulr API key. Generate API key from Singulr Platform. + */ + singulr_api_key?: string | null; + /** + * Singulr Application Id + * @description The Singulr application ID. Get application ID from Singulr Platform. + */ + singulr_application_id?: string | null; + /** + * Singulr Guardrail Id + * @description The Singulr Guardrail ID. Get guardrail ID from Singulr Platform. + */ + singulr_guardrail_id?: string | null; /** * Skip System Message In Guardrail - * @description When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting. + * @description When True, unified guardrails skip system-role messages when building evaluation inputs (texts and structured_messages). When False, system messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_system_message_in_guardrail setting. For Anthropic /v1/messages, the flag applies only to the trusted top-level system prompt. In-sequence system entries are untrusted client input and remain in texts and structured_messages. */ skip_system_message_in_guardrail?: boolean | null; + /** + * Skip Tool Message In Guardrail + * @description When True, unified guardrails skip tool-role messages when building evaluation inputs (texts and structured_messages). When False, tool messages are included even if litellm_settings sets a global skip. When None, use the global litellm.skip_tool_message_in_guardrail setting. + */ + skip_tool_message_in_guardrail?: boolean | null; + /** + * Skip Unscannable Attachments + * @description Implemented by guardrail='model_armor'. When True, attachment references that carry no inline bytes (file_id, gs://, or http(s) URLs) pass through unscanned instead of blocking, while fail_on_error still governs real Model Armor API errors. Default False blocks them. + * @default false + */ + skip_unscannable_attachments: boolean | null; + /** + * Sticky Session Routing + * @description When True (default), after sensitive data is detected and routed, all subsequent requests in the same session will continue routing to the same model. + * @default true + */ + sticky_session_routing: boolean | null; /** * Template Id * @description The ID of your Model Armor template */ template_id?: string | null; + /** + * Timeout + * @description Per-request timeout for the guardrail provider API call (seconds). Accepts int, float, or numeric string; coerced to float on load. Each guardrail handler chooses its own default when unset. + */ + timeout?: number | null; /** * Tool Selection Quality Check * @description Enable tool selection quality check to evaluate quality of tool/function calls. */ tool_selection_quality_check?: boolean | null; + /** + * Tracker Api Base + * @description Base URL for the Ovalix Tracker service. + */ + tracker_api_base?: string | null; + /** + * Tracker Api Key + * @description API key for the Ovalix Tracker service. + */ + tracker_api_key?: string | null; /** * Unreachable Fallback - * @description What to do when Akto is unreachable. 'fail_open' = allow, 'fail_closed' = block. + * @description Behavior when the headroom compression service is unreachable or errors. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and forwards the request uncompressed instead of blocking it. * @default fail_closed * @enum {string} */ @@ -29179,6 +30162,8 @@ export interface components { }; /** MCPCredentials */ MCPCredentials: { + /** Audience */ + audience?: string | null; /** Auth Value */ auth_value?: string | null; /** Aws Access Key Id */ @@ -29195,13 +30180,70 @@ export interface components { aws_session_name?: string | null; /** Aws Session Token */ aws_session_token?: string | null; + /** Client Assertion Signing Alg */ + client_assertion_signing_alg?: string | null; /** Client Id */ client_id?: string | null; + /** Client Private Key */ + client_private_key?: string | null; + /** Client Private Key Id */ + client_private_key_id?: string | null; /** Client Secret */ client_secret?: string | null; + /** Id Jag Resource */ + id_jag_resource?: string | null; + /** Id Jag Resource Token Endpoint */ + id_jag_resource_token_endpoint?: string | null; + /** Redirect Uris */ + redirect_uris?: string[] | null; /** Scopes */ scopes?: string[] | null; + /** Subject Token Type */ + subject_token_type?: string | null; + /** Token Endpoint Auth Method */ + token_endpoint_auth_method?: ("client_secret_basic" | "client_secret_post") | null; + /** Token Exchange Endpoint */ + token_exchange_endpoint?: string | null; + /** Token Exchange Profile */ + token_exchange_profile?: string | null; + /** Upstream Resource */ + upstream_resource?: string | null; + /** Upstream Token Header */ + upstream_token_header?: string | null; }; + /** + * MCPEnvVar + * @description One environment variable for an MCP server. + * + * Variables can be interpolated into ``static_headers`` using ``${NAME}`` + * syntax. ``scope=global`` values are stored on the server. ``scope=user`` + * values are stored per-user in ``LiteLLM_MCPUserEnvVars`` and supplied by + * each user. + */ + MCPEnvVar: { + /** Description */ + description?: string | null; + /** Name */ + name: string; + /** @default global */ + scope: components["schemas"]["MCPEnvVarScope"]; + /** + * Value + * @default + */ + value: string; + }; + /** + * MCPEnvVarScope + * @description Scope for an MCP server environment variable. + * + * - ``global``: value is provided by the admin and used for all users. + * - ``user``: each user must provide their own value via the per-user + * env-var endpoint. The admin-supplied ``value`` is treated as a + * placeholder/hint and is not used at request time. + * @enum {string} + */ + MCPEnvVarScope: "global" | "user"; /** * MCPOAuthUserCredentialRequest * @description Stores a user's OAuth2 token for an OpenAPI MCP server. @@ -29363,6 +30405,55 @@ export interface components { /** Server Id */ server_id: string; }; + /** + * MCPUserEnvVarSpec + * @description Describes one per-user env var slot for the calling user. + * + * Stored values are write-only: the status only reports whether a value + * ``is_set`` and never echoes the decrypted secret back to the client. + */ + MCPUserEnvVarSpec: { + /** Description */ + description?: string | null; + /** + * Is Set + * @default false + */ + is_set: boolean; + /** Name */ + name: string; + }; + /** + * MCPUserEnvVarsRequest + * @description Payload for storing the calling user's per-user env var values. + */ + MCPUserEnvVarsRequest: { + /** Values */ + values: { + [key: string]: string; + }; + }; + /** + * MCPUserEnvVarsStatus + * @description Per-user env var status for a single MCP server. + */ + MCPUserEnvVarsStatus: { + /** Alias */ + alias?: string | null; + /** + * Missing Count + * @default 0 + */ + missing_count: number; + /** Required */ + required?: components["schemas"]["MCPUserEnvVarSpec"][]; + /** Server Id */ + server_id: string; + /** Server Name */ + server_name?: string | null; + /** Setup Url */ + setup_url?: string | null; + }; /** MakeAgentsPublicRequest */ MakeAgentsPublicRequest: { /** Agent Ids */ @@ -29775,8 +30866,10 @@ export interface components { approval_status?: string | null; /** Args */ args?: string[]; + /** Audience */ + audience?: string | null; /** Auth Type */ - auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token") | null; + auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token" | "oauth2_token_exchange" | "oauth2_id_jag" | "true_passthrough" | "oauth_delegate") | null; /** Authorization Url */ authorization_url?: string | null; /** @@ -29791,12 +30884,21 @@ export interface components { /** Command */ command?: string | null; credentials?: components["schemas"]["MCPCredentials"] | null; + /** Dcr Bridge */ + dcr_bridge?: boolean | null; + /** + * Delegate Auth To Upstream + * @default false + */ + delegate_auth_to_upstream: boolean; /** Description */ description?: string | null; /** Env */ env?: { [key: string]: string; }; + /** Env Vars */ + env_vars?: components["schemas"]["MCPEnvVar"][] | null; /** Extra Headers */ extra_headers?: string[] | null; /** Instructions */ @@ -29806,6 +30908,10 @@ export interface components { * @default false */ is_byok: boolean; + /** Issuer */ + issuer?: string | null; + /** Max Concurrent Requests */ + max_concurrent_requests?: number | null; /** Mcp Access Groups */ mcp_access_groups?: string[]; /** Mcp Info */ @@ -29814,6 +30920,11 @@ export interface components { } | null; /** Oauth2 Flow */ oauth2_flow?: ("client_credentials" | "authorization_code") | null; + /** + * Oauth Passthrough + * @default false + */ + oauth_passthrough: boolean; /** Registration Url */ registration_url?: string | null; /** Server Id */ @@ -29828,6 +30939,8 @@ export interface components { static_headers?: { [key: string]: string; } | null; + /** Subject Token Type */ + subject_token_type?: string | null; /** * Submitted At * @description Server-managed: set by the endpoint; caller values are overridden. @@ -29838,6 +30951,12 @@ export interface components { * @description Server-managed: set by the endpoint; caller values are overridden. */ submitted_by?: string | null; + /** Timeout */ + timeout?: number | null; + /** Token Exchange Endpoint */ + token_exchange_endpoint?: string | null; + /** Token Exchange Profile */ + token_exchange_profile?: string | null; /** Token Url */ token_url?: string | null; /** Tool Name To Description */ @@ -30881,7 +32000,7 @@ export interface components { } | null; /** Guardrail Name */ guardrail_name?: string | null; - litellm_params?: components["schemas"]["BaseLitellmParams-Input"] | null; + litellm_params?: components["schemas"]["BaseLitellmParams"] | null; }; /** PatchPromptRequest */ PatchPromptRequest: { @@ -31063,7 +32182,7 @@ export interface components { * PiiEntityType * @enum {string} */ - PiiEntityType: "CREDIT_CARD" | "CRYPTO" | "DATE_TIME" | "EMAIL_ADDRESS" | "IBAN_CODE" | "IP_ADDRESS" | "NRP" | "LOCATION" | "PERSON" | "PHONE_NUMBER" | "MEDICAL_LICENSE" | "URL" | "US_BANK_NUMBER" | "US_DRIVER_LICENSE" | "US_ITIN" | "US_PASSPORT" | "US_SSN" | "UK_NHS" | "UK_NINO" | "ES_NIF" | "ES_NIE" | "IT_FISCAL_CODE" | "IT_DRIVER_LICENSE" | "IT_VAT_CODE" | "IT_PASSPORT" | "IT_IDENTITY_CARD" | "PL_PESEL" | "SG_NRIC_FIN" | "SG_UEN" | "AU_ABN" | "AU_ACN" | "AU_TFN" | "AU_MEDICARE" | "IN_PAN" | "IN_AADHAAR" | "IN_VEHICLE_REGISTRATION" | "IN_VOTER" | "IN_PASSPORT" | "FI_PERSONAL_IDENTITY_CODE"; + PiiEntityType: "CREDIT_CARD" | "CRYPTO" | "DATE_TIME" | "EMAIL_ADDRESS" | "IBAN_CODE" | "IP_ADDRESS" | "NRP" | "LOCATION" | "PERSON" | "PHONE_NUMBER" | "MEDICAL_LICENSE" | "URL" | "US_BANK_NUMBER" | "US_DRIVER_LICENSE" | "US_ITIN" | "US_PASSPORT" | "US_SSN" | "UK_NHS" | "UK_NINO" | "UK_PASSPORT" | "UK_POSTCODE" | "UK_VEHICLE_REGISTRATION" | "ES_NIF" | "ES_NIE" | "IT_FISCAL_CODE" | "IT_DRIVER_LICENSE" | "IT_VAT_CODE" | "IT_PASSPORT" | "IT_IDENTITY_CARD" | "PL_PESEL" | "SG_NRIC_FIN" | "SG_UEN" | "AU_ABN" | "AU_ACN" | "AU_TFN" | "AU_MEDICARE" | "IN_PAN" | "IN_AADHAAR" | "IN_VEHICLE_REGISTRATION" | "IN_VOTER" | "IN_PASSPORT" | "FI_PERSONAL_IDENTITY_CODE"; /** * PipelineTestRequest * @description Request body for testing a guardrail pipeline with sample messages. @@ -32224,6 +33343,21 @@ export interface components { /** Value */ value: string; }; + /** + * RealtimeTranscriptionSessionResponse + * @description Response from POST /v1/realtime/transcription_sessions. + * + * `client_secret.value` contains the encrypted token instead of the raw + * ephemeral key. Unknown fields pass through unchanged. + */ + RealtimeTranscriptionSessionResponse: { + /** Client Secret */ + client_secret?: { + [key: string]: unknown; + } | null; + } & { + [key: string]: unknown; + }; /** RegenerateKeyRequest */ RegenerateKeyRequest: { /** Access Group Ids */ @@ -32994,6 +34128,20 @@ export interface components { /** Run Id */ run_id: string; }; + /** SCIMEnterpriseUser */ + SCIMEnterpriseUser: { + /** Costcenter */ + costCenter?: string | null; + /** Department */ + department?: string | null; + /** Division */ + division?: string | null; + /** Employeenumber */ + employeeNumber?: string | null; + manager?: components["schemas"]["SCIMUserManager"] | null; + /** Organization */ + organization?: string | null; + }; /** SCIMFeature */ SCIMFeature: { /** Maxoperations */ @@ -33025,7 +34173,7 @@ export interface components { /** SCIMListResponse */ SCIMListResponse: { /** Resources */ - Resources: components["schemas"]["SCIMUser"][] | components["schemas"]["SCIMGroup"][]; + Resources: components["schemas"]["SCIMUser-Output"][] | components["schemas"]["SCIMGroup"][]; /** * Itemsperpage * @default 10 @@ -33050,6 +34198,19 @@ export interface components { SCIMMember: { /** Display */ display?: string | null; + /** Type */ + type?: string | null; + /** Value */ + value: string; + }; + /** SCIMMultiValuedAttribute */ + SCIMMultiValuedAttribute: { + /** Display */ + display?: string | null; + /** Primary */ + primary?: boolean | null; + /** Type */ + type?: string | null; /** Value */ value: string; }; @@ -33129,7 +34290,7 @@ export interface components { sort: components["schemas"]["SCIMFeature"]; }; /** SCIMUser */ - SCIMUser: { + "SCIMUser-Input": { /** * Active * @default true @@ -33139,6 +34300,8 @@ export interface components { displayName?: string | null; /** Emails */ emails?: components["schemas"]["SCIMUserEmail"][] | null; + /** Entitlements */ + entitlements?: components["schemas"]["SCIMMultiValuedAttribute"][] | null; /** Externalid */ externalId?: string | null; /** Groups */ @@ -33150,11 +34313,17 @@ export interface components { [key: string]: unknown; } | null; name?: components["schemas"]["SCIMUserName"] | null; + /** Roles */ + roles?: components["schemas"]["SCIMMultiValuedAttribute"][] | null; /** Schemas */ schemas: string[]; + "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"?: components["schemas"]["SCIMEnterpriseUser"] | null; /** Username */ userName?: string | null; }; + "SCIMUser-Output": { + [key: string]: unknown; + }; /** SCIMUserEmail */ SCIMUserEmail: { /** Primary */ @@ -33179,6 +34348,15 @@ export interface components { /** Value */ value: string; }; + /** SCIMUserManager */ + SCIMUserManager: { + /** $Ref */ + $ref?: string | null; + /** Displayname */ + displayName?: string | null; + /** Value */ + value?: string | null; + }; /** SCIMUserName */ SCIMUserName: { /** Familyname */ @@ -35136,8 +36314,10 @@ export interface components { allowed_tools?: string[] | null; /** Args */ args?: string[]; + /** Audience */ + audience?: string | null; /** Auth Type */ - auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token") | null; + auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token" | "oauth2_token_exchange" | "oauth2_id_jag" | "true_passthrough" | "oauth_delegate") | null; /** Authorization Url */ authorization_url?: string | null; /** @@ -35152,12 +36332,21 @@ export interface components { /** Command */ command?: string | null; credentials?: components["schemas"]["MCPCredentials"] | null; + /** Dcr Bridge */ + dcr_bridge?: boolean | null; + /** + * Delegate Auth To Upstream + * @default false + */ + delegate_auth_to_upstream: boolean; /** Description */ description?: string | null; /** Env */ env?: { [key: string]: string; }; + /** Env Vars */ + env_vars?: components["schemas"]["MCPEnvVar"][] | null; /** Extra Headers */ extra_headers?: string[] | null; /** Instructions */ @@ -35167,12 +36356,23 @@ export interface components { * @default false */ is_byok: boolean; + /** Issuer */ + issuer?: string | null; + /** Max Concurrent Requests */ + max_concurrent_requests?: number | null; /** Mcp Access Groups */ mcp_access_groups?: string[]; /** Mcp Info */ mcp_info?: { [key: string]: unknown; } | null; + /** Oauth2 Flow */ + oauth2_flow?: ("client_credentials" | "authorization_code") | null; + /** + * Oauth Passthrough + * @default false + */ + oauth_passthrough: boolean; /** Registration Url */ registration_url?: string | null; /** Server Id */ @@ -35187,6 +36387,14 @@ export interface components { static_headers?: { [key: string]: string; } | null; + /** Subject Token Type */ + subject_token_type?: string | null; + /** Timeout */ + timeout?: number | null; + /** Token Exchange Endpoint */ + token_exchange_endpoint?: string | null; + /** Token Exchange Profile */ + token_exchange_profile?: string | null; /** Token Url */ token_url?: string | null; /** Tool Name To Description */ @@ -37088,6 +38296,46 @@ export interface operations { }; }; }; + jwks_json__well_known_jwks_json_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + native_client_auth_discovery__well_known_litellm_cli_auth_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; get_ui_config__well_known_litellm_ui_config_get: { parameters: { query?: never; @@ -37108,6 +38356,283 @@ export interface operations { }; }; }; + oauth_authorization_server_mcp__well_known_oauth_authorization_server_get: { + parameters: { + query?: { + mcp_server_name?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + oauth_authorization_server_aggregate__well_known_oauth_authorization_server_mcp_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + oauth_authorization_server_mcp_standard__well_known_oauth_authorization_server_mcp__mcp_server_name__get: { + parameters: { + query?: never; + header?: never; + path: { + mcp_server_name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + oauth_authorization_server_mcp__well_known_oauth_authorization_server__mcp_server_name__get: { + parameters: { + query?: never; + header?: never; + path: { + mcp_server_name: string | null; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + oauth_authorization_server_legacy__well_known_oauth_authorization_server__mcp_server_name__mcp_get: { + parameters: { + query?: never; + header?: never; + path: { + mcp_server_name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + oauth_protected_resource_mcp__well_known_oauth_protected_resource_get: { + parameters: { + query?: { + mcp_server_name?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + oauth_protected_resource_aggregate__well_known_oauth_protected_resource_mcp_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + oauth_protected_resource_mcp_standard__well_known_oauth_protected_resource_mcp__mcp_server_name__get: { + parameters: { + query?: never; + header?: never; + path: { + mcp_server_name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + oauth_protected_resource_mcp__well_known_oauth_protected_resource__mcp_server_name__mcp_get: { + parameters: { + query?: never; + header?: never; + path: { + mcp_server_name: string | null; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + openid_configuration__well_known_openid_configuration_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; invoke_agent_a2a_a2a__agent_id__post: { parameters: { query?: never; @@ -38154,6 +39679,78 @@ export interface operations { }; }; }; + authorize_authorize_get: { + parameters: { + query: { + redirect_uri: string; + client_id?: string | null; + state?: string; + mcp_server_name?: string | null; + code_challenge?: string | null; + code_challenge_method?: string | null; + response_type?: string | null; + scope?: string | null; + resource?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + authorize_complete_authorize_complete_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": components["schemas"]["Body_authorize_complete_authorize_complete_post"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; get_auto_router_benchmarks_auto_router_benchmarks_get: { parameters: { query?: { @@ -39365,6 +40962,41 @@ export interface operations { }; }; }; + callback_callback_get: { + parameters: { + query?: { + code?: string | null; + state?: string | null; + error?: string | null; + error_description?: string | null; + error_uri?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; get_callback_configs_callbacks_configs_get: { parameters: { query?: never; @@ -40901,7 +42533,10 @@ export interface operations { update_hashicorp_vault_config_config_overrides_hashicorp_vault_post: { parameters: { query?: never; - header?: never; + header?: { + /** @description The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability */ + "litellm-changed-by"?: string | null; + }; path?: never; cookie?: never; }; @@ -40934,7 +42569,10 @@ export interface operations { delete_hashicorp_vault_config_config_overrides_hashicorp_vault_delete: { parameters: { query?: never; - header?: never; + header?: { + /** @description The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability */ + "litellm-changed-by"?: string | null; + }; path?: never; cookie?: never; }; @@ -40949,6 +42587,15 @@ export interface operations { "application/json": unknown; }; }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; }; }; test_hashicorp_vault_connection_config_overrides_hashicorp_vault_test_connection_post: { @@ -47174,6 +48821,12 @@ export interface operations { query?: { /** @description The server id to list tools for */ server_id?: string | null; + /** @description Filter tools to a single MCP server by name or alias */ + mcp_server_name?: string | null; + /** @description Filter tools to a single toolset by name */ + toolset_name?: string | null; + /** @description Admin only. Return the full server tool catalog without the allowed_tools filter or per-key tool permissions, so the MCP settings UI can configure the allowlist. Ignored for non-admins. */ + include_disabled_tools?: boolean; }; header?: never; path?: never; @@ -48928,6 +50581,26 @@ export interface operations { }; }; }; + create_realtime_transcription_session_openai_v1_realtime_transcription_sessions_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RealtimeTranscriptionSessionResponse"]; + }; + }; + }; + }; responses_api_openai_v1_responses_post: { parameters: { query?: never; @@ -51743,6 +53416,57 @@ export interface operations { }; }; }; + create_realtime_transcription_session_realtime_transcription_sessions_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RealtimeTranscriptionSessionResponse"]; + }; + }; + }; + }; + register_client_register_post: { + parameters: { + query?: { + mcp_server_name?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; reload_anthropic_beta_headers_reload_anthropic_beta_headers_post: { parameters: { query?: never; @@ -51985,6 +53709,39 @@ export interface operations { }; }; }; + revoke_endpoint_revoke_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": components["schemas"]["Body_revoke_endpoint_revoke_post"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; get_robots_robots_txt_get: { parameters: { query?: never; @@ -52649,7 +54406,7 @@ export interface operations { }; requestBody: { content: { - "application/json": components["schemas"]["SCIMUser"]; + "application/json": components["schemas"]["SCIMUser-Input"]; }; }; responses: { @@ -52659,7 +54416,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["SCIMUser"]; + "application/json": components["schemas"]["SCIMUser-Output"]; }; }; /** @description Validation Error */ @@ -52692,7 +54449,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["SCIMUser"]; + "application/json": components["schemas"]["SCIMUser-Output"]; }; }; /** @description Validation Error */ @@ -52719,7 +54476,7 @@ export interface operations { }; requestBody: { content: { - "application/json": components["schemas"]["SCIMUser"]; + "application/json": components["schemas"]["SCIMUser-Input"]; }; }; responses: { @@ -52729,7 +54486,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["SCIMUser"]; + "application/json": components["schemas"]["SCIMUser-Output"]; }; }; /** @description Validation Error */ @@ -52797,7 +54554,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["SCIMUser"]; + "application/json": components["schemas"]["SCIMUser-Output"]; }; }; /** @description Validation Error */ @@ -53280,6 +55037,8 @@ export interface operations { page_size?: number; /** @description Filter logs by status (e.g., success, failure) */ status_filter?: string | null; + /** @description Filter logs by cache state: 'hit' or 'miss'. Miss includes legacy rows with a null/unknown cache state */ + cache_hit_filter?: string | null; /** @description Filter logs by model */ model?: string | null; /** @description Filter logs by model ID (litellm model deployment id) */ @@ -53298,6 +55057,8 @@ export interface operations { sort_by?: string; /** @description Sort order: asc or desc */ sort_order?: string | null; + /** @description Exclude LiteLLM internal health check requests from results */ + exclude_internal_health_checks?: boolean; }; header?: never; path?: never; @@ -53388,6 +55149,8 @@ export interface operations { page_size?: number; /** @description Filter logs by status (e.g., success, failure) */ status_filter?: string | null; + /** @description Filter logs by cache state: 'hit' or 'miss'. Miss includes legacy rows with a null/unknown cache state */ + cache_hit_filter?: string | null; /** @description Filter logs by model */ model?: string | null; /** @description Filter logs by model ID (litellm model deployment id) */ @@ -53406,6 +55169,8 @@ export interface operations { sort_by?: string; /** @description Sort order: asc or desc */ sort_order?: string | null; + /** @description Exclude LiteLLM internal health check requests from results */ + exclude_internal_health_checks?: boolean; }; header?: never; path?: never; @@ -55387,6 +57152,41 @@ export interface operations { }; }; }; + token_endpoint_token_post: { + parameters: { + query?: { + mcp_server_name?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": components["schemas"]["Body_token_endpoint_token_post"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; toolset_mcp_route_toolset__toolset_name__mcp_get: { parameters: { query?: never; @@ -56500,6 +58300,39 @@ export interface operations { }; }; }; + discover_agent_card_v1_a2a_discover_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["DiscoverAgentRequest"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DiscoverAgentResponse"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; invoke_agent_a2a_v1_a2a__agent_id__message_send_post: { parameters: { query?: never; @@ -58524,6 +60357,26 @@ export interface operations { }; }; }; + index_list_v1_indexes_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["IndexListResponse"]; + }; + }; + }; + }; index_create_v1_indexes_post: { parameters: { query?: never; @@ -58709,6 +60562,8 @@ export interface operations { query?: { /** @description Filter MCP servers by team scope. When provided, returns only servers the team has access to plus globally available (allow_all_keys) servers. Used by the Create Key UI to show team-scoped MCP servers. */ team_id?: string | null; + /** @description Annotate each returned server with connected_app_reachable: whether a connected app authorized by the calling user (a gateway OAuth session) is served this server on the aggregate MCP endpoint. */ + connected_app_view?: boolean; }; header?: never; path?: never; @@ -59223,6 +61078,103 @@ export interface operations { }; }; }; + get_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_get: { + parameters: { + query?: never; + header?: never; + path: { + server_id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MCPUserEnvVarsStatus"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + store_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_post: { + parameters: { + query?: never; + header?: never; + path: { + server_id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["MCPUserEnvVarsRequest"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MCPUserEnvVarsStatus"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + clear_mcp_user_env_vars_v1_mcp_server__server_id__user_env_vars_delete: { + parameters: { + query?: never; + header?: never; + path: { + server_id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MCPUserEnvVarsStatus"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; get_mcp_tools_v1_mcp_tools_get: { parameters: { query?: never; @@ -59417,6 +61369,26 @@ export interface operations { }; }; }; + list_mcp_user_env_var_status_v1_mcp_user_env_vars_status_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MCPUserEnvVarsStatus"][]; + }; + }; + }; + }; list_memory_v1_memory_get: { parameters: { query?: { @@ -59900,6 +61872,26 @@ export interface operations { }; }; }; + create_realtime_transcription_session_v1_realtime_transcription_sessions_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RealtimeTranscriptionSessionResponse"]; + }; + }; + }; + }; rerank_v1_rerank_post: { parameters: { query?: never; @@ -61810,6 +63802,139 @@ export interface operations { }; }; }; + list_gemini_agents_v1beta_agents_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + create_gemini_agent_v1beta_agents_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + get_gemini_agent_v1beta_agents__name__get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + delete_gemini_agent_v1beta_agents__name__delete: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + list_gemini_agent_versions_v1beta_agents__name__versions_get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; create_interaction_v1beta_interactions_post: { parameters: { query?: never; @@ -64066,6 +66191,46 @@ export interface operations { }; }; }; + authorize__mcp_server_name__authorize_get: { + parameters: { + query: { + redirect_uri: string; + client_id?: string | null; + state?: string; + code_challenge?: string | null; + code_challenge_method?: string | null; + response_type?: string | null; + scope?: string | null; + resource?: string | null; + }; + header?: never; + path: { + mcp_server_name: string | null; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; dynamic_mcp_route__mcp_server_name__mcp_get: { parameters: { query?: never; @@ -64283,6 +66448,72 @@ export interface operations { }; }; }; + register_client__mcp_server_name__register_post: { + parameters: { + query?: never; + header?: never; + path: { + mcp_server_name: string | null; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + token_endpoint__mcp_server_name__token_post: { + parameters: { + query?: never; + header?: never; + path: { + mcp_server_name: string | null; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": components["schemas"]["Body_token_endpoint__mcp_server_name__token_post"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; list_batches__provider__v1_batches_get: { parameters: { query?: { diff --git a/uv.lock b/uv.lock index ca5c4eb8c3c..f42c67079e6 100644 --- a/uv.lock +++ b/uv.lock @@ -10,7 +10,7 @@ resolution-markers = [ ] [options] -exclude-newer = "2026-08-23T20:15:58.934396Z" +exclude-newer = "2026-08-24T20:19:42.376246Z" exclude-newer-span = "P3D" [manifest] @@ -4665,12 +4665,12 @@ proxy-dev = [ [[package]] name = "litellm-enterprise" -version = "0.1.60" +version = "0.1.61" source = { editable = "enterprise" } [[package]] name = "litellm-proxy-extras" -version = "0.4.89" +version = "0.4.90" source = { editable = "litellm-proxy-extras" } [[package]]