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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] Litellm new endpoint add container file upload (#18743)
Ishaan Jaff1f141f0dbb27
diff --git a/docs/my-website/docs/container_files.md b/docs/my-website/docs/container_files.mdindex 25b58a043c8..1ef7687ea77 100644--- a/docs/my-website/docs/container_files.md+++ b/docs/my-website/docs/container_files.md@@ -21,6 +21,7 @@ Looking for how to use Code Interpreter? See the [Code Interpreter Guide](/docs/| Endpoint | Method | Description ||----------|--------|-------------|+| `/v1/containers/{container_id}/files` | POST | Upload file to container || `/v1/containers/{container_id}/files` | GET | List files in container || `/v1/containers/{container_id}/files/{file_id}` | GET | Get file metadata || `/v1/containers/{container_id}/files/{file_id}/content` | GET | Download file content |@@ -28,6 +29,45 @@ Looking for how to use Code Interpreter? See the [Code Interpreter Guide](/docs/## LiteLLM Python SDK+### Upload Container File++Upload files directly to a container session. This is useful when `/chat/completions` or `/responses` sends files to the container but the input file type is limited to PDF. This endpoint lets you work with other file types like CSV, Excel, Python scripts, etc.++```python showLineNumbers title="upload_container_file.py"+from litellm import upload_container_file++# Upload a CSV file+file = upload_container_file(+ container_id="cntr_123...",+ file=("data.csv", open("data.csv", "rb").read(), "text/csv"),+ custom_llm_provider="openai"+)++print(f"Uploaded: {file.id}")+print(f"Path: {file.path}")+```++**Async:**++```python showLineNumbers title="aupload_container_file.py"+from litellm import aupload_container_file++file = await aupload_container_file(+ container_id="cntr_123...",+ file=("script.py", b"print('hello world')", "text/x-python"),+ custom_llm_provider="openai"+)+```++**Supported file formats:**+- CSV (`.csv`)+- Excel (`.xlsx`)+- Python scripts (`.py`)+- JSON (`.json`)+- Markdown (`.md`)+- Text files (`.txt`)+- And more...+### List Container Files```python showLineNumbers title="list_container_files.py"@@ -103,6 +143,40 @@ print(f"Deleted: {result.deleted}")import Tabs from '@theme/Tabs';import TabItem from '@theme/TabItem';+### Upload File++<Tabs>+<TabItem value="openai-sdk" label="OpenAI SDK">++```python showLineNumbers title="upload_file.py"+from openai import OpenAI++client = OpenAI(+ api_key="sk-1234",+ base_url="http://localhost:4000"+)++file = client.containers.files.create(+ container_id="cntr_123...",+ file=open("data.csv", "rb")+)++print(f"Uploaded: {file.id}")+print(f"Path: {file.path}")+```++</TabItem>+<TabItem value="curl" label="curl">++```bash showLineNumbers title="upload_file.sh"+curl "http://localhost:4000/v1/containers/cntr_123.../files" \+ -H "Authorization: Bearer sk-1234" \+ -F file="@data.csv"+```++</TabItem>+</Tabs>+### List Files<Tabs>@@ -236,6 +310,13 @@ curl -X DELETE "http://localhost:4000/v1/containers/cntr_123.../files/cfile_456.## Parameters+### Upload File++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `container_id` | string | Yes | Container ID |+| `file` | FileTypes | Yes | File to upload. Can be a tuple of (filename, content, content_type), file-like object, or bytes |+### List Files| Parameter | Type | Required | Description |diff --git a/litellm/containers/endpoint_factory.py b/litellm/containers/endpoint_factory.pyindex 998b42a3abd..0b73a19b922 100644--- a/litellm/containers/endpoint_factory.py+++ b/litellm/containers/endpoint_factory.py@@ -216,6 +216,8 @@ _generated_endpoints = generate_container_endpoints()# Export generated functions dynamicallylist_container_files = _generated_endpoints.get("list_container_files")alist_container_files = _generated_endpoints.get("alist_container_files")+upload_container_file = _generated_endpoints.get("upload_container_file")+aupload_container_file = _generated_endpoints.get("aupload_container_file")retrieve_container_file = _generated_endpoints.get("retrieve_container_file")aretrieve_container_file = _generated_endpoints.get("aretrieve_container_file")delete_container_file = _generated_endpoints.get("delete_container_file")diff --git a/litellm/containers/endpoints.json b/litellm/containers/endpoints.jsonindex 4a23fc75c31..1ba61ee26e9 100644--- a/litellm/containers/endpoints.json+++ b/litellm/containers/endpoints.json@@ -9,6 +9,16 @@"query_params": ["after", "limit", "order"],"response_type": "ContainerFileListResponse"},+ {+ "name": "upload_container_file",+ "async_name": "aupload_container_file",+ "path": "/containers/{container_id}/files",+ "method": "POST",+ "path_params": ["container_id"],+ "query_params": [],+ "response_type": "ContainerFileObject",+ "is_multipart": true+ },{"name": "retrieve_container_file","async_name": "aretrieve_container_file",diff --git a/litellm/containers/main.py b/litellm/containers/main.pyindex 1fe7a26c0a8..625a291fb55 100644--- a/litellm/containers/main.py+++ b/litellm/containers/main.py@@ -13,11 +13,13 @@ from litellm.main import base_llm_http_handlerfrom litellm.types.containers.main import (ContainerCreateOptionalRequestParams,ContainerFileListResponse,+ ContainerFileObject,ContainerListOptionalRequestParams,ContainerListResponse,ContainerObject,DeleteContainerResult,)+from litellm.types.llms.openai import FileTypesfrom litellm.types.router import GenericLiteLLMParamsfrom litellm.types.utils import CallTypesfrom litellm.utils import ProviderConfigManager, client@@ -28,11 +30,13 @@ __all__ = ["alist_container_files","alist_containers","aretrieve_container",+ "aupload_container_file","create_container","delete_container","list_container_files","list_containers","retrieve_container",+ "upload_container_file",]##### Container Create #######################@@ -1011,3 +1015,236 @@ def list_container_files(extra_kwargs=kwargs,)++##### Container File Upload #######################+@client+async def aupload_container_file(+ container_id: str,+ file: FileTypes,+ timeout=600, # default to 10 minutes+ custom_llm_provider: Literal["openai"] = "openai",+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> ContainerFileObject:+ """Asynchronously upload a file to a container.++ This endpoint allows uploading files directly to a container session,+ supporting various file types like CSV, Excel, Python scripts, etc.++ Parameters:+ - `container_id` (str): The ID of the container to upload the file to+ - `file` (FileTypes): The file to upload. Can be:+ - A tuple of (filename, content, content_type)+ - A tuple of (filename, content)+ - A file-like object with read() method+ - Bytes+ - A string path to a file+ - `timeout` (int): Request timeout in seconds+ - `custom_llm_provider` (Literal["openai"]): The LLM provider to use+ - `extra_headers` (Optional[Dict[str, Any]]): Additional headers+ - `extra_query` (Optional[Dict[str, Any]]): Additional query parameters+ - `extra_body` (Optional[Dict[str, Any]]): Additional body parameters+ - `kwargs` (dict): Additional keyword arguments++ Returns:+ - `response` (ContainerFileObject): The uploaded file object++ Example:+ ```python+ import litellm++ # Upload a CSV file+ response = await litellm.aupload_container_file(+ container_id="container_abc123",+ file=("data.csv", open("data.csv", "rb").read(), "text/csv"),+ custom_llm_provider="openai",+ )+ print(response)+ ```+ """+ local_vars = locals()+ try:+ loop = asyncio.get_event_loop()+ kwargs["async_call"] = True++ func = partial(+ upload_container_file,+ container_id=container_id,+ file=file,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ extra_query=extra_query,+ extra_body=extra_body,+ **kwargs,+ )++ ctx = contextvars.copy_context()+ func_with_context = partial(ctx.run, func)+ init_response = await loop.run_in_executor(None, func_with_context)++ if asyncio.iscoroutine(init_response):+ response = await init_response+ else:+ response = init_response++ return response+ except Exception as e:+ raise litellm.exception_type(+ model="",+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )+++# fmt: off++@overload+def upload_container_file(+ container_id: str,+ file: FileTypes,+ timeout=600,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider: Literal["openai"] = "openai",+ *,+ aupload_container_file: Literal[True],+ **kwargs,+) -> Coroutine[Any, Any, ContainerFileObject]:+ ...+++@overload+def upload_container_file(+ container_id: str,+ file: FileTypes,+ timeout=600,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider: Literal["openai"] = "openai",+ *,+ aupload_container_file: Literal[False] = False,+ **kwargs,+) -> ContainerFileObject:+ ...++# fmt: on+++@client+def upload_container_file(+ container_id: str,+ file: FileTypes,+ timeout=600, # default to 10 minutes+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ api_version: Optional[str] = None,+ custom_llm_provider: Literal["openai"] = "openai",+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> Union[+ ContainerFileObject,+ Coroutine[Any, Any, ContainerFileObject],+]:+ """Upload a file to a container using the OpenAI Container API.++ This endpoint allows uploading files directly to a container session,+ supporting various file types like CSV, Excel, Python scripts, JSON, etc.+ This is useful when /chat/completions or /responses sends files to the+ container but the input file type is limited to PDF. This endpoint lets+ you work with other file types.++ Currently supports OpenAI++ Example:+ ```python+ import litellm++ # Upload a CSV file+ response = litellm.upload_container_file(+ container_id="container_abc123",+ file=("data.csv", open("data.csv", "rb").read(), "text/csv"),+ custom_llm_provider="openai",+ )+ print(response)++ # Upload a Python script+ response = litellm.upload_container_file(+ container_id="container_abc123",+ file=("script.py", b"print('hello world')", "text/x-python"),+ custom_llm_provider="openai",+ )+ print(response)+ ```+ """+ from litellm.llms.custom_httpx.container_handler import generic_container_handler++ local_vars = locals()+ try:+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.pop("litellm_logging_obj") # type: ignore+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id")+ _is_async = kwargs.pop("async_call", False) is True++ # Check for mock response first+ mock_response = kwargs.get("mock_response")+ if mock_response is not None:+ if isinstance(mock_response, str):+ mock_response = json.loads(mock_response)++ response = ContainerFileObject(**mock_response)+ return response++ # get llm provider logic+ litellm_params = GenericLiteLLMParams(**kwargs)+ # get provider config+ container_provider_config: Optional[BaseContainerConfig] = (+ ProviderConfigManager.get_provider_container_config(+ provider=litellm.LlmProviders(custom_llm_provider),+ )+ )++ if container_provider_config is None:+ raise ValueError(f"Container provider config not found for provider: {custom_llm_provider}")++ # Pre Call logging+ litellm_logging_obj.update_environment_variables(+ model="",+ optional_params={"container_id": container_id},+ litellm_params={+ "litellm_call_id": litellm_call_id,+ },+ custom_llm_provider=custom_llm_provider,+ )++ # Set the correct call type+ litellm_logging_obj.call_type = CallTypes.upload_container_file.value++ return generic_container_handler.handle(+ endpoint_name="upload_container_file",+ container_provider_config=container_provider_config,+ litellm_params=litellm_params,+ logging_obj=litellm_logging_obj,+ extra_headers=extra_headers,+ extra_query=extra_query,+ timeout=timeout or DEFAULT_REQUEST_TIMEOUT,+ _is_async=_is_async,+ container_id=container_id,+ file=file,+ )++ except Exception as e:+ raise litellm.exception_type(+ model="",+ custom_llm_provider=custom_llm_provider,+ original_exception=e,+ completion_kwargs=local_vars,+ extra_kwargs=kwargs,+ )diff --git a/litellm/llms/custom_httpx/container_handler.py b/litellm/llms/custom_httpx/container_handler.pyindex ed112e4dd58..73017eaaf30 100644--- a/litellm/llms/custom_httpx/container_handler.py+++ b/litellm/llms/custom_httpx/container_handler.py@@ -88,6 +88,34 @@ def _build_query_params(return params+def _prepare_multipart_file_upload(+ file: Any,+ headers: Dict[str, Any],+) -> tuple:+ """+ Prepare file and headers for multipart upload.++ Returns:+ Tuple of (files_dict, headers_without_content_type)+ """+ from litellm.litellm_core_utils.prompt_templates.common_utils import (+ extract_file_data,+ )++ extracted = extract_file_data(file)+ filename = extracted.get("filename") or "file"+ content = extracted.get("content") or b""+ content_type = extracted.get("content_type") or "application/octet-stream"+ files = {"file": (filename, content, content_type)}++ # Remove content-type header - httpx will set it automatically for multipart+ headers_copy = headers.copy()+ headers_copy.pop("content-type", None)+ headers_copy.pop("Content-Type", None)++ return files, headers_copy++class GenericContainerHandler:"""Generic handler for container file API endpoints.@@ -210,6 +238,7 @@ class GenericContainerHandler:# Make requestmethod = endpoint_config["method"].upper()returns_binary = endpoint_config.get("returns_binary", False)+ is_multipart = endpoint_config.get("is_multipart", False)try:if method == "GET":@@ -217,7 +246,11 @@ class GenericContainerHandler:elif method == "DELETE":response = http_client.delete(url=url, headers=headers, params=query_params)elif method == "POST":- response = http_client.post(url=url, headers=headers, params=query_params)+ if is_multipart and "file" in kwargs:+ files, headers = _prepare_multipart_file_upload(kwargs["file"], headers)+ response = http_client.post(url=url, headers=headers, params=query_params, files=files)+ else:+ response = http_client.post(url=url, headers=headers, params=query_params)else:raise ValueError(f"Unsupported HTTP method: {method}")@@ -307,6 +340,7 @@ class GenericContainerHandler:# Make requestmethod = endpoint_config["method"].upper()returns_binary = endpoint_config.get("returns_binary", False)+ is_multipart = endpoint_config.get("is_multipart", False)try:if method == "GET":@@ -314,7 +348,11 @@ class GenericContainerHandler:elif method == "DELETE":response = await http_client.delete(url=url, headers=headers, params=query_params)elif method == "POST":- response = await http_client.post(url=url, headers=headers, params=query_params)+ if is_multipart and "file" in kwargs:+ files, headers = _prepare_multipart_file_upload(kwargs["file"], headers)+ response = await http_client.post(url=url, headers=headers, params=query_params, files=files)+ else:+ response = await http_client.post(url=url, headers=headers, params=query_params)else:raise ValueError(f"Unsupported HTTP method: {method}")diff --git a/litellm/proxy/container_endpoints/handler_factory.py b/litellm/proxy/container_endpoints/handler_factory.pyindex 7eee44afb4b..dc10e39bc91 100644--- a/litellm/proxy/container_endpoints/handler_factory.py+++ b/litellm/proxy/container_endpoints/handler_factory.py@@ -43,7 +43,7 @@ def _get_container_provider_config(custom_llm_provider: str):raise ValueError(f"Container API not supported for provider: {custom_llm_provider}")-def _create_handler_for_path_params(path_params: List[str], route_type: str, returns_binary: bool = False):+def _create_handler_for_path_params(path_params: List[str], route_type: str, returns_binary: bool = False, is_multipart: bool = False):"""Dynamically create a handler with the correct path parameter signature."""@@ -63,6 +63,23 @@ def _create_handler_for_path_params(path_params: List[str], route_type: str, ret)return handler_binary_content+ # For multipart file upload endpoints+ if is_multipart:+ async def handler_multipart_upload(+ request: Request,+ container_id: str,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+ ):+ return await _process_multipart_upload_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type=route_type,+ container_id=container_id,+ )+ return handler_multipart_upload+# Create handlers for different path parameter combinationsif path_params == ["container_id"]:async def handler_container_id(@@ -193,6 +210,83 @@ async def _process_binary_request(raise e+async def _process_multipart_upload_request(+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth,+ route_type: str,+ container_id: str,+):+ """Process multipart file upload requests."""+ from litellm.proxy.common_utils.http_parsing_utils import (+ convert_upload_files_to_file_data,+ get_form_data,+ )+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ # Parse multipart form data and convert files+ form_data = await get_form_data(request)+ data = await convert_upload_files_to_file_data(form_data)++ if "file" not in data:+ from fastapi import HTTPException+ raise HTTPException(status_code=400, detail="Missing required 'file' field")++ # convert_upload_files_to_file_data returns list of tuples, extract single file+ file_list = data["file"]+ if isinstance(file_list, list) and len(file_list) > 0:+ data["file"] = file_list[0]++ data["container_id"] = container_id++ custom_llm_provider = (+ get_custom_llm_provider_from_request_headers(request=request)+ or get_custom_llm_provider_from_request_query(request=request)+ or "openai"+ )+ data["custom_llm_provider"] = custom_llm_provider++ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ return await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type=route_type, # type: ignore[arg-type]+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )++async def _process_request(request: Request,fastapi_response: Response,@@ -272,9 +366,10 @@ def register_container_file_endpoints(router: APIRouter) -> None:path_params = endpoint_config.get("path_params", [])route_type = endpoint_config["async_name"]returns_binary = endpoint_config.get("returns_binary", False)+ is_multipart = endpoint_config.get("is_multipart", False)# Create handler with correct signature for path params- handler = _create_handler_for_path_params(path_params, route_type, returns_binary)+ handler = _create_handler_for_path_params(path_params, route_type, returns_binary, is_multipart)# Register routesroute_method = getattr(router, method)diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 2191968e86c..8a8fd6794e7 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -2,4 +2,7 @@ model_list:- model_name: anthropic/*litellm_params:model: anthropic/*+ - model_name: openai/*+ litellm_params:+ model: openai/*diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex a321e25a9a5..5d2e13a78b9 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -38,6 +38,7 @@ ROUTE_ENDPOINT_MAPPING = {"aretrieve_container": "/containers/{container_id}","adelete_container": "/containers/{container_id}",# Auto-generated container file routes+ "aupload_container_file": "/containers/{container_id}/files","alist_container_files": "/containers/{container_id}/files","aretrieve_container_file": "/containers/{container_id}/files/{file_id}","adelete_container_file": "/containers/{container_id}/files/{file_id}",@@ -144,6 +145,7 @@ async def route_request("alist_containers","aretrieve_container","adelete_container",+ "aupload_container_file","alist_container_files","aretrieve_container_file","adelete_container_file",@@ -204,6 +206,7 @@ async def route_request("alist_containers","aretrieve_container","adelete_container",+ "aupload_container_file","alist_container_files","aretrieve_container_file","adelete_container_file",@@ -287,6 +290,7 @@ async def route_request("alist_containers","aretrieve_container","adelete_container",+ "aupload_container_file","alist_container_files","aretrieve_container_file","adelete_container_file",diff --git a/litellm/router.py b/litellm/router.pyindex fa58340b9b1..98ccf41c96d 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -4003,6 +4003,8 @@ class Router:"retrieve_container","adelete_container","delete_container",+ "aupload_container_file",+ "upload_container_file","alist_container_files","list_container_files","aretrieve_container_file",@@ -4154,6 +4156,7 @@ class Router:"alist_containers","aretrieve_container","adelete_container",+ "aupload_container_file","alist_container_files","aretrieve_container_file","adelete_container_file",diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 784c8403c3f..3817f46c3e2 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -324,6 +324,8 @@ class CallTypes(str, Enum):adelete_container = "adelete_container"list_container_files = "list_container_files"alist_container_files = "alist_container_files"+ upload_container_file = "upload_container_file"+ aupload_container_file = "aupload_container_file"acancel_fine_tuning_job = "acancel_fine_tuning_job"cancel_fine_tuning_job = "cancel_fine_tuning_job"diff --git a/provider_endpoints_support.json b/provider_endpoints_support.jsonindex bc5dea7b97c..617e9d1e3d5 100644--- a/provider_endpoints_support.json+++ b/provider_endpoints_support.json@@ -1515,7 +1515,7 @@"list_containers": true,"retrieve_container": true,"delete_container": true,- "create_container_file": false,+ "create_container_file": true,"list_container_files": true,"retrieve_container_file": true,"retrieve_container_file_content": true,