Skip to content

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

Merge remote-tracking branch 'origin/main' into litellm_decrease_anys_opus5_r5

mateo-berri6df5eef7681a
diff --cc litellm/integrations/otel/model/metadata.py
index 9eab3021d58,cc81b689708..0de25b3f875
--- a/litellm/integrations/otel/model/metadata.py
+++ b/litellm/integrations/otel/model/metadata.py
@@@ -215,9 -217,10 +217,10 @@@ class LLMCallEvent
# needs to be reasonable for a span that never gets closed (a leak).
provisional_span_name: str
time_to_first_chunk_seconds: float | None
+ trace_name: str | None
@classmethod
- def from_dict(cls, kwargs: Mapping[str, Any]) -> LLMCallEvent:
+ def from_dict(cls, kwargs: Mapping[str, object]) -> LLMCallEvent:
raw_payload: Final = kwargs.get("standard_logging_object")
payload: Final = cast("StandardLoggingPayload", raw_payload) if raw_payload else None
operation: Final = resolve_operation(as_str(kwargs.get("call_type")))
diff --cc litellm/llms/bedrock/files/transformation.py
index f50d63c9f6f,6e2b0c12090..8b0affa1c0d
--- a/litellm/llms/bedrock/files/transformation.py
+++ b/litellm/llms/bedrock/files/transformation.py
@@@ -247,7 -264,129 +264,129 @@@ def _validate_file_id_against_configure
return validate_against(configured_bucket_names[-1])
+ _REJECTED_FILE_ID_REQUEST_URL: Final = "https://litellm.ai"
+
+
+ def _rejected_file_id(reason: ValueError) -> BedrockError:
+ message: Final = str(reason)
+ return BedrockError(
+ status_code=400,
+ message=message,
+ response=httpx.Response(
+ status_code=400,
+ text=message,
+ request=httpx.Request(method="GET", url=_REJECTED_FILE_ID_REQUEST_URL),
+ ),
+ )
+
+
+ def _resolve_managed_s3_object(file_id: str, litellm_params: Mapping[str, object]) -> tuple[str, str]:
+ configured_bucket_names: Final = get_configured_s3_bucket_names(litellm_params)
+ allow_legacy_cloud_file_ids: Final = should_allow_legacy_cloud_file_ids(litellm_params)
+ try:
+ return _validate_file_id_against_configured_buckets(
+ s3_uri=extract_s3_uri_from_file_id(file_id),
+ configured_bucket_names=configured_bucket_names,
+ allow_legacy_cloud_file_ids=allow_legacy_cloud_file_ids,
+ )
+ except ValueError as reason:
+ raise _rejected_file_id(reason) from reason
+
+
+ _ANY_MANAGED_LISTING_PREFIX: Final = os.path.commonprefix(BEDROCK_MANAGED_S3_PREFIXES)
+ _MANAGED_LISTING_PREFIX_BY_PURPOSE: Final = MappingProxyType(
+ {
+ "batch": os.path.commonprefix((BEDROCK_MANAGED_S3_BATCH_PREFIX, BEDROCK_MANAGED_S3_UPLOAD_PREFIX)),
+ "batch_output": BEDROCK_MANAGED_S3_OUTPUT_PREFIX,
+ }
+ )
+
+
+ _EMPTY_LISTING_QUERY: Final = (("list-type", "2"), ("max-keys", "0"))
+
+
+ def _managed_listing_prefix(configured_prefix: str, purpose: str | None) -> str | None:
+ managed_prefix: Final = _MANAGED_LISTING_PREFIX_BY_PURPOSE.get(purpose) if purpose else _ANY_MANAGED_LISTING_PREFIX
+ if managed_prefix is None:
+ return None
+ return f"{configured_prefix}/{managed_prefix}" if configured_prefix else managed_prefix
+
+
+ def _listing_query(configured_prefix: str, purpose: str | None) -> tuple[tuple[str, str], ...]:
+ listing_prefix: Final = _managed_listing_prefix(configured_prefix, purpose)
+ if listing_prefix is None:
+ return _EMPTY_LISTING_QUERY
+ return (("list-type", "2"), ("prefix", listing_prefix))
+
+
+ def _requested_listing_purpose(litellm_params: Mapping[str, object]) -> str | None:
+ requested_purpose: Final = litellm_params.get(LIST_FILES_PURPOSE_PARAM)
+ return requested_purpose if isinstance(requested_purpose, str) else None
+
+
+ def _walked_listing_purpose(litellm_params: Mapping[str, object]) -> str | None:
+ walked_purpose: Final = litellm_params.get(LIST_FILES_LOCATION_PARAM)
+ return walked_purpose if isinstance(walked_purpose, str) else _requested_listing_purpose(litellm_params)
+
+
+ def _output_location_still_unlisted(litellm_params: Mapping[str, object]) -> bool:
+ if _walked_listing_purpose(litellm_params) is not None:
+ return False
+ return _listing_bucket_name(litellm_params, "batch_output") != _listing_bucket_name(litellm_params, None)
+
+
+ def _listing_bucket_name(litellm_params: Mapping[str, object], purpose: str | None) -> str:
+ if purpose != "batch_output":
+ return get_configured_s3_bucket_name(litellm_params)
+ trusted: Final = _trusted_s3_model_credentials(litellm_params)
+ return (
+ trusted.s3_output_bucket_name
+ or os.getenv("AWS_S3_OUTPUT_BUCKET_NAME")
+ or get_configured_s3_bucket_name(litellm_params)
+ )
+
+
+ def _listed_object_created_at(entry: ET.Element) -> int:
+ last_modified: Final = entry.findtext("{*}LastModified")
+ if not last_modified:
+ return 0
+ return int(datetime.fromisoformat(last_modified.replace("Z", "+00:00")).timestamp())
+
+
+ def _listed_managed_file(
+ entry: ET.Element,
+ bucket_name: str,
+ configured_bucket_name: str,
+ allow_legacy_cloud_file_ids: bool,
+ ) -> OpenAIFileObject | None:
+ object_key: Final = entry.findtext("{*}Key")
+ if not object_key:
+ return None
+ file_id: Final = f"s3://{bucket_name}/{object_key}"
+ try:
+ validate_managed_cloud_file_id(
+ file_id=file_id,
+ scheme="s3://",
+ configured_bucket_name=configured_bucket_name,
+ allowed_object_prefixes=BEDROCK_MANAGED_S3_PREFIXES,
+ allow_legacy_cloud_file_ids=allow_legacy_cloud_file_ids,
+ )
+ except ValueError:
+ return None
+ _, configured_prefix = split_configured_cloud_bucket_name(configured_bucket_name)
+ relative_key: Final = object_key[len(configured_prefix) + 1 :] if configured_prefix else object_key
+ return OpenAIFileObject(
+ id=file_id,
+ bytes=int(entry.findtext("{*}Size") or 0),
+ created_at=_listed_object_created_at(entry),
+ filename=posixpath.basename(object_key),
+ object="file",
+ purpose="batch_output" if relative_key.startswith(BEDROCK_MANAGED_S3_OUTPUT_PREFIX) else "batch",
+ status="uploaded",
+ )
+
+
-def _uploaded_object_size(litellm_params: Mapping[str, object], raw_response: Response) -> int:
+def _uploaded_object_size(litellm_params: Mapping[str, object], response_headers: Mapping[str, str]) -> int:
"""
S3 answers PutObject with an empty body, so the stored object size comes from the
signed request recorded by `transform_create_file_request`, not the response headers.
diff --cc litellm/proxy/_lazy_features.py
index 17743e153f2,dd1180b30ad..33629c2369c
--- a/litellm/proxy/_lazy_features.py
+++ b/litellm/proxy/_lazy_features.py
@@@ -8,14 -8,17 +8,17 @@@ omits each feature's routes until the f
import asyncio
import importlib
- from collections.abc import Callable
+ from collections.abc import Callable, Mapping, Sequence
from collections.abc import Set as AbstractSet
from dataclasses import dataclass, field
+ from types import MappingProxyType
from typing import TYPE_CHECKING, Final
+ from starlette.routing import BaseRoute, Match
-from starlette.types import Receive, Scope, Send
+from starlette.types import ASGIApp, Receive, Scope, Send
from litellm._logging import verbose_proxy_logger
+ from litellm.proxy.route_priority import hot_routes_first
if TYPE_CHECKING:
from fastapi import APIRouter, FastAPI
diff --cc litellm/proxy/analytics_endpoints/cache_activity.py
index 952ef5bdcfc,902e3fb3db3..5de3b610782
--- a/litellm/proxy/analytics_endpoints/cache_activity.py
+++ b/litellm/proxy/analytics_endpoints/cache_activity.py
@@@ -6,22 -6,15 +6,25 @@@ from typing import Final, Protoco
from pydantic import BaseModel, TypeAdapter
+ from litellm.proxy._types import LiteLLMRoutes
+
-if TYPE_CHECKING:
- from litellm.proxy.utils import PrismaClient
-
UNKNOWN_CALL_TYPE: Final = "Unknown"
+ INFO_ROUTES_JSON: Final = json.dumps(LiteLLMRoutes.info_routes.value)
+class _SupportsQueryRaw(Protocol):
+ """The single database operation the cache-activity queries issue."""
+
+ async def query_raw(self, query: str, *args: object) -> Sequence[object]: ...
+
+
+class _SupportsRawQueryDb(Protocol):
+ """A prisma client handle, narrowed to the raw-query surface used here."""
+
+ @property
+ def db(self) -> _SupportsQueryRaw: ...
+
+
class CacheActivityGroup(BaseModel):
call_type: str
api_requests: int
diff --cc litellm/proxy/client/cli/commands/up.py
index 45d21b0c0b5,f2624797a5f..00e8b0a3a76
--- a/litellm/proxy/client/cli/commands/up.py
+++ b/litellm/proxy/client/cli/commands/up.py
@@@ -166,11 -166,10 +166,11 @@@ def up(ctx: click.Context) -> None
is already running (this does not start one for you). Cursor is not
supported: it has no equivalent file-based config to patch.
"""
- base_url: Final = ctx.obj["base_url"]
+ ctx_obj: Final[CliContextObj] = ctx.obj
+ base_url: Final = ctx_obj["base_url"]
try:
- _ensure_fresh_login(ctx)
+ ensure_fresh_login(ctx)
api_key: Final = resolve_api_key(ctx)
verify_proxy_key(base_url, api_key)
diff --cc litellm/proxy/db/prisma_client.py
index 2f2ebfdf2bb,acd01b0e99e..0524d015047
--- a/litellm/proxy/db/prisma_client.py
+++ b/litellm/proxy/db/prisma_client.py
@@@ -13,9 -13,10 +13,10 @@@ import urlli
import urllib.parse
from collections.abc import Callable
from datetime import datetime, timedelta
-from typing import Any, Final, Protocol
+from typing import TYPE_CHECKING, Any, Final, Protocol
from litellm._logging import verbose_proxy_logger
+ from litellm.proxy.db.db_url_settings import add_missing_query_params, token_refresh_params_from_url
from litellm.proxy.db.token_auth import (
DEFAULT_POSTGRES_PORT,
DatabaseTokenAuth,
diff --cc litellm/proxy/hooks/proxy_track_cost_callback.py
index e6ada41f062,3a61f773001..e1fc87d8ed9
--- a/litellm/proxy/hooks/proxy_track_cost_callback.py
+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py
@@@ -1,8 -1,8 +1,8 @@@
import asyncio
import traceback
- from collections.abc import Sequence
+ from collections.abc import Callable, Sequence
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, cast
+from typing import TYPE_CHECKING, Any, Final, Protocol, cast
import litellm
from litellm._logging import verbose_proxy_logger
diff --cc litellm/proxy/ocr_endpoints/endpoints.py
index 1d0108cc2ba,53ebbe91b54..8170c95e3e6
--- a/litellm/proxy/ocr_endpoints/endpoints.py
+++ b/litellm/proxy/ocr_endpoints/endpoints.py
@@@ -28,27 -28,10 +28,10 @@@ def _build_document_from_upload
filename: str | None,
content_type: str | None,
) -> dict[str, str]:
- """
- Convert uploaded file bytes into a Mistral-format document dict with base64 data URI.
-
- Delegates to convert_file_document_to_url_document after resolving MIME type
- from the upload's content_type header or filename.
- """
- mime_type = content_type.split(";")[0].strip() if content_type else None
- if not mime_type or mime_type == "application/octet-stream":
- if filename:
- mime_type = get_mime_type(filename)
-
- return convert_file_document_to_url_document(
- {
- "type": "file",
- "file": file_content,
- "mime_type": mime_type or "application/octet-stream",
- }
- )
+ return convert_upload_to_url_document(file_content, filename, content_type)
-def _with_request_format(data: Mapping[str, Any], request: Request) -> Mapping[str, Any]:
+def _with_request_format(data: Mapping[str, object], request: Request) -> Mapping[str, object]:
"""
Resolve the requested response format from the body or the `x-req-format` header.
diff --cc litellm/proxy/utils.py
index 21328a4962a,c095586b6c9..c0c741fe8dc
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@@ -3606,13 -4067,16 +4068,16 @@@ class PrismaClient
# loop and times out after 30s.
if token_auth is not None and reader_iam_endpoint is not None:
reader_token: Final = mint_database_token(token_auth, reader_iam_endpoint)
- read_replica_url = reader_iam_endpoint.build_url(reader_token)
+ read_replica_url = add_missing_query_params(
+ reader_iam_endpoint.build_url(reader_token),
+ token_refresh_params_from_url(read_replica_url),
+ )
os.environ["DATABASE_URL_READ_REPLICA"] = read_replica_url
- reader_kwargs: Final[dict[str, Any]] = {"datasource": {"url": read_replica_url}}
+ reader_datasource: Final = DatasourceOverride(url=read_replica_url)
if http_client is not None:
- reader_prisma = Prisma(http=http_client, **reader_kwargs)
+ reader_prisma = Prisma(http=http_client, datasource=reader_datasource)
else:
- reader_prisma = Prisma(**reader_kwargs)
+ reader_prisma = Prisma(datasource=reader_datasource)
reader_wrapper: Final = PrismaWrapper(
original_prisma=reader_prisma,
token_auth=token_auth,