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]

[Feat] Add Initial support for Bedrock Batches API (#14190)

Ishaan Jaff19e2bab8c83b
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index 7eb355d39f2..2d4b9655c5d 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -335,12 +335,15 @@ router_settings:
| ANTHROPIC_API_KEY | API key for Anthropic service
| ANTHROPIC_API_BASE | Base URL for Anthropic API. Default is https://api.anthropic.com
| AWS_ACCESS_KEY_ID | Access Key ID for AWS services
+| AWS_BATCH_ROLE_ARN | ARN of the AWS IAM role for batch operations
| AWS_DEFAULT_REGION | Default AWS region for service interactions when AWS_REGION is not set
| AWS_PROFILE_NAME | AWS CLI profile name to be used
| AWS_REGION | AWS region for service interactions (takes precedence over AWS_DEFAULT_REGION)
| AWS_REGION_NAME | Default AWS region for service interactions
| AWS_ROLE_ARN | ARN of the AWS IAM role to assume for authentication
| AWS_ROLE_NAME | Role name for AWS IAM usage
+| AWS_S3_BUCKET_NAME | Name of the AWS S3 bucket for file operations
+| AWS_S3_OUTPUT_BUCKET_NAME | Name of the AWS S3 output bucket for batch operations
| AWS_SECRET_ACCESS_KEY | Secret Access Key for AWS services
| AWS_SESSION_NAME | Name for AWS session
| AWS_WEB_IDENTITY_TOKEN | Web identity token for AWS
diff --git a/litellm/batches/main.py b/litellm/batches/main.py
index 3ea0f95157f..0d250779da3 100644
--- a/litellm/batches/main.py
+++ b/litellm/batches/main.py
@@ -14,13 +14,15 @@ import asyncio
import contextvars
import os
from functools import partial
-from typing import Any, Coroutine, Dict, Literal, Optional, Union
+from typing import Any, Coroutine, Dict, Literal, Optional, Union, cast
import httpx
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.azure.batches.handler import AzureBatchesAPI
+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
+from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
from litellm.llms.openai.openai import OpenAIBatchesAPI
from litellm.llms.vertex_ai.batches.handler import VertexAIBatchPrediction
from litellm.secret_managers.main import get_secret_str
@@ -31,13 +33,19 @@ from litellm.types.llms.openai import (
RetrieveBatchRequest,
)
from litellm.types.router import GenericLiteLLMParams
-from litellm.types.utils import LiteLLMBatch
-from litellm.utils import client, get_litellm_params, supports_httpx_timeout
+from litellm.types.utils import LiteLLMBatch, LlmProviders
+from litellm.utils import (
+ ProviderConfigManager,
+ client,
+ get_litellm_params,
+ supports_httpx_timeout,
+)
####### ENVIRONMENT VARIABLES ###################
openai_batches_instance = OpenAIBatchesAPI()
azure_batches_instance = AzureBatchesAPI()
vertex_ai_batches_instance = VertexAIBatchPrediction(gcs_bucket_name="")
+base_llm_http_handler = BaseLLMHTTPHandler()
#################################################
@@ -46,7 +54,7 @@ async def acreate_batch(
completion_window: Literal["24h"],
endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
input_file_id: str,
- custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",
+ custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock"] = "openai",
metadata: Optional[Dict[str, str]] = None,
extra_headers: Optional[Dict[str, str]] = None,
extra_body: Optional[Dict[str, str]] = None,
@@ -94,7 +102,7 @@ def create_batch(
completion_window: Literal["24h"],
endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
input_file_id: str,
- custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",
+ custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock"] = "openai",
metadata: Optional[Dict[str, str]] = None,
extra_headers: Optional[Dict[str, str]] = None,
extra_body: Optional[Dict[str, str]] = None,
@@ -111,8 +119,8 @@ def create_batch(
proxy_server_request = kwargs.get("proxy_server_request", None)
model_info = kwargs.get("model_info", None)
_is_async = kwargs.pop("acreate_batch", False) is True
- litellm_params = get_litellm_params(**kwargs)
- litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj", None)
+ litellm_params = dict(GenericLiteLLMParams(**kwargs))
+ litellm_logging_obj: LiteLLMLoggingObj = cast(LiteLLMLoggingObj, kwargs.get("litellm_logging_obj", None))
### TIMEOUT LOGIC ###
timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
litellm_logging_obj.update_environment_variables(
@@ -142,6 +150,7 @@ def create_batch(
timeout = float(timeout) # type: ignore
elif timeout is None:
timeout = 600.0
+
_create_batch_request = CreateBatchRequest(
completion_window=completion_window,
@@ -151,6 +160,27 @@ def create_batch(
extra_headers=extra_headers,
extra_body=extra_body,
)
+ provider_config = ProviderConfigManager.get_provider_batches_config(
+ model="",
+ provider=LlmProviders(custom_llm_provider),
+ )
+ if provider_config is not None:
+ response = base_llm_http_handler.create_batch(
+ provider_config=provider_config,
+ litellm_params=litellm_params,
+ create_batch_data=_create_batch_request,
+ headers=extra_headers or {},
+ api_base=optional_params.api_base,
+ api_key=optional_params.api_key,
+ logging_obj=litellm_logging_obj,
+ _is_async=_is_async,
+ client=client
+ if client is not None
+ and isinstance(client, (HTTPHandler, AsyncHTTPHandler))
+ else None,
+ timeout=timeout,
+ )
+ return response
api_base: Optional[str] = None
if custom_llm_provider == "openai":
# for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
@@ -322,20 +352,21 @@ def retrieve_batch(
"""
try:
optional_params = GenericLiteLLMParams(**kwargs)
- litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj", None)
+ litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get("litellm_logging_obj", None)
### TIMEOUT LOGIC ###
timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
litellm_params = get_litellm_params(
custom_llm_provider=custom_llm_provider,
**kwargs,
)
- litellm_logging_obj.update_environment_variables(
- model=None,
- user=None,
- optional_params=optional_params.model_dump(),
- litellm_params=litellm_params,
- custom_llm_provider=custom_llm_provider,
- )
+ if litellm_logging_obj is not None:
+ litellm_logging_obj.update_environment_variables(
+ model=None,
+ user=None,
+ optional_params=optional_params.model_dump(),
+ litellm_params=litellm_params,
+ custom_llm_provider=custom_llm_provider,
+ )
if (
timeout is not None
diff --git a/litellm/files/main.py b/litellm/files/main.py
index 5d0dc05771a..299e52895bf 100644
--- a/litellm/files/main.py
+++ b/litellm/files/main.py
@@ -50,7 +50,7 @@ vertex_ai_files_instance = VertexAIFilesHandler()
async def acreate_file(
file: FileTypes,
purpose: Literal["assistants", "batch", "fine-tune"],
- custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",
+ custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock"] = "openai",
extra_headers: Optional[Dict[str, str]] = None,
extra_body: Optional[Dict[str, str]] = None,
**kwargs,
@@ -94,7 +94,7 @@ async def acreate_file(
def create_file(
file: FileTypes,
purpose: Literal["assistants", "batch", "fine-tune"],
- custom_llm_provider: Optional[Literal["openai", "azure", "vertex_ai"]] = None,
+ custom_llm_provider: Optional[Literal["openai", "azure", "vertex_ai", "bedrock"]] = None,
extra_headers: Optional[Dict[str, str]] = None,
extra_body: Optional[Dict[str, str]] = None,
**kwargs,
@@ -109,7 +109,7 @@ def create_file(
try:
_is_async = kwargs.pop("acreate_file", False) is True
optional_params = GenericLiteLLMParams(**kwargs)
- litellm_params_dict = get_litellm_params(**kwargs)
+ litellm_params_dict = dict(**kwargs)
logging_obj = cast(
Optional[LiteLLMLoggingObj], kwargs.get("litellm_logging_obj")
)
diff --git a/litellm/llms/base_llm/__init__.py b/litellm/llms/base_llm/__init__.py
index 187c985fd67..665e242969c 100644
--- a/litellm/llms/base_llm/__init__.py
+++ b/litellm/llms/base_llm/__init__.py
@@ -1,5 +1,6 @@
from .anthropic_messages.transformation import BaseAnthropicMessagesConfig
from .audio_transcription.transformation import BaseAudioTranscriptionConfig
+from .batches.transformation import BaseBatchesConfig
from .chat.transformation import BaseConfig
from .embedding.transformation import BaseEmbeddingConfig
from .image_edit.transformation import BaseImageEditConfig
@@ -12,4 +13,5 @@ __all__ = [
"BaseAnthropicMessagesConfig",
"BaseEmbeddingConfig",
"BaseImageEditConfig",
+ "BaseBatchesConfig",
]
diff --git a/litellm/llms/base_llm/batches/transformation.py b/litellm/llms/base_llm/batches/transformation.py
new file mode 100644
index 00000000000..1d3e54fae67
--- /dev/null
+++ b/litellm/llms/base_llm/batches/transformation.py
@@ -0,0 +1,176 @@
+import types
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+import httpx
+from httpx import Headers
+
+from litellm.types.llms.openai import (
+ AllMessageValues,
+ CreateBatchRequest,
+)
+from litellm.types.utils import LiteLLMBatch, LlmProviders
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+
+ from ..chat.transformation import BaseLLMException as _BaseLLMException
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+ BaseLLMException = _BaseLLMException
+else:
+ LiteLLMLoggingObj = Any
+ BaseLLMException = Any
+
+
+class BaseBatchesConfig(ABC):
+ """
+ Abstract base class for batch processing configurations across different LLM providers.
+
+ This class defines the interface that all provider-specific batch configurations
+ must implement to work with LiteLLM's unified batch processing system.
+ """
+
+ def __init__(self):
+ pass
+
+ @property
+ @abstractmethod
+ def custom_llm_provider(self) -> LlmProviders:
+ """Return the LLM provider type for this configuration."""
+ pass
+
+ @classmethod
+ def get_config(cls):
+ """Get configuration dictionary for this class."""
+ return {
+ k: v
+ for k, v in cls.__dict__.items()
+ if not k.startswith("__")
+ and not k.startswith("_abc")
+ and not isinstance(
+ v,
+ (
+ types.FunctionType,
+ types.BuiltinFunctionType,
+ classmethod,
+ staticmethod,
+ ),
+ )
+ and v is not None
+ }
+
+ @abstractmethod
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ """
+ Validate and prepare environment-specific headers and parameters.
+
+ Args:
+ headers: HTTP headers dictionary
+ model: Model name
+ messages: List of messages
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters
+ api_key: API key
+ api_base: API base URL
+
+ Returns:
+ Updated headers dictionary
+ """
+ pass
+
+ @abstractmethod
+ def get_complete_batch_url(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ model: str,
+ optional_params: Dict,
+ litellm_params: Dict,
+ data: CreateBatchRequest,
+ ) -> str:
+ """
+ Get the complete URL for batch creation request.
+
+ Args:
+ api_base: Base API URL
+ api_key: API key
+ model: Model name
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters
+ data: Batch creation request data
+
+ Returns:
+ Complete URL for the batch request
+ """
+ pass
+
+ @abstractmethod
+ def transform_create_batch_request(
+ self,
+ model: str,
+ create_batch_data: CreateBatchRequest,
+ optional_params: dict,
+ litellm_params: dict,
+ ) -> Union[bytes, str, Dict[str, Any]]:
+ """
+ Transform the batch creation request to provider-specific format.
+
+ Args:
+ model: Model name
+ create_batch_data: Batch creation request data
+ optional_params: Optional parameters
+ litellm_params: LiteLLM parameters
+
+ Returns:
+ Transformed request data
+ """
+ pass
+
+ @abstractmethod
+ def transform_create_batch_response(
+ self,
+ model: Optional[str],
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ litellm_params: dict,
+ ) -> LiteLLMBatch:
+ """
+ Transform provider-specific batch response to LiteLLM format.
+
+ Args:
+ model: Model name
+ raw_response: Raw HTTP response
+ logging_obj: Logging object
+ litellm_params: LiteLLM parameters
+
+ Returns:
+ LiteLLM batch object
+ """
+ pass
+
+ @abstractmethod
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[Dict, Headers]
+ ) -> "BaseLLMException":
+ """
+ Get the appropriate error class for this provider.
+
+ Args:
+ error_message: Error message
+ status_code: HTTP status code
+ headers: Response headers
+
+ Returns:
+ Provider-specific exception class
+ """
+ pass
diff --git a/litellm/llms/base_llm/files/transformation.py b/litellm/llms/base_llm/files/transformation.py
index 5c37a8b7547..35b76479cdc 100644
--- a/litellm/llms/base_llm/files/transformation.py
+++ b/litellm/llms/base_llm/files/transformation.py
@@ -35,6 +35,16 @@ class BaseFilesConfig(BaseConfig):
def custom_llm_provider(self) -> LlmProviders:
pass
+ @property
+ def file_upload_http_method(self) -> str:
+ """
+ HTTP method to use for file uploads.
+ Override this in provider configs if they need different methods.
+ Default is POST (used by most providers like OpenAI, Anthropic).
+ S3-based providers like Bedrock should return "PUT".
+ """
+ return "POST"
+
@abstractmethod
def get_supported_openai_params(
self, model: str
diff --git a/litellm/llms/bedrock/batches/transformation.py b/litellm/llms/bedrock/batches/transformation.py
new file mode 100644
index 00000000000..ce580ebc624
--- /dev/null
+++ b/litellm/llms/bedrock/batches/transformation.py
@@ -0,0 +1,254 @@
+import os
+import time
+from typing import Any, Dict, List, Literal, Optional, Union, cast
+
+from httpx import Headers, Response
+
+from litellm.llms.base_llm.batches.transformation import BaseBatchesConfig
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.types.llms.bedrock import (
+ BedrockBatchJobStatus,
+ BedrockCreateBatchRequest,
+ BedrockCreateBatchResponse,
+ BedrockInputDataConfig,
+ BedrockOutputDataConfig,
+ BedrockS3InputDataConfig,
+ BedrockS3OutputDataConfig,
+)
+from litellm.types.llms.openai import (
+ AllMessageValues,
+ CreateBatchRequest,
+)
+from litellm.types.utils import LiteLLMBatch, LlmProviders
+
+from ..base_aws_llm import BaseAWSLLM
+from ..common_utils import CommonBatchFilesUtils
+
+
+class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig):
+ """
+ Config for Bedrock Batches - handles batch job creation and management for Bedrock
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.common_utils = CommonBatchFilesUtils()
+
+ @property
+ def custom_llm_provider(self) -> LlmProviders:
+ return LlmProviders.BEDROCK
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ """
+ Validate and prepare environment for Bedrock batch requests.
+ AWS credentials are handled by BaseAWSLLM.
+ """
+ # Add any Bedrock-specific headers if needed
+ return headers
+
+ def get_complete_batch_url(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ model: str,
+ optional_params: Dict,
+ litellm_params: Dict,
+ data: CreateBatchRequest,
+ ) -> str:
+ """
+ Get the complete URL for Bedrock batch creation.
+ Bedrock batch jobs are created via the model invocation job API.
+ """
+ aws_region_name = self._get_aws_region_name(optional_params, model)
+
+ # Bedrock model invocation job endpoint
+ # Format: https://bedrock.{region}.amazonaws.com/model-invocation-job
+ bedrock_endpoint = f"https://bedrock.{aws_region_name}.amazonaws.com/model-invocation-job"
+
+ return bedrock_endpoint
+
+
+
+
+
+
+
+ def transform_create_batch_request(
+ self,
+ model: str,
+ create_batch_data: CreateBatchRequest,
+ optional_params: dict,
+ litellm_params: dict,
+ ) -> Dict[str, Any]:
+ """
+ Transform the batch creation request to Bedrock format.
+
+ Bedrock batch inference requires:
+ - modelId: The Bedrock model ID
+ - jobName: Unique name for the batch job
+ - inputDataConfig: Configuration for input data (S3 location)
+ - outputDataConfig: Configuration for output data (S3 location)
+ - roleArn: IAM role ARN for the batch job
+ """
+ # Get required parameters
+ input_file_id = create_batch_data.get("input_file_id")
+ if not input_file_id:
+ raise ValueError("input_file_id is required for Bedrock batch creation")
+
+ # Extract S3 information from file ID using common utility
+ input_bucket, input_key = self.common_utils.parse_s3_uri(input_file_id)
+
+ # Get output S3 configuration
+ output_bucket = litellm_params.get("s3_output_bucket_name") or os.getenv("AWS_S3_OUTPUT_BUCKET_NAME")
+ if not output_bucket:
+ # Use same bucket as input if no output bucket specified
+ output_bucket = input_bucket
+
+ # Get IAM role ARN
+ role_arn = (
+ litellm_params.get("aws_batch_role_arn")
+ or optional_params.get("aws_batch_role_arn")
+ or os.getenv("AWS_BATCH_ROLE_ARN")
+ )
+ if not role_arn:
+ raise ValueError(
+ "AWS IAM role ARN is required for Bedrock batch jobs. "
+ "Set 'aws_batch_role_arn' in litellm_params or AWS_BATCH_ROLE_ARN env var"
+ )
+
+ # Get the actual Bedrock model ID using common utility
+ bedrock_model_id = self.common_utils.extract_model_from_s3_file_path(input_file_id, optional_params)
+
+ if not bedrock_model_id:
+ raise ValueError("Could not determine Bedrock model ID. Ensure the model is specified in the input file or passed as a parameter.")
+
+ # Generate job name with the correct model ID using common utility
+ job_name = self.common_utils.generate_unique_job_name(bedrock_model_id, prefix="litellm")
+ output_key = f"litellm-batch-outputs/{job_name}/"
+
+ # Build input data config
+ input_data_config: BedrockInputDataConfig = {
+ "s3InputDataConfig": BedrockS3InputDataConfig(
+ s3Uri=f"s3://{input_bucket}/{input_key}"
+ )
+ }
+
+ # Build output data config
+ output_data_config: BedrockOutputDataConfig = {
+ "s3OutputDataConfig": BedrockS3OutputDataConfig(
+ s3Uri=f"s3://{output_bucket}/{output_key}"
+ )
+ }
+
+ # Create Bedrock batch request with proper typing
+ bedrock_request: BedrockCreateBatchRequest = {
+ "modelId": bedrock_model_id,
+ "jobName": job_name,
+ "inputDataConfig": input_data_config,
+ "outputDataConfig": output_data_config,
+ "roleArn": role_arn
+ }
+
+ # Add optional parameters if provided
+ completion_window = create_batch_data.get("completion_window")
+ if completion_window:
+ # Map OpenAI completion window to Bedrock timeout
+ # OpenAI uses "24h", Bedrock expects timeout in hours
+ if completion_window == "24h":
+ bedrock_request["timeoutDurationInHours"] = 24
+
+ # For Bedrock, we need to return a pre-signed request with AWS auth headers
+ # Use common utility for AWS signing
+ endpoint_url = f"https://bedrock.{self._get_aws_region_name(optional_params, model)}.amazonaws.com/model-invocation-job"
+ signed_headers, signed_data = self.common_utils.sign_aws_request(
+ service_name="bedrock",
+ data=bedrock_request,
+ endpoint_url=endpoint_url,
+ optional_params=optional_params,
+ method="POST"
+ )
+
+ # Return a pre-signed request format that the HTTP handler can use
+ return {
+ "method": "POST",
+ "url": endpoint_url,
+ "headers": signed_headers,
+ "data": signed_data.decode('utf-8')
+ }
+
+ def transform_create_batch_response(
+ self,
+ model: Optional[str],
+ raw_response: Response,
+ logging_obj: Any,
+ litellm_params: dict,
+ ) -> LiteLLMBatch:
+ """
+ Transform Bedrock batch creation response to LiteLLM format.
+ """
+ try:
+ response_data: BedrockCreateBatchResponse = raw_response.json()
+ except Exception as e:
+ raise ValueError(f"Failed to parse Bedrock batch response: {e}")
+
+ # Extract information from typed Bedrock response
+ job_arn = response_data.get("jobArn", "")
+ status: BedrockBatchJobStatus = response_data.get("status", "Submitted")
+
+ # Map Bedrock status to OpenAI-compatible status
+ status_mapping: Dict[BedrockBatchJobStatus, str] = {
+ "Submitted": "validating",
+ "InProgress": "in_progress",
+ "Completed": "completed",
+ "Failed": "failed",
+ "Stopping": "cancelling",
+ "Stopped": "cancelled"
+ }
+
+ openai_status = cast(Literal["validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"], status_mapping.get(status, "validating"))
+
+ # Get original request data from litellm_params if available
+ original_request = litellm_params.get("original_batch_request", {})
+
+ # Create LiteLLM batch object
+ return LiteLLMBatch(
+ id=job_arn, # Use ARN as the batch ID
+ object="batch",
+ endpoint=original_request.get("endpoint", "/v1/chat/completions"),
+ errors=None,
+ input_file_id=original_request.get("input_file_id", ""),
+ completion_window=original_request.get("completion_window", "24h"),
+ status=openai_status,
+ output_file_id=None, # Will be populated when job completes
+ error_file_id=None,
+ created_at=int(time.time()),
+ in_progress_at=int(time.time()) if status == "InProgress" else None,
+ expires_at=None,
+ finalizing_at=None,
+ completed_at=None,
+ failed_at=None,
+ expired_at=None,
+ cancelling_at=None,
+ cancelled_at=None,
+ request_counts=None,
+ metadata=original_request.get("metadata", {}),
+ )
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[Dict, Headers]
+ ) -> BaseLLMException:
+ """
+ Get Bedrock-specific error class using common utility.
+ """
+ return self.common_utils.get_error_class(error_message, status_code, headers)
+
+
diff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.py
index c76fc0a80c3..831a6da93b3 100644
--- a/litellm/llms/bedrock/common_utils.py
+++ b/litellm/llms/bedrock/common_utils.py
@@ -6,6 +6,9 @@ import json
import os
from typing import TYPE_CHECKING, Dict, List, Literal, Optional, Union
+if TYPE_CHECKING:
+ from litellm.types.llms.bedrock import BedrockCreateBatchRequest
+
import httpx
import litellm
@@ -608,3 +611,218 @@ def get_anthropic_beta_from_headers(headers: dict) -> List[str]:
# Split comma-separated values and strip whitespace
return [beta.strip() for beta in anthropic_beta_header.split(",")]
+
+
+class CommonBatchFilesUtils:
+ """
+ Common utilities for Bedrock batch and file operations.
+ Provides shared functionality to reduce code duplication between batches and files.
+ """
+
+ def __init__(self):
+ # Import here to avoid circular imports
+ from .base_aws_llm import BaseAWSLLM
+ self._base_aws = BaseAWSLLM()
+
+ def get_bedrock_model_id_from_litellm_model(self, model: str) -> str:
+ """
+ Extract the actual Bedrock model ID from LiteLLM model name.
+
+ Args:
+ model: LiteLLM model name (e.g., "bedrock/anthropic.claude-3-sonnet-20240229-v1:0")
+
+ Returns:
+ Bedrock model ID (e.g., "anthropic.claude-3-sonnet-20240229-v1:0")
+ """
+ if model.startswith("bedrock/"):
+ return model[8:] # Remove "bedrock/" prefix
+ return model
+
+ def parse_s3_uri(self, s3_uri: str) -> tuple:
+ """
+ Parse S3 URI into bucket and key components.
+
+ Args:
+ s3_uri: S3 URI (e.g., "s3://bucket/key/path")
+
+ Returns:
+ Tuple of (bucket, key)
+
+ Raises:
+ ValueError: If URI format is invalid
+ """
+ if not s3_uri.startswith("s3://"):
+ raise ValueError(f"Invalid S3 URI format: {s3_uri}")
+
+ s3_parts = s3_uri[5:].split("/", 1) # Remove "s3://" and split on first "/"
+ if len(s3_parts) != 2:
+ raise ValueError(f"Invalid S3 URI format: {s3_uri}")
+
+ return s3_parts[0], s3_parts[1] # bucket, key
+
+ def extract_model_from_s3_file_path(self, s3_uri: str, optional_params: dict) -> str:
+ """
+ Extract model ID from S3 file path.
+
+ The Bedrock file transformation creates S3 objects with the model name embedded:
+ Format: s3://bucket/litellm-bedrock-files-{model}-{uuid}.jsonl
+ """
+ # Check if model is provided in optional_params first
+ if "model" in optional_params and optional_params["model"]:
+ return self.get_bedrock_model_id_from_litellm_model(optional_params["model"])
+
+ # Extract model from S3 URI path
+ # Expected format: s3://bucket/litellm-bedrock-files-{model}-{uuid}.jsonl
+ try:
+ bucket, object_key = self.parse_s3_uri(s3_uri)
+
+ # Extract model from object key if it follows our naming pattern
+ if object_key.startswith("litellm-bedrock-files-"):
+ # Remove prefix and suffix to get model part
+ model_part = object_key[22:] # Remove "litellm-bedrock-files-"
+ # Find the last dash before the UUID
+ parts = model_part.split("-")
+ if len(parts) > 1:
+ # Reconstruct model name (everything except the last UUID part and .jsonl)
+ model_name = "-".join(parts[:-1])
+ if model_name.endswith(".jsonl"):
+ model_name = model_name[:-6] # Remove .jsonl
+ return model_name
+ except Exception:
+ pass
+
+ # Fallback to default model
+ return "anthropic.claude-3-5-sonnet-20240620-v1:0"
+
+ def sign_aws_request(
+ self,
+ service_name: str,
+ data: Union[str, dict, "BedrockCreateBatchRequest"],
+ endpoint_url: str,
+ optional_params: dict,
+ method: str = "POST",
+ ) -> tuple:
+ """
+ Sign AWS request using Signature Version 4.
+
+ Args:
+ service_name: AWS service name ("bedrock" or "s3")
+ data: Request data (string or dict)
+ endpoint_url: Full endpoint URL
+ optional_params: Optional parameters containing AWS credentials
+ method: HTTP method (default: POST)
+
+ Returns:
+ Tuple of (signed_headers, signed_data)
+ """
+ try:
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ except ImportError:
+ raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.")
+
+ # Get AWS credentials using existing methods
+ aws_region_name = self._base_aws._get_aws_region_name(
+ optional_params=optional_params, model=""
+ )
+ credentials = self._base_aws.get_credentials(
+ aws_access_key_id=optional_params.get("aws_access_key_id"),
+ aws_secret_access_key=optional_params.get("aws_secret_access_key"),
+ aws_session_token=optional_params.get("aws_session_token"),
+ aws_region_name=aws_region_name,
+ aws_session_name=optional_params.get("aws_session_name"),
+ aws_profile_name=optional_params.get("aws_profile_name"),
+ aws_role_name=optional_params.get("aws_role_name"),
+ aws_web_identity_token=optional_params.get("aws_web_identity_token"),
+ aws_sts_endpoint=optional_params.get("aws_sts_endpoint"),
+ )
+
+ # Prepare the request data
+ if isinstance(data, dict):
+ import json
+ request_data = json.dumps(data)
+ else:
+ request_data = data
+
+ # Prepare headers
+ headers = {"Content-Type": "application/json"}
+
+ # Create AWS request and sign it
+ sigv4 = SigV4Auth(credentials, service_name, aws_region_name)
+ request = AWSRequest(
+ method=method.upper(), url=endpoint_url, data=request_data, headers=headers
+ )
+ sigv4.add_auth(request)
+ prepped = request.prepare()
+
+ return dict(prepped.headers), request_data.encode('utf-8') if isinstance(request_data, str) else request_data
+
+ def generate_unique_job_name(self, model: str, prefix: str = "litellm") -> str:
+ """
+ Generate a unique job name for AWS services.
+ AWS services often have length limits, so this creates a concise name.
+
+ Args:
+ model: Model name to include in the job name
+ prefix: Prefix for the job name
+
+ Returns:
+ Unique job name (≤ 63 characters for Bedrock compatibility)
+ """
+ import fastuuid as uuid
+ unique_id = str(uuid.uuid4())[:8]
+ # Format: {prefix}-batch-{model}-{uuid}
+ # Example: litellm-batch-claude-266c398e
+ job_name = f"{prefix}-batch-{unique_id}"
+
+ return job_name
+
+ def get_s3_bucket_and_key_from_config(
+ self,
+ litellm_params: dict,
+ optional_params: dict,
+ bucket_env_var: str = "AWS_S3_BUCKET_NAME",
+ key_prefix: str = "litellm"
+ ) -> tuple:
+ """
+ Get S3 bucket and generate a unique key from configuration.
+
+ Args:
+ litellm_params: LiteLLM parameters
+ optional_params: Optional parameters
+ bucket_env_var: Environment variable name for bucket
+ key_prefix: Prefix for the S3 key
+
+ Returns:
+ Tuple of (bucket_name, object_key)
+ """
+ import time
+ import uuid
+
+ # Get bucket name
+ bucket_name = (
+ litellm_params.get("s3_bucket_name")
+ or optional_params.get("s3_bucket_name")
+ or os.getenv(bucket_env_var)
+ )
+ if not bucket_name:
+ raise ValueError(f"S3 bucket name is required. Set 's3_bucket_name' parameter or {bucket_env_var} env var")
+
+ # Generate unique object key
+ timestamp = int(time.time())
+ unique_id = str(uuid.uuid4())[:8]
+ object_key = f"{key_prefix}-{timestamp}-{unique_id}"
+
+ return bucket_name, object_key
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[Dict, httpx.Headers]
+ ) -> BaseLLMException:
+ """
+ Get Bedrock-specific error class.
+ """
+ return BedrockError(
+ status_code=status_code,
+ message=error_message,
+ headers=headers
+ )
diff --git a/litellm/llms/bedrock/files/transformation.py b/litellm/llms/bedrock/files/transformation.py
new file mode 100644
index 00000000000..83bbad7e1e8
--- /dev/null
+++ b/litellm/llms/bedrock/files/transformation.py
@@ -0,0 +1,607 @@
+import json
+import os
+import time
+import uuid
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from httpx import Headers, Response
+
+from litellm.litellm_core_utils.prompt_templates.common_utils import extract_file_data
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.llms.base_llm.files.transformation import (
+ BaseFilesConfig,
+ LiteLLMLoggingObj,
+)
+from litellm.types.llms.openai import (
+ AllMessageValues,
+ CreateFileRequest,
+ FileTypes,
+ OpenAICreateFileRequestOptionalParams,
+ OpenAIFileObject,
+ PathLike,
+)
+from litellm.types.utils import ExtractedFileData, LlmProviders
+
+from ..base_aws_llm import BaseAWSLLM
+from ..common_utils import BedrockError
+
+
+class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig):
+ """
+ Config for Bedrock Files - handles S3 uploads for Bedrock batch processing
+ """
+
+ def __init__(self):
+ self.jsonl_transformation = BedrockJsonlFilesTransformation()
+ super().__init__()
+
+ @property
+ def custom_llm_provider(self) -> LlmProviders:
+ return LlmProviders.BEDROCK
+
+ @property
+ def file_upload_http_method(self) -> str:
+ """
+ Bedrock files are uploaded to S3, which requires PUT requests
+ """
+ return "PUT"
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ # No additional headers needed for S3 uploads - AWS credentials handled by BaseAWSLLM
+ return headers
+
+
+
+ def _get_content_from_openai_file(self, openai_file_content: FileTypes) -> str:
+ """
+ Helper to extract content from various OpenAI file types and return as string.
+
+ Handles:
+ - Direct content (str, bytes, IO[bytes])
+ - Tuple formats: (filename, content, [content_type], [headers])
+ - PathLike objects
+ """
+ content: Union[str, bytes] = b""
+ # Extract file content from tuple if necessary
+ if isinstance(openai_file_content, tuple):
+ # Take the second element which is always the file content
+ file_content = openai_file_content[1]
+ else:
+ file_content = openai_file_content
+
+ # Handle different file content types
+ if isinstance(file_content, str):
+ # String content can be used directly
+ content = file_content
+ elif isinstance(file_content, bytes):
+ # Bytes content can be decoded
+ content = file_content
+ elif isinstance(file_content, PathLike): # PathLike
+ with open(str(file_content), "rb") as f:
+ content = f.read()
+ elif hasattr(file_content, "read"): # IO[bytes]
+ # File-like objects need to be read
+ content = file_content.read()
+
+ # Ensure content is string
+ if isinstance(content, bytes):
+ content = content.decode("utf-8")
+
+ return content
+
+ def _get_s3_object_name_from_batch_jsonl(
+ self,
+ openai_jsonl_content: List[Dict[str, Any]],
+ ) -> str:
+ """
+ Gets a unique S3 object name for the Bedrock batch processing job
+
+ named as: litellm-bedrock-files/{model}/{uuid}
+ """
+ _model = openai_jsonl_content[0].get("body", {}).get("model", "")
+ # Remove bedrock/ prefix if present
+ if _model.startswith("bedrock/"):
+ _model = _model[8:]
+ object_name = f"litellm-bedrock-files-{_model}-{uuid.uuid4()}.jsonl"
+ return object_name
+
+ def get_object_name(
+ self, extracted_file_data: ExtractedFileData, purpose: str
+ ) -> str:
+ """
+ Get the object name for the request
+ """
+ extracted_file_data_content = extracted_file_data.get("content")
+
+ if extracted_file_data_content is None:
+ raise ValueError("file content is required")
+
+ if purpose == "batch":
+ ## 1. If jsonl, check if there's a model name
+ file_content = self._get_content_from_openai_file(
+ extracted_file_data_content
+ )
+
+ # Split into lines and parse each line as JSON
+ openai_jsonl_content = [
+ json.loads(line) for line in file_content.splitlines() if line.strip()
+ ]
+ if len(openai_jsonl_content) > 0:
+ return self._get_s3_object_name_from_batch_jsonl(openai_jsonl_content)
+
+ ## 2. If not jsonl, return the filename
+ filename = extracted_file_data.get("filename")
+ if filename:
+ return filename
+ ## 3. If no file name, return timestamp
+ return str(int(time.time()))
+
+ def get_complete_file_url(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ model: str,
+ optional_params: Dict,
+ litellm_params: Dict,
+ data: CreateFileRequest,
+ ) -> str:
+ """
+ Get the complete S3 URL for the file upload request
+ """
+ bucket_name = litellm_params.get("s3_bucket_name") or os.getenv("AWS_S3_BUCKET_NAME")
+ if not bucket_name:
+ raise ValueError("S3 bucket_name is required. Set 's3_bucket_name' in litellm_params or AWS_S3_BUCKET_NAME env var")
+
+ aws_region_name = self._get_aws_region_name(optional_params, model)
+
+ file_data = data.get("file")
+ purpose = data.get("purpose")
+ if file_data is None:
+ raise ValueError("file is required")
+ if purpose is None:
+ raise ValueError("purpose is required")
+ extracted_file_data = extract_file_data(file_data)
+ object_name = self.get_object_name(extracted_file_data, purpose)
+
+ # S3 endpoint URL format
+ s3_endpoint_url = optional_params.get("s3_endpoint_url") or f"https://s3.{aws_region_name}.amazonaws.com"
+
+ return f"{s3_endpoint_url}/{bucket_name}/{object_name}"
+
+ def get_supported_openai_params(
+ self, model: str
+ ) -> List[OpenAICreateFileRequestOptionalParams]:
+ return []
+
+ def map_openai_params(
+ self,
+ non_default_params: dict,
+ optional_params: dict,
+ model: str,
+ drop_params: bool,
+ ) -> dict:
+ return optional_params
+
+ def _get_bedrock_provider_from_model(self, model: str) -> Optional[str]:
+ """
+ Extract provider from Bedrock model name
+ """
+ if model.startswith("anthropic."):
+ return "anthropic"
+ elif model.startswith("cohere."):
+ return "cohere"
+ elif model.startswith("meta.") or model.startswith("llama"):
+ return "meta"
+ elif model.startswith("mistral."):
+ return "mistral"
+ elif model.startswith("ai21."):
+ return "ai21"
+ elif model.startswith("amazon."):
+ return "amazon"
+ else:
+ return None
+
+ def _map_openai_to_bedrock_params(
+ self,
+ openai_request_body: Dict[str, Any],
+ provider: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Transform OpenAI request body to Bedrock-compatible modelInput parameters using existing transformation logic
+ """
+ _model = openai_request_body.get("model", "")
+ messages = openai_request_body.get("messages", [])
+
+ # Use existing Anthropic transformation logic for Anthropic models
+ if provider == "anthropic":
+ from litellm.llms.bedrock.chat.invoke_transformations.anthropic_claude3_transformation import (
+ AmazonAnthropicClaudeConfig,
+ )
+
+ anthropic_config = AmazonAnthropicClaudeConfig()
+
+ # Extract optional params (everything except model and messages)
+ optional_params = {k: v for k, v in openai_request_body.items() if k not in ["model", "messages"]}
+
+ # Transform using existing Anthropic logic
+ bedrock_params = anthropic_config.transform_request(
+ model=_model,
+ messages=messages,
+ optional_params=optional_params,
+ litellm_params={},
+ headers={}
+ )
+
+ return bedrock_params
+ else:
+ # For other providers, use basic mapping
+ bedrock_params = {
+ "messages": messages,
+ **{k: v for k, v in openai_request_body.items() if k not in ["model", "messages"]}
+ }
+ return bedrock_params
+
+ def _transform_openai_jsonl_content_to_bedrock_jsonl_content(
+ self, openai_jsonl_content: List[Dict[str, Any]]
+ ) -> List[Dict[str, Any]]:
+ """
+ Transforms OpenAI JSONL content to Bedrock batch format
+
+ Bedrock batch format: { "recordId": "alphanumeric string", "modelInput": {JSON body} }
+ Example:
+ {
+ "recordId": "CALL0000001",
+ "modelInput": {
+ "anthropic_version": "bedrock-2023-05-31",
+ "max_tokens": 1024,
+ "messages": [
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "Hello"}]
+ }
+ ]
+ }
+ }
+ """
+
+ bedrock_jsonl_content = []
+ for idx, _openai_jsonl_content in enumerate(openai_jsonl_content):
+ # Extract the request body from OpenAI format
+ openai_body = _openai_jsonl_content.get("body", {})
+ model = openai_body.get("model", "")
+
+ # Determine provider from model name
+ provider = self._get_bedrock_provider_from_model(model)
+
+ # Transform to Bedrock modelInput format
+ model_input = self._map_openai_to_bedrock_params(
+ openai_request_body=openai_body,
+ provider=provider
+ )
+
+ # Create Bedrock batch record
+ record_id = _openai_jsonl_content.get("custom_id", f"CALL{str(idx).zfill(7)}")
+ bedrock_record = {
+ "recordId": record_id,
+ "modelInput": model_input
+ }
+
+ bedrock_jsonl_content.append(bedrock_record)
+ return bedrock_jsonl_content
+
+ def transform_create_file_request(
+ self,
+ model: str,
+ create_file_data: CreateFileRequest,
+ optional_params: dict,
+ litellm_params: dict,
+ ) -> Union[bytes, str, dict]:
+ """
+ Transform file request and return a pre-signed request for S3.
+ This keeps the HTTP handler clean by doing all the signing here.
+ """
+ file_data = create_file_data.get("file")
+ if file_data is None:
+ raise ValueError("file is required")
+ extracted_file_data = extract_file_data(file_data)
+ extracted_file_data_content = extracted_file_data.get("content")
+
+ # Get and transform the file content
+ if (
+ create_file_data.get("purpose") == "batch"
+ and extracted_file_data.get("content_type") == "application/jsonl"
+ and extracted_file_data_content is not None
+ ):
+ ## Transform JSONL content to Bedrock format
+ original_file_content = self._get_content_from_openai_file(
+ extracted_file_data_content
+ )
+ openai_jsonl_content = [
+ json.loads(line) for line in original_file_content.splitlines() if line.strip()
+ ]
+ bedrock_jsonl_content = (
+ self._transform_openai_jsonl_content_to_bedrock_jsonl_content(
+ openai_jsonl_content
+ )
+ )
+ file_content = "\n".join(json.dumps(item) for item in bedrock_jsonl_content)
+ elif isinstance(extracted_file_data_content, bytes):
+ file_content = extracted_file_data_content.decode('utf-8')
+ elif isinstance(extracted_file_data_content, str):
+ file_content = extracted_file_data_content
+ else:
+ raise ValueError("Unsupported file content type")
+
+ # Get the S3 URL for upload
+ api_base = self.get_complete_file_url(
+ api_base=None,
+ api_key=None,
+ model=model,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ data=create_file_data,
+ )
+
+ # Sign the request and return a pre-signed request object
+ signed_headers, signed_body = self._sign_s3_request(
+ content=file_content,
+ api_base=api_base,
+ optional_params=optional_params,
+ )
+
+ # Return a dict that tells the HTTP handler exactly what to do
+ return {
+ "method": "PUT",
+ "url": api_base,
+ "headers": signed_headers,
+ "data": signed_body or file_content,
+ }
+
+ def _sign_s3_request(
+ self,
+ content: str,
+ api_base: str,
+ optional_params: dict,
+ ) -> Tuple[dict, str]:
+ """
+ Sign S3 PUT request using the same proven logic as S3Logger.
+ Reuses the exact pattern from litellm/integrations/s3_v2.py
+ """
+ try:
+ import hashlib
+
+ import requests
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ except ImportError:
+ raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.")
+
+ # Get AWS credentials using existing methods
+ aws_region_name = self._get_aws_region_name(
+ optional_params=optional_params, model=""
+ )
+ credentials = self.get_credentials(
+ aws_access_key_id=optional_params.get("aws_access_key_id"),
+ aws_secret_access_key=optional_params.get("aws_secret_access_key"),
+ aws_session_token=optional_params.get("aws_session_token"),
+ aws_region_name=aws_region_name,
+ aws_session_name=optional_params.get("aws_session_name"),
+ aws_profile_name=optional_params.get("aws_profile_name"),
+ aws_role_name=optional_params.get("aws_role_name"),
+ aws_web_identity_token=optional_params.get("aws_web_identity_token"),
+ aws_sts_endpoint=optional_params.get("aws_sts_endpoint"),
+ )
+
+ # Calculate SHA256 hash of the content (REQUIRED for S3)
+ content_hash = hashlib.sha256(content.encode("utf-8")).hexdigest()
+
+ # Prepare headers with required S3 headers (same as s3_v2.py)
+ request_headers = {
+ "Content-Type": "application/json", # JSONL files are JSON content
+ "x-amz-content-sha256": content_hash, # REQUIRED by S3
+ "Content-Language": "en",
+ "Cache-Control": "private, immutable, max-age=31536000, s-maxage=0",
+ }
+
+ # Use requests.Request to prepare the request (same pattern as s3_v2.py)
+ req = requests.Request("PUT", api_base, data=content, headers=request_headers)
+ prepped = req.prepare()
+
+ # Sign the request with S3 service
+ aws_request = AWSRequest(
+ method=prepped.method,
+ url=prepped.url,
+ data=prepped.body,
+ headers=prepped.headers,
+ )
+
+ # Get region name for non-LLM API calls (same as s3_v2.py)
+ signing_region = self.get_aws_region_name_for_non_llm_api_calls(
+ aws_region_name=aws_region_name
+ )
+
+ SigV4Auth(credentials, "s3", signing_region).add_auth(aws_request)
+
+ # Return signed headers and body
+ signed_body = aws_request.body
+ if isinstance(signed_body, bytes):
+ signed_body = signed_body.decode('utf-8')
+ elif signed_body is None:
+ signed_body = content # Fallback to original content
+
+ return dict(aws_request.headers), signed_body
+
+ def transform_create_file_response(
+ self,
+ model: Optional[str],
+ raw_response: Response,
+ logging_obj: LiteLLMLoggingObj,
+ litellm_params: dict,
+ ) -> OpenAIFileObject:
+ """
+ Transform S3 File upload response into OpenAI-style FileObject
+ """
+ # For S3 uploads, we typically get an ETag and other metadata
+ response_headers = raw_response.headers
+
+ # Extract S3 object information from the response
+ # S3 PUT object returns ETag and other metadata in headers
+ content_length = response_headers.get("Content-Length", "0")
+
+ # Extract bucket and key from the request URL or litellm_params
+ bucket_name = litellm_params.get("s3_bucket_name") or os.getenv("AWS_S3_BUCKET_NAME")
+
+ # Generate file ID in S3 format
+ object_key = getattr(logging_obj, 'object_key', None) or f"file-{int(time.time())}"
+ file_id = f"s3://{bucket_name}/{object_key}"
+
+ # Extract filename from object key
+ filename = object_key.split("/")[-1] if "/" in object_key else object_key
+
+ return OpenAIFileObject(
+ purpose="batch", # Default purpose for Bedrock files
+ id=file_id,
+ filename=filename,
+ created_at=int(time.time()), # Current timestamp
+ status="uploaded",
+ bytes=int(content_length) if content_length.isdigit() else 0,
+ object="file",
+ )
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[Dict, Headers]
+ ) -> BaseLLMException:
+ return BedrockError(
+ status_code=status_code, message=error_message, headers=headers
+ )
+
+
+class BedrockJsonlFilesTransformation:
+ """
+ Transforms OpenAI /v1/files/* requests to Bedrock S3 file uploads for batch processing
+ """
+
+ def transform_openai_file_content_to_bedrock_file_content(
+ self, openai_file_content: Optional[FileTypes] = None
+ ) -> Tuple[str, str]:
+ """
+ Transforms OpenAI FileContentRequest to Bedrock S3 file format
+ """
+
+ if openai_file_content is None:
+ raise ValueError("contents of file are None")
+ # Read the content of the file
+ file_content = self._get_content_from_openai_file(openai_file_content)
+
+ # Split into lines and parse each line as JSON
+ openai_jsonl_content = [
+ json.loads(line) for line in file_content.splitlines() if line.strip()
+ ]
+ bedrock_jsonl_content = (
+ self._transform_openai_jsonl_content_to_bedrock_jsonl_content(
+ openai_jsonl_content
+ )
+ )
+ bedrock_jsonl_string = "\n".join(
+ json.dumps(item) for item in bedrock_jsonl_content
+ )
+ object_name = self._get_s3_object_name(
+ openai_jsonl_content=openai_jsonl_content
+ )
+ return bedrock_jsonl_string, object_name
+
+ def _transform_openai_jsonl_content_to_bedrock_jsonl_content(
+ self, openai_jsonl_content: List[Dict[str, Any]]
+ ):
+ """
+ Delegate to the main BedrockFilesConfig transformation method
+ """
+ config = BedrockFilesConfig()
+ return config._transform_openai_jsonl_content_to_bedrock_jsonl_content(openai_jsonl_content)
+
+ def _get_s3_object_name(
+ self,
+ openai_jsonl_content: List[Dict[str, Any]],
+ ) -> str:
+ """
+ Gets a unique S3 object name for the Bedrock batch processing job
+
+ named as: litellm-bedrock-files-{model}-{uuid}
+ """
+ _model = openai_jsonl_content[0].get("body", {}).get("model", "")
+ # Remove bedrock/ prefix if present
+ if _model.startswith("bedrock/"):
+ _model = _model[8:]
+ object_name = f"litellm-bedrock-files-{_model}-{uuid.uuid4()}.jsonl"
+ return object_name
+
+
+
+ def _get_content_from_openai_file(self, openai_file_content: FileTypes) -> str:
+ """
+ Helper to extract content from various OpenAI file types and return as string.
+
+ Handles:
+ - Direct content (str, bytes, IO[bytes])
+ - Tuple formats: (filename, content, [content_type], [headers])
+ - PathLike objects
+ """
+ content: Union[str, bytes] = b""
+ # Extract file content from tuple if necessary
+ if isinstance(openai_file_content, tuple):
+ # Take the second element which is always the file content
+ file_content = openai_file_content[1]
+ else:
+ file_content = openai_file_content
+
+ # Handle different file content types
+ if isinstance(file_content, str):
+ # String content can be used directly
+ content = file_content
+ elif isinstance(file_content, bytes):
+ # Bytes content can be decoded
+ content = file_content
+ elif isinstance(file_content, PathLike): # PathLike
+ with open(str(file_content), "rb") as f:
+ content = f.read()
+ elif hasattr(file_content, "read"): # IO[bytes]
+ # File-like objects need to be read
+ content = file_content.read()
+
+ # Ensure content is string
+ if isinstance(content, bytes):
+ content = content.decode("utf-8")
+
+ return content
+
+ def transform_s3_bucket_response_to_openai_file_object(
+ self, create_file_data: CreateFileRequest, s3_upload_response: Dict[str, Any]
+ ) -> OpenAIFileObject:
+ """
+ Transforms S3 Bucket upload file response to OpenAI FileObject
+ """
+ # S3 response typically contains ETag, key, etc.
+ object_key = s3_upload_response.get("Key", "")
+ bucket_name = s3_upload_response.get("Bucket", "")
+
+ # Extract filename from object key
+ filename = object_key.split("/")[-1] if "/" in object_key else object_key
+
+ return OpenAIFileObject(
+ purpose=create_file_data.get("purpose", "batch"),
+ id=f"s3://{bucket_name}/{object_key}",
+ filename=filename,
+ created_at=int(time.time()), # Current timestamp
+ status="uploaded",
+ bytes=s3_upload_response.get("ContentLength", 0),
+ object="file",
+ )
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 2faea53901c..13133a56aad 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -28,6 +28,7 @@ from litellm.llms.base_llm.audio_transcription.transformation import (
BaseAudioTranscriptionConfig,
)
from litellm.llms.base_llm.base_model_iterator import MockResponseIterator
+from litellm.llms.base_llm.batches.transformation import BaseBatchesConfig
from litellm.llms.base_llm.chat.transformation import BaseConfig
from litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig
from litellm.llms.base_llm.files.transformation import BaseFilesConfig
@@ -58,6 +59,7 @@ from litellm.types.llms.anthropic_messages.anthropic_response import (
AnthropicMessagesResponse,
)
from litellm.types.llms.openai import (
+ CreateBatchRequest,
CreateFileRequest,
OpenAIFileObject,
ResponseInputParam,
@@ -66,7 +68,12 @@ from litellm.types.llms.openai import (
from litellm.types.rerank import OptionalRerankParams, RerankResponse
from litellm.types.responses.main import DeleteResponseResult
from litellm.types.router import GenericLiteLLMParams
-from litellm.types.utils import EmbeddingResponse, FileTypes, TranscriptionResponse
+from litellm.types.utils import (
+ EmbeddingResponse,
+ FileTypes,
+ LiteLLMBatch,
+ TranscriptionResponse,
+)
from litellm.types.vector_stores import (
VectorStoreCreateOptionalRequestParams,
VectorStoreCreateResponse,
@@ -2212,15 +2219,38 @@ class BaseLLMHTTPHandler:
else:
sync_httpx_client = client
- if isinstance(transformed_request, str) or isinstance(
- transformed_request, bytes
- ):
- upload_response = sync_httpx_client.post(
- url=api_base,
- headers=headers,
- data=transformed_request,
+ if isinstance(transformed_request, dict) and "method" in transformed_request:
+ # Handle pre-signed requests (e.g., from Bedrock S3 uploads)
+ upload_response = getattr(sync_httpx_client, transformed_request["method"].lower())(
+ url=transformed_request["url"],
+ headers=transformed_request["headers"],
+ data=transformed_request["data"],
timeout=timeout,
)
+ elif isinstance(transformed_request, str) or isinstance(
+ transformed_request, bytes
+ ):
+ # Handle traditional file uploads
+ # Ensure transformed_request is a string for httpx compatibility
+ if isinstance(transformed_request, bytes):
+ transformed_request = transformed_request.decode('utf-8')
+
+ # Use the HTTP method specified by the provider config
+ http_method = provider_config.file_upload_http_method.upper()
+ if http_method == "PUT":
+ upload_response = sync_httpx_client.put(
+ url=api_base,
+ headers=headers,
+ data=transformed_request,
+ timeout=timeout,
+ )
+ else: # Default to POST
+ upload_response = sync_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ data=transformed_request,
+ timeout=timeout,
+ )
else:
try:
# Step 1: Initial request to get upload URL
@@ -2280,16 +2310,52 @@ class BaseLLMHTTPHandler:
)
else:
async_httpx_client = client
+
+ #########################################################
+ # Debug Logging
+ #########################################################
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "complete_input_dict": transformed_request,
+ "api_base": api_base,
+ "headers": headers,
+ },
+ )
- if isinstance(transformed_request, str) or isinstance(
- transformed_request, bytes
- ):
- upload_response = await async_httpx_client.post(
- url=api_base,
- headers=headers,
- data=transformed_request,
+ if isinstance(transformed_request, dict) and "method" in transformed_request:
+ # Handle pre-signed requests (e.g., from Bedrock S3 uploads)
+ upload_response = await getattr(async_httpx_client, transformed_request["method"].lower())(
+ url=transformed_request["url"],
+ headers=transformed_request["headers"],
+ data=transformed_request["data"],
timeout=timeout,
)
+ elif isinstance(transformed_request, str) or isinstance(
+ transformed_request, bytes
+ ):
+ # Handle traditional file uploads
+ # Ensure transformed_request is a string for httpx compatibility
+ if isinstance(transformed_request, bytes):
+ transformed_request = transformed_request.decode('utf-8')
+
+ # Use the HTTP method specified by the provider config
+ http_method = provider_config.file_upload_http_method.upper()
+ if http_method == "PUT":
+ upload_response = await async_httpx_client.put(
+ url=api_base,
+ headers=headers,
+ data=transformed_request,
+ timeout=timeout,
+ )
+ else: # Default to POST
+ upload_response = await async_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ data=transformed_request,
+ timeout=timeout,
+ )
else:
try:
# Step 1: Initial request to get upload URL
@@ -2330,6 +2396,188 @@ class BaseLLMHTTPHandler:
litellm_params=litellm_params,
)
+ def create_batch(
+ self,
+ create_batch_data: "CreateBatchRequest",
+ litellm_params: dict,
+ provider_config: "BaseBatchesConfig",
+ headers: dict,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ logging_obj: "LiteLLMLoggingObj",
+ _is_async: bool = False,
+ client: Optional[Union["HTTPHandler", "AsyncHTTPHandler"]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Union["LiteLLMBatch", Coroutine[Any, Any, "LiteLLMBatch"]]:
+ """
+ Creates a batch using provider-specific batch creation process
+ """
+ # get config from model, custom llm provider
+ headers = provider_config.validate_environment(
+ api_key=api_key,
+ headers=headers,
+ model="",
+ messages=[],
+ optional_params={},
+ litellm_params=litellm_params,
+ )
+
+ api_base = provider_config.get_complete_batch_url(
+ api_base=api_base,
+ api_key=api_key,
+ model="",
+ optional_params={},
+ litellm_params=litellm_params,
+ data=create_batch_data,
+ )
+ if api_base is None:
+ raise ValueError("api_base is required for create_batch")
+
+ # Get the transformed request data
+ transformed_request = provider_config.transform_create_batch_request(
+ model="",
+ create_batch_data=create_batch_data,
+ litellm_params=litellm_params,
+ optional_params={},
+ )
+
+ if _is_async:
+ return self.async_create_batch(
+ transformed_request=transformed_request,
+ litellm_params=litellm_params,
+ provider_config=provider_config,
+ headers=headers,
+ api_base=api_base,
+ logging_obj=logging_obj,
+ client=client,
+ timeout=timeout,
+ create_batch_data=create_batch_data,
+ )
+
+ if client is None or not isinstance(client, HTTPHandler):
+ sync_httpx_client = _get_httpx_client()
+ else:
+ sync_httpx_client = client
+
+ try:
+ if isinstance(transformed_request, dict) and "method" in transformed_request:
+ # Handle pre-signed requests (e.g., from Bedrock with AWS auth)
+ batch_response = getattr(sync_httpx_client, transformed_request["method"].lower())(
+ url=transformed_request["url"],
+ headers=transformed_request["headers"],
+ data=transformed_request["data"],
+ timeout=timeout,
+ )
+ elif isinstance(transformed_request, dict):
+ # For other providers that use JSON requests
+ batch_response = sync_httpx_client.post(
+ url=api_base,
+ headers={**headers, "Content-Type": "application/json"},
+ json=transformed_request,
+ timeout=timeout,
+ )
+ else:
+ # Handle other request types if needed
+ batch_response = sync_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ data=transformed_request,
+ timeout=timeout,
+ )
+ except Exception as e:
+ verbose_logger.exception(f"Error creating batch: {e}")
+ raise self._handle_error(
+ e=e,
+ provider_config=provider_config,
+ )
+
+ # Store original request for response transformation
+ litellm_params_with_request = {**litellm_params, "original_batch_request": create_batch_data}
+
+ return provider_config.transform_create_batch_response(
+ model=None,
+ raw_response=batch_response,
+ logging_obj=logging_obj,
+ litellm_params=litellm_params_with_request,
+ )
+
+ async def async_create_batch(
+ self,
+ transformed_request: Union[bytes, str, dict],
+ litellm_params: dict,
+ provider_config: "BaseBatchesConfig",
+ headers: dict,
+ api_base: str,
+ logging_obj: "LiteLLMLoggingObj",
+ client: Optional[Union["HTTPHandler", "AsyncHTTPHandler"]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ create_batch_data: Optional["CreateBatchRequest"] = None,
+ ):
+ """
+ Async version of create_batch
+ """
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=provider_config.custom_llm_provider
+ )
+ else:
+ async_httpx_client = client
+
+ #########################################################
+ # Debug Logging
+ #########################################################
+ logging_obj.pre_call(
+ input="",
+ api_key="",
+ additional_args={
+ "complete_input_dict": transformed_request,
+ "api_base": api_base,
+ "headers": headers,
+ },
+ )
+
+ try:
+ if isinstance(transformed_request, dict) and "method" in transformed_request:
+ # Handle pre-signed requests (e.g., from Bedrock with AWS auth)
+ batch_response = await getattr(async_httpx_client, transformed_request["method"].lower())(
+ url=transformed_request["url"],
+ headers=transformed_request["headers"],
+ data=transformed_request["data"],
+ timeout=timeout,
+ )
+ elif isinstance(transformed_request, dict):
+ # For other providers that use JSON requests
+ batch_response = await async_httpx_client.post(
+ url=api_base,
+ headers={**headers, "Content-Type": "application/json"},
+ json=transformed_request,
+ timeout=timeout,
+ )
+ else:
+ # Handle other request types if needed
+ batch_response = await async_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ data=transformed_request,
+ timeout=timeout,
+ )
+ except Exception as e:
+ verbose_logger.exception(f"Error creating batch: {e}")
+ raise self._handle_error(
+ e=e,
+ provider_config=provider_config,
+ )
+
+ # Store original request for response transformation (for async version)
+ litellm_params_with_request = {**litellm_params, "original_batch_request": create_batch_data or {}}
+
+ return provider_config.transform_create_batch_response(
+ model=None,
+ raw_response=batch_response,
+ logging_obj=logging_obj,
+ litellm_params=litellm_params_with_request,
+ )
+
def list_files(self):
"""
Lists all files
@@ -2381,6 +2629,7 @@ class BaseLLMHTTPHandler:
BaseVectorStoreConfig,
BaseGoogleGenAIGenerateContentConfig,
BaseAnthropicMessagesConfig,
+ BaseBatchesConfig,
"BasePassthroughConfig",
],
):
diff --git a/litellm/types/llms/bedrock.py b/litellm/types/llms/bedrock.py
index 068c9db035b..5853f9de2aa 100644
--- a/litellm/types/llms/bedrock.py
+++ b/litellm/types/llms/bedrock.py
@@ -573,3 +573,84 @@ class AmazonDeepSeekR1StreamingResponse(TypedDict):
generation_token_count: int
stop_reason: Optional[str]
prompt_token_count: int
+
+
+################ Bedrock Batch Types #################
+
+
+class BedrockS3InputDataConfig(TypedDict):
+ """S3 input data configuration for Bedrock batch jobs."""
+ s3Uri: str
+
+
+class BedrockInputDataConfig(TypedDict):
+ """Input data configuration for Bedrock batch jobs."""
+ s3InputDataConfig: BedrockS3InputDataConfig
+
+
+class BedrockS3OutputDataConfig(TypedDict):
+ """S3 output data configuration for Bedrock batch jobs."""
+ s3Uri: str
+
+
+class BedrockOutputDataConfig(TypedDict):
+ """Output data configuration for Bedrock batch jobs."""
+ s3OutputDataConfig: BedrockS3OutputDataConfig
+
+
+class BedrockCreateBatchRequest(TypedDict, total=False):
+ """
+ Request structure for creating a Bedrock batch inference job.
+
+ Reference: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateModelInvocationJob.html
+ """
+ jobName: str
+ roleArn: str
+ modelId: str
+ inputDataConfig: BedrockInputDataConfig
+ outputDataConfig: BedrockOutputDataConfig
+ timeoutDurationInHours: Optional[int]
+ clientRequestToken: Optional[str]
+ tags: Optional[List[dict]]
+
+
+BedrockBatchJobStatus = Literal[
+ "Submitted",
+ "InProgress",
+ "Completed",
+ "Failed",
+ "Stopping",
+ "Stopped"
+]
+
+
+class BedrockCreateBatchResponse(TypedDict):
+ """
+ Response structure from creating a Bedrock batch inference job.
+
+ Reference: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateModelInvocationJob.html
+ """
+ jobArn: str
+ jobName: str
+ status: BedrockBatchJobStatus
+
+
+class BedrockGetBatchResponse(TypedDict, total=False):
+ """
+ Response structure from getting a Bedrock batch inference job.
+
+ Reference: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_GetModelInvocationJob.html
+ """
+ jobArn: str
+ jobName: str
+ modelId: str
+ roleArn: str
+ status: BedrockBatchJobStatus
+ message: Optional[str]
+ submitTime: Optional[str]
+ lastModifiedTime: Optional[str]
+ endTime: Optional[str]
+ inputDataConfig: BedrockInputDataConfig
+ outputDataConfig: BedrockOutputDataConfig
+ timeoutDurationInHours: Optional[int]
+ clientRequestToken: Optional[str]
diff --git a/litellm/types/router.py b/litellm/types/router.py
index 864fdbf79b8..8bed2bdccda 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -216,6 +216,10 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
auto_router_default_model: Optional[str] = None
auto_router_embedding_model: Optional[str] = None
+ # Batch/File API Params
+ s3_bucket_name: Optional[str] = None
+ gcs_bucket_name: Optional[str] = None
+
def __init__(
self,
custom_llm_provider: Optional[str] = None,
@@ -265,6 +269,9 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
auto_router_config: Optional[str] = None,
auto_router_default_model: Optional[str] = None,
auto_router_embedding_model: Optional[str] = None,
+ # Batch/File API Params
+ s3_bucket_name: Optional[str] = None,
+ gcs_bucket_name: Optional[str] = None,
**params,
):
args = locals()
diff --git a/litellm/utils.py b/litellm/utils.py
index 405d4cb98e4..1c70f894d52 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -234,6 +234,7 @@ from litellm.llms.base_llm.base_utils import (
BaseLLMModelInfo,
type_to_response_format_param,
)
+from litellm.llms.base_llm.batches.transformation import BaseBatchesConfig
from litellm.llms.base_llm.chat.transformation import BaseConfig
from litellm.llms.base_llm.completion.transformation import BaseTextCompletionConfig
from litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig
@@ -7287,6 +7288,20 @@ class ProviderConfigManager:
from litellm.llms.vertex_ai.files.transformation import VertexAIFilesConfig
return VertexAIFilesConfig()
+ elif LlmProviders.BEDROCK == provider:
+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig
+
+ return BedrockFilesConfig()
+ return None
+
+ @staticmethod
+ def get_provider_batches_config(
+ model: str,
+ provider: LlmProviders,
+ ) -> Optional[BaseBatchesConfig]:
+ if LlmProviders.BEDROCK == provider:
+ from litellm.llms.bedrock.batches.transformation import BedrockBatchesConfig
+ return BedrockBatchesConfig()
return None
@staticmethod
diff --git a/tests/batches_tests/bedrock_batch_completions.jsonl b/tests/batches_tests/bedrock_batch_completions.jsonl
new file mode 100644
index 00000000000..3037b1031ea
--- /dev/null
+++ b/tests/batches_tests/bedrock_batch_completions.jsonl
@@ -0,0 +1,3 @@
+{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
+{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
+
diff --git a/tests/batches_tests/test_bedrock_files_and_batches.py b/tests/batches_tests/test_bedrock_files_and_batches.py
new file mode 100644
index 00000000000..edf8c3c7745
--- /dev/null
+++ b/tests/batches_tests/test_bedrock_files_and_batches.py
@@ -0,0 +1,70 @@
+
+# What is this?
+## Unit Tests for OpenAI Batches API
+import asyncio
+import json
+import os
+import sys
+import traceback
+import tempfile
+from dotenv import load_dotenv
+
+load_dotenv()
+sys.path.insert(
+ 0, os.path.abspath("../..")
+) # Adds the parent directory to the system-path
+
+
+import pytest
+from typing import Optional
+import litellm
+
+
+async def test_async_create_file():
+ """
+ 1. Create File for Batch completion
+ 2. Create Batch Request
+ 3. Retrieve the specific batch
+ """
+ litellm._turn_on_debug()
+ print("Testing async create batch")
+
+ file_name = "bedrock_batch_completions.jsonl"
+ _current_dir = os.path.dirname(os.path.abspath(__file__))
+ file_path = os.path.join(_current_dir, file_name)
+ file_obj = await litellm.acreate_file(
+ file=open(file_path, "rb"),
+ purpose="batch",
+ custom_llm_provider="bedrock",
+ s3_bucket_name="litellm-proxy",
+ )
+
+async def test_async_file_and_batch():
+ """
+ Test file retrieval
+ """
+ litellm._turn_on_debug()
+ file_name = "bedrock_batch_completions.jsonl"
+ _current_dir = os.path.dirname(os.path.abspath(__file__))
+ file_path = os.path.join(_current_dir, file_name)
+ file_obj = await litellm.acreate_file(
+ file=open(file_path, "rb"),
+ purpose="batch",
+ custom_llm_provider="bedrock",
+ s3_bucket_name="litellm-proxy",
+ )
+ print("CREATED FILE RESPONSE=", file_obj)
+
+ # create batch
+ create_batch_response = await litellm.acreate_batch(
+ completion_window="24h",
+ endpoint="/v1/chat/completions",
+ input_file_id=file_obj.id,
+ metadata={"key1": "value1", "key2": "value2"},
+ custom_llm_provider="bedrock",
+ aws_batch_role_arn="arn:aws:iam::888602223428:role/service-role/AmazonBedrockExecutionRoleForAgents_BB9HNW6V4CV"
+ )
+ print("CREATED BATCH RESPONSE=", create_batch_response)
+