Skip to content

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

Merge origin/litellm_internal_staging into fix/bedrock-cancel-batch

mateo-berri776015248785
diff --cc litellm/batches/main.py
index 9d4cb29e926,ce52c12818e..365f134e9aa
--- a/litellm/batches/main.py
+++ b/litellm/batches/main.py
@@@ -943,13 -869,13 +869,13 @@@ async def acancel_batch
def cancel_batch(
batch_id: str,
- model: Optional[str] = None,
- custom_llm_provider: Union[Literal["openai", "azure", "vertex_ai", "bedrock"], str] = "openai",
- metadata: Optional[Dict[str, str]] = None,
- extra_headers: Optional[Dict[str, str]] = None,
- extra_body: Optional[Dict[str, str]] = None,
+ model: str | None = None,
- custom_llm_provider: Literal["openai", "azure", "vertex_ai"] | str = "openai",
++ custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock"] | str = "openai",
+ metadata: dict[str, str] | None = None,
+ extra_headers: dict[str, str] | None = None,
+ extra_body: dict[str, str] | None = None,
**kwargs,
- ) -> Union[LiteLLMBatch, Coroutine[Any, Any, LiteLLMBatch]]:
+ ) -> LiteLLMBatch | Coroutine[Any, Any, LiteLLMBatch]:
"""
Cancels a batch.
@@@ -1087,18 -991,9 +991,14 @@@
timeout=timeout,
max_retries=optional_params.max_retries,
)
+ elif custom_llm_provider == "bedrock":
- from litellm.llms.bedrock.batches.handler import BedrockBatchesHandler
-
+ response = BedrockBatchesHandler.cancel_batch(
+ batch_id=batch_id,
+ **kwargs,
+ )
else:
raise litellm.exceptions.BadRequestError(
- message="LiteLLM doesn't support {} for 'cancel_batch'. Only 'openai', 'azure', 'vertex_ai', and 'bedrock' are supported.".format(
- custom_llm_provider
- ),
- message=f"LiteLLM doesn't support {custom_llm_provider} for 'cancel_batch'. Only 'openai', 'azure', and 'vertex_ai' are supported.",
++ message=f"LiteLLM doesn't support {custom_llm_provider} for 'cancel_batch'. Only 'openai', 'azure', 'vertex_ai', and 'bedrock' are supported.",
model="n/a",
llm_provider=custom_llm_provider,
response=httpx.Response(
diff --cc litellm/llms/bedrock/batches/handler.py
index c710bcfdafa,1752a727347..757552cec7e
--- a/litellm/llms/bedrock/batches/handler.py
+++ b/litellm/llms/bedrock/batches/handler.py
@@@ -1,13 -1,15 +1,18 @@@
from datetime import datetime
- from typing import Any, Optional, cast
-from typing import Any, Final, cast
++from typing import TYPE_CHECKING, Any, Final, cast
from openai.types.batch import BatchRequestCounts
from openai.types.batch import Metadata as OpenAIBatchMetadata
from litellm.types.utils import LiteLLMBatch
- # AWS Bedrock model-invocation-job statuses -> OpenAI Batch statuses.
- _BEDROCK_MIJ_STATUS_TO_OPENAI = {
++if TYPE_CHECKING:
++ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
++
+ # AWS Bedrock model-invocation-job statuses → OpenAI Batch statuses.
+ # Mirrors the mapping used by `BedrockBatchesConfig.transform_create_batch_response`
+ # so create / retrieve return consistent statuses.
+ _BEDROCK_MIJ_STATUS_TO_OPENAI: Final = {
"Submitted": "validating",
"Validating": "validating",
"Scheduled": "validating",
@@@ -63,77 -74,31 +77,104 @@@ def _to_epoch(value: Any) -> int | None
class BedrockBatchesHandler:
- """Handler for Bedrock Batches."""
+ """
+ Handler for Bedrock Batches.
+
+ Specific providers/models needed some special handling.
+
+ E.g. Twelve Labs Embedding Async Invoke
+ """
+ @staticmethod
+ def cancel_batch(
+ batch_id: str,
- aws_region_name: Optional[str] = None,
- logging_obj=None,
- **kwargs,
++ aws_region_name: str | None = None,
++ logging_obj: "LiteLLMLoggingObj | None" = None,
++ aws_access_key_id: str | None = None,
++ aws_secret_access_key: str | None = None,
++ aws_session_token: str | None = None,
++ aws_session_name: str | None = None,
++ aws_profile_name: str | None = None,
++ aws_role_name: str | None = None,
++ aws_web_identity_token: str | None = None,
++ aws_sts_endpoint: str | None = None,
++ aws_external_id: str | None = None,
++ **kwargs: object, # kwargs-ok: litellm.cancel_batch forwards arbitrary user kwargs verbatim
+ ) -> "LiteLLMBatch":
- """
- Cancel an AWS Bedrock batch model invocation job using StopModelInvocationJob.
- """
+ try:
+ import boto3
+ from botocore.exceptions import ClientError
+ except ImportError as exc:
- raise ImportError(
- "Missing boto3/botocore to call bedrock. Run 'pip install boto3'."
- ) from exc
++ raise ImportError("Missing boto3/botocore to call bedrock. Run 'pip install boto3'.") from exc
+
- region = (
- aws_region_name or _extract_region_from_bedrock_arn(batch_id) or "us-east-1"
- )
++ region: Final = aws_region_name or _extract_region_from_bedrock_arn(batch_id) or "us-east-1"
+
+ from litellm.llms.bedrock.batches.transformation import BedrockBatchesConfig
+
- creds = BedrockBatchesConfig().get_credentials(
- aws_access_key_id=kwargs.get("aws_access_key_id"),
- aws_secret_access_key=kwargs.get("aws_secret_access_key"),
- aws_session_token=kwargs.get("aws_session_token"),
++ creds: Final = BedrockBatchesConfig().get_credentials(
++ aws_access_key_id=aws_access_key_id,
++ aws_secret_access_key=aws_secret_access_key,
++ aws_session_token=aws_session_token,
+ aws_region_name=region,
- aws_session_name=kwargs.get("aws_session_name"),
- aws_profile_name=kwargs.get("aws_profile_name"),
- aws_role_name=kwargs.get("aws_role_name"),
- aws_web_identity_token=kwargs.get("aws_web_identity_token"),
- aws_sts_endpoint=kwargs.get("aws_sts_endpoint"),
- aws_external_id=kwargs.get("aws_external_id"),
++ aws_session_name=aws_session_name,
++ aws_profile_name=aws_profile_name,
++ aws_role_name=aws_role_name,
++ aws_web_identity_token=aws_web_identity_token,
++ aws_sts_endpoint=aws_sts_endpoint,
++ aws_external_id=aws_external_id,
+ )
+
- client = boto3.client(
++ client: Final = boto3.client(
+ "bedrock",
+ region_name=region,
+ aws_access_key_id=creds.access_key,
+ aws_secret_access_key=creds.secret_key,
+ aws_session_token=creds.token,
+ )
+
+ try:
+ client.stop_model_invocation_job(jobIdentifier=batch_id)
+ except ClientError as e:
- error_code = e.response.get("Error", {}).get("Code")
- error_msg = e.response.get("Error", {}).get("Message", "").lower()
- if error_code == "ValidationException" and any(
- term in error_msg for term in ["stop", "terminal", "completed", "already"]
- ):
- pass
- else:
- raise e
++ error_code: Final = e.response.get("Error", {}).get("Code")
++ error_msg: Final = e.response.get("Error", {}).get("Message", "").lower()
++ already_terminal: Final = error_code == "ValidationException" and any(
++ term in error_msg for term in ("stop", "terminal", "completed", "already")
++ )
++ if not already_terminal:
++ raise
+
+ return BedrockBatchesHandler._handle_model_invocation_job_status(
+ batch_id=batch_id,
+ aws_region_name=region,
+ logging_obj=logging_obj,
- **kwargs,
++ aws_access_key_id=aws_access_key_id,
++ aws_secret_access_key=aws_secret_access_key,
++ aws_session_token=aws_session_token,
++ aws_session_name=aws_session_name,
++ aws_profile_name=aws_profile_name,
++ aws_role_name=aws_role_name,
++ aws_web_identity_token=aws_web_identity_token,
++ aws_sts_endpoint=aws_sts_endpoint,
++ aws_external_id=aws_external_id,
+ )
+
@staticmethod
- def _handle_async_invoke_status(
- batch_id: str, aws_region_name: str, logging_obj=None, **kwargs
- ) -> "LiteLLMBatch":
+ def _handle_async_invoke_status(batch_id: str, aws_region_name: str, logging_obj=None, **kwargs) -> "LiteLLMBatch":
+ """
+ Handle async invoke status check for AWS Bedrock.
+
+ This is for Twelve Labs Embedding Async Invoke.
+
+ Args:
+ batch_id: The async invoke ARN
+ aws_region_name: AWS region name
+ **kwargs: Additional parameters
+
+ Returns:
+ dict: Status information including status, output_file_id (S3 URL), etc.
+ """
import asyncio
+
from litellm.llms.bedrock.embed.embedding import BedrockEmbedding
async def _async_get_status():
diff --cc tests/test_litellm/llms/bedrock/batches/test_handler.py
index 18780ccce0f,18780ccce0f..a54a0efae55
--- a/tests/test_litellm/llms/bedrock/batches/test_handler.py
+++ b/tests/test_litellm/llms/bedrock/batches/test_handler.py
@@@ -336,3 -336,3 +336,57 @@@ def test_logging_url_uses_bare_id_when_
assert pre_kwargs["additional_args"]["api_base"] == (
f"https://bedrock.us-west-2.amazonaws.com/model-invocation-job/{JOB_ID}"
)
++
++
++def test_cancel_batch_stops_job_and_returns_mapped_status(patched_boto3):
++ fake_client, boto_client_factory = patched_boto3
++ fake_client.get_model_invocation_job.return_value = _fake_boto3_response(status="Stopping")
++
++ batch = BedrockBatchesHandler.cancel_batch(batch_id=JOB_ARN)
++
++ fake_client.stop_model_invocation_job.assert_called_once_with(jobIdentifier=JOB_ARN)
++ _, kwargs = boto_client_factory.call_args
++ assert kwargs["region_name"] == "us-west-2"
++ assert batch.status == "cancelling"
++
++
++def test_cancel_batch_tolerates_already_terminal_job(patched_boto3):
++ from botocore.exceptions import ClientError
++
++ fake_client, _ = patched_boto3
++ fake_client.stop_model_invocation_job.side_effect = ClientError(
++ {"Error": {"Code": "ValidationException", "Message": "Job is already in a terminal state"}},
++ "StopModelInvocationJob",
++ )
++ fake_client.get_model_invocation_job.return_value = _fake_boto3_response(status="Stopped")
++
++ batch = BedrockBatchesHandler.cancel_batch(batch_id=JOB_ARN)
++
++ assert batch.status == "cancelled"
++
++
++def test_cancel_batch_reraises_other_client_errors(patched_boto3):
++ from botocore.exceptions import ClientError
++
++ fake_client, _ = patched_boto3
++ fake_client.stop_model_invocation_job.side_effect = ClientError(
++ {"Error": {"Code": "AccessDeniedException", "Message": "not authorized"}},
++ "StopModelInvocationJob",
++ )
++
++ with pytest.raises(ClientError):
++ BedrockBatchesHandler.cancel_batch(batch_id=JOB_ARN)
++
++ fake_client.get_model_invocation_job.assert_not_called()
++
++
++def test_litellm_cancel_batch_dispatches_to_bedrock(patched_boto3):
++ import litellm
++
++ fake_client, _ = patched_boto3
++ fake_client.get_model_invocation_job.return_value = _fake_boto3_response(status="Stopped")
++
++ batch = litellm.cancel_batch(batch_id=JOB_ARN, custom_llm_provider="bedrock")
++
++ fake_client.stop_model_invocation_job.assert_called_once_with(jobIdentifier=JOB_ARN)
++ assert batch.status == "cancelled"