Skip to content

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

chore: merge main into fix/batch-retrieve-model-group

mateo-berri741b10cdc9b0
diff --cc litellm/proxy/batches_endpoints/endpoints.py
index dbbbbd6f7cd,6d5f7a65855..f6c86d75169
--- a/litellm/proxy/batches_endpoints/endpoints.py
+++ b/litellm/proxy/batches_endpoints/endpoints.py
@@@ -6,11 -6,13 +6,13 @@@
######################################################################
import asyncio
import os
-from collections.abc import Mapping
+from collections.abc import Mapping, MutableMapping
+ from datetime import datetime
from types import MappingProxyType
- from typing import Any, Final, cast
+ from typing import TYPE_CHECKING, Any, Final, Literal, cast
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
+ from pydantic import TypeAdapter
import litellm
from litellm._logging import verbose_proxy_logger
@@@ -51,28 -63,84 +63,98 @@@ from litellm.proxy.openai_files_endpoin
update_batch_in_database,
validate_managed_id_requirement,
)
+ from litellm.proxy.pass_through_endpoints.llm_provider_handlers.batch_attribution import request_tags_from_metadata
from litellm.proxy.route_llm_request import raise_if_required_body_param_missing
- from litellm.proxy.utils import handle_exception_on_proxy, is_known_model
+ from litellm.proxy.utils import PrismaClient, ProxyLogging, handle_exception_on_proxy, is_known_model
+ from litellm.repositories.managed_batch_repository import ManagedBatchRepository
from litellm.repositories.table_repositories import ManagedFileRepository
+ from litellm.router import Router
from litellm.types.llms.openai import LiteLLMBatchCreateRequest
+ from litellm.types.utils import LiteLLMBatch
+
+ if TYPE_CHECKING:
+ from prisma.models import LiteLLM_ManagedObjectTable
router: Final = APIRouter()
+ _METADATA_ADAPTER: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object])
+
+
+ def _request_tags(data: Mapping[str, object]) -> tuple[str, ...] | None:
+ metadata: Final = data.get("litellm_metadata")
+ if metadata is None:
+ return None
+ return request_tags_from_metadata(_METADATA_ADAPTER.validate_python(metadata))
+
+
+ def _litellm_executed_batch_runner(llm_router: Router, proxy_logging_obj: ProxyLogging) -> LiteLLMExecutedBatchRunner:
+ from litellm.proxy.proxy_server import general_settings, prisma_client
+
+ managed_files: Final = proxy_logging_obj.get_proxy_hook("managed_files")
+ if prisma_client is None or not isinstance(managed_files, ManagedBatchStore):
+ raise batch_error(
+ 400,
+ "LiteLLM-executed batches need a database: set DATABASE_URL so LiteLLM can keep the batch and its files",
+ )
+ return LiteLLMExecutedBatchRunner(
+ llm_router=llm_router,
+ prisma_client=prisma_client,
+ managed_files=managed_files,
+ batches=ManagedBatchRepository(prisma_client),
+ proxy_logging_obj=proxy_logging_obj,
+ general_settings=general_settings,
+ )
+
+
+ async def _batch_from_database(
+ batch_id: str,
+ unified_batch_id: str | Literal[False],
+ executed_batch: bool,
+ managed_files_obj: object,
+ prisma_client: PrismaClient | None,
+ llm_router: Router | None,
+ proxy_logging_obj: ProxyLogging,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> tuple["LiteLLM_ManagedObjectTable | None", LiteLLMBatch | None]:
+ row, batch = await get_batch_from_database(
+ batch_id=batch_id,
+ unified_batch_id=unified_batch_id,
+ managed_files_obj=managed_files_obj,
+ prisma_client=prisma_client,
+ verbose_proxy_logger=verbose_proxy_logger,
+ )
+ updated_at: Final[object] = getattr(row, "updated_at", None)
+ if not executed_batch or batch is None or llm_router is None or not isinstance(updated_at, datetime):
+ return row, batch
+ if not executed_batch_runner_lost(batch.status, updated_at):
+ return row, batch
+ runner: Final = _litellm_executed_batch_runner(llm_router, proxy_logging_obj)
+ return row, await runner.fail_abandoned(batch, user_api_key_dict)
+
+
+ async def _raise_when_input_file_must_be_managed(model: str, credentials: Mapping[str, object]) -> None:
+ if await litellm_executed_provider_for(credentials) is None:
+ return
+ raise batch_error(
+ 400,
+ f"Batches for {model} run inside LiteLLM, so the input file must be a LiteLLM managed file: "
+ f"{LITELLM_EXECUTED_BATCH_UPLOAD_GUIDANCE}",
+ )
+def _litellm_metadata_of(data: MutableMapping[str, object]) -> MutableMapping[str, object]:
+ """The request's litellm_metadata mapping, created on the request when it carries none.
+
+ The success handler reads this mapping, so a flag or a model group set here has to live
+ inside it rather than beside it.
+ """
+ existing: Final = data.get("litellm_metadata")
+ if isinstance(existing, MutableMapping):
+ return existing
+ created: Final[dict[str, object]] = {} # mutable-ok: the logging layer copies and extends this mapping
+ data["litellm_metadata"] = created # rebind-ok: the success handler reads the request's own mapping
+ return created
+
+
def _raise_not_found_when_openai_fallback_unservable(
requested_provider: "str | None",
data: Mapping[str, object],