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(batches): track cost for unmanaged Bedrock batches, generalize the flag (#32315)
Sameer Kankutec2141b1113d8
diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.pyindex b9ac98f515c..f209ab54f64 100644--- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py+++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py@@ -29,7 +29,7 @@ class CheckBatchCost:proxy_logging_obj: "ProxyLogging",prisma_client: "PrismaClient",llm_router: "Router",- track_unmanaged_vertex_batch_cost: bool = False,+ track_unmanaged_batch_cost: bool = False,):from litellm.proxy.utils import PrismaClient, ProxyLoggingfrom litellm.router import Router@@ -37,7 +37,7 @@ class CheckBatchCost:self.proxy_logging_obj: ProxyLogging = proxy_logging_objself.prisma_client: PrismaClient = prisma_clientself.llm_router: Router = llm_router- self._track_unmanaged_vertex_batch_cost = track_unmanaged_vertex_batch_cost+ self._track_unmanaged_batch_cost = track_unmanaged_batch_cost# Cached after the first poll cycle. Once we know the column is absent we skip# the guaranteed-failing primary query on every subsequent cycle.self._has_batch_processed_column: bool = True@@ -118,11 +118,11 @@ class CheckBatchCost:Resolve (model_id, batch_id) for a managed-object row, where model_id is a routerdeployment id and batch_id is the raw provider batch id.- Managed batches encode both in a base64 unified id. Unmanaged Vertex batches, created with- a raw gs:// input_file_id, store the raw provider job id as unified_object_id; when- track_unmanaged_vertex_batch_cost is enabled the model is derived from the gs:// path and- mapped to a configured vertex_ai deployment. Returns None (recording a metric) when the row- can't be routed.+ Managed batches encode both in a base64 unified id. Unmanaged batches (created outside+ LiteLLM's own /v1/batches with a raw input_file_id) store the raw provider job id as+ unified_object_id instead; when track_unmanaged_batch_cost is enabled the model is derived+ from the provider-specific input_file_id layout (Vertex gs:// or Bedrock s3://) and mapped+ to a matching deployment. Returns None (recording a metric) when the row can't be routed."""from litellm.proxy.openai_files_endpoints.common_utils import (_is_base64_encoded_unified_file_id,@@ -142,8 +142,43 @@ class CheckBatchCost:return Nonereturn model_id, get_batch_id_from_unified_batch_id(decoded)- if self._track_unmanaged_vertex_batch_cost:- return self._resolve_unmanaged_vertex_routing(job, prom_logger)+ if self._track_unmanaged_batch_cost:+ from litellm.llms.bedrock.batches.transformation import (+ BedrockBatchesConfig,+ )+ from litellm.llms.vertex_ai.batches.transformation import (+ VertexAIBatchTransformation,+ )++ input_file_id = self._get_input_file_id(job)+ if VertexAIBatchTransformation.is_unmanaged_gcs_batch_input_file_id(+ input_file_id+ ):+ assert input_file_id is not None # narrowed by is_unmanaged_gcs_batch_input_file_id+ return self._resolve_unmanaged_provider_routing(+ job=job,+ prom_logger=prom_logger,+ llm_provider="vertex_ai",+ bare_model_name=VertexAIBatchTransformation.get_bare_model_name_from_gcs_file(+ input_file_id+ ),+ )+ if BedrockBatchesConfig.is_unmanaged_s3_batch_input_file_id(input_file_id):+ assert input_file_id is not None # narrowed by is_unmanaged_s3_batch_input_file_id+ return self._resolve_unmanaged_provider_routing(+ job=job,+ prom_logger=prom_logger,+ llm_provider="bedrock",+ bare_model_name=BedrockBatchesConfig.get_bare_model_name_from_s3_file(+ input_file_id+ ),+ )+ verbose_proxy_logger.info(+ f"Skipping job {unified_object_id}: not a recognized unmanaged batch "+ "(no gs:// or s3:// input_file_id with an embedded model)"+ )+ self._record_error(prom_logger, "invalid_unified_id")+ return Noneverbose_proxy_logger.info(f"Skipping job {unified_object_id} because it is not a valid unified object id"@@ -151,36 +186,17 @@ class CheckBatchCost:self._record_error(prom_logger, "invalid_unified_id")return None- def _resolve_unmanaged_vertex_routing(+ def _resolve_unmanaged_provider_routing(self,job: "LiteLLM_ManagedObjectTable",prom_logger: Optional["PrometheusLogger"],+ llm_provider: str,+ bare_model_name: str,) -> Optional[Tuple[str, str]]:- from litellm.llms.vertex_ai.batches.transformation import (- VertexAIBatchTransformation,- )-- input_file_id = self._get_input_file_id(job)- if not VertexAIBatchTransformation.is_unmanaged_gcs_batch_input_file_id(- input_file_id- ):- verbose_proxy_logger.info(- f"Skipping job {job.unified_object_id}: not an unmanaged vertex batch "- "(no gs:// input_file_id with a publishers/ model path)"- )- self._record_error(prom_logger, "invalid_unified_id")- return None- assert input_file_id is not None # narrowed by is_unmanaged_gcs_batch_input_file_id-- bare_model_name = VertexAIBatchTransformation.get_bare_model_name_from_gcs_file(- input_file_id- )- deployment_id = self._get_vertex_ai_deployment_id_for_bare_model(- bare_model_name- )+ deployment_id = self._get_deployment_id_for_bare_model(bare_model_name, llm_provider)if deployment_id is None:verbose_proxy_logger.info(- f"Skipping unmanaged vertex batch {job.unified_object_id}: no vertex_ai "+ f"Skipping unmanaged {llm_provider} batch {job.unified_object_id}: no {llm_provider} "f"deployment configured for model {bare_model_name}")self._record_error(prom_logger, "unmanaged_no_matching_deployment")@@ -188,22 +204,22 @@ class CheckBatchCost:return deployment_id, job.unified_object_id- def _get_vertex_ai_deployment_id_for_bare_model(- self, bare_model_name: str+ def _get_deployment_id_for_bare_model(+ self, bare_model_name: str, llm_provider: str) -> Optional[str]:model_group = self.llm_router.resolve_model_name_from_model_id(bare_model_name)deployment_id = (- self._get_vertex_ai_deployment_id(model_group) if model_group else None+ self._get_deployment_id_for_provider(model_group, llm_provider) if model_group else None)if deployment_id is not None:return deployment_id- return self._get_vertex_ai_deployment_id_from_matching_deployments(- bare_model_name+ return self._get_deployment_id_from_matching_deployments(+ bare_model_name, llm_provider)- def _get_vertex_ai_deployment_id_from_matching_deployments(- self, bare_model_name: str+ def _get_deployment_id_from_matching_deployments(+ self, bare_model_name: str, llm_provider: str) -> Optional[str]:from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider@@ -215,13 +231,13 @@ class CheckBatchCost:if not self._is_bare_model_match(actual_model, bare_model_name):continuetry:- _, llm_provider, _, _ = get_llm_provider(+ _, deployment_llm_provider, _, _ = get_llm_provider(model=actual_model,custom_llm_provider=litellm_params.get("custom_llm_provider"),)except Exception:continue- if llm_provider != "vertex_ai":+ if deployment_llm_provider != llm_provider:continuemodel_info = deployment.get("model_info") or {}deployment_id = model_info.get("id")@@ -231,15 +247,21 @@ class CheckBatchCost:@staticmethoddef _is_bare_model_match(actual_model: str, bare_model_name: str) -> bool:+ # Bedrock model ids may have ":" replaced with "-" in the S3 object key (see+ # BedrockBatchesConfig.get_bare_model_name_from_s3_file), so normalize both sides;+ # a no-op for providers like vertex_ai whose model ids never contain a colon.+ normalized_actual = actual_model.replace(":", "-")+ normalized_bare = bare_model_name.replace(":", "-")return (- actual_model == bare_model_name- or actual_model.endswith(f"/{bare_model_name}")- or actual_model.endswith(f":{bare_model_name}")+ normalized_actual == normalized_bare+ or normalized_actual.endswith(f"/{normalized_bare}"))- def _get_vertex_ai_deployment_id(self, model_group: str) -> Optional[str]:+ def _get_deployment_id_for_provider(+ self, model_group: str, llm_provider: str+ ) -> Optional[str]:"""- Returns the first deployment id for `model_group` whose provider is vertex_ai,+ Returns the first deployment id for `model_group` whose provider is `llm_provider`,skipping deployments from other providers that happen to share the model group name."""from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider@@ -249,13 +271,13 @@ class CheckBatchCost:if deployment_info is None:continuetry:- _, llm_provider, _, _ = get_llm_provider(+ _, deployment_llm_provider, _, _ = get_llm_provider(model=deployment_info.litellm_params.model,custom_llm_provider=deployment_info.litellm_params.custom_llm_provider,)except Exception:continue- if llm_provider == "vertex_ai":+ if deployment_llm_provider == llm_provider:return deployment_idreturn Nonediff --git a/litellm/batches/batch_utils.py b/litellm/batches/batch_utils.pyindex 11b07d39981..2fcb8455e90 100644--- a/litellm/batches/batch_utils.py+++ b/litellm/batches/batch_utils.py@@ -118,6 +118,7 @@ def _batch_cost_calculator(total_cost = _get_batch_job_cost_from_file_content(file_content_dictionary=file_content_dictionary,custom_llm_provider=custom_llm_provider,+ model_name=model_name,model_info=model_info,)verbose_logger.debug("total_cost=%s", total_cost)@@ -363,6 +364,7 @@ def _count_entry_tokens(def _get_batch_job_cost_from_file_content(file_content_dictionary: List[dict],custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai",+ model_name: Optional[str] = None,model_info: Optional[ModelInfo] = None,) -> float:"""@@ -377,9 +379,15 @@ def _get_batch_job_cost_from_file_content(for _item in file_content_dictionary:if _batch_response_was_successful(_item, custom_llm_provider):_response_body = _get_response_from_batch_job_output_file(_item, custom_llm_provider)- if model_info is not None or custom_llm_provider == "anthropic":+ if model_info is not None or custom_llm_provider in ("anthropic", "bedrock"):usage = _get_batch_job_usage_from_response_body(_response_body, custom_llm_provider)- model = _response_body.get("model", "")+ # Bedrock batch output lines report a short internal model id+ # (e.g. "claude-sonnet-4-6") that is not in the cost map; use the+ # deployment model name for pricing when available.+ if custom_llm_provider == "bedrock" and model_name:+ model = model_name+ else:+ model = _response_body.get("model") or model_name or ""prompt_cost, completion_cost = batch_cost_calculator(usage=usage,model=model,@@ -485,7 +493,7 @@ def _get_batch_job_usage_from_response_body(response_body: dict, custom_llm_prov"""Get the tokens of a batch job from the response body"""- if custom_llm_provider == "anthropic":+ if custom_llm_provider in ("anthropic", "bedrock"):from litellm.llms.anthropic.chat.transformation import AnthropicConfigreturn AnthropicConfig().calculate_usage(@@ -513,6 +521,8 @@ def _get_response_from_batch_job_output_file(batch_job_output_file: dict, custom"""if custom_llm_provider == "anthropic":return _get_anthropic_result_from_batch_results_line(batch_job_output_file).get("message", None) or {}+ if custom_llm_provider == "bedrock":+ return batch_job_output_file.get("modelOutput", None) or {}_response: dict = batch_job_output_file.get("response", None) or {}_response_body = _response.get("body", None) or {}return _response_body@@ -523,9 +533,12 @@ def _batch_response_was_successful(batch_job_output_file: dict, custom_llm_proviCheck if the batch job response was successfulOpenAI-shaped output rows report ``response.status_code == 200``; Anthropic- message batch results lines report ``result.type == "succeeded"``.+ message batch results lines report ``result.type == "succeeded"``; Bedrock+ batch output lines report ``modelOutput`` (and no ``error``)."""if custom_llm_provider == "anthropic":return _get_anthropic_result_from_batch_results_line(batch_job_output_file).get("type") == "succeeded"+ if custom_llm_provider == "bedrock":+ return batch_job_output_file.get("modelOutput") is not None and batch_job_output_file.get("error") is None_response: dict = batch_job_output_file.get("response", None) or {}return _response.get("status_code", None) == 200diff --git a/litellm/llms/bedrock/batches/transformation.py b/litellm/llms/bedrock/batches/transformation.pyindex b0e28b6ba90..4fcf7cf91cb 100644--- a/litellm/llms/bedrock/batches/transformation.py+++ b/litellm/llms/bedrock/batches/transformation.py@@ -5,6 +5,9 @@ from typing import Any, Dict, List, Literal, Optional, Union, castfrom httpx import Headers, Response+from litellm.litellm_core_utils.cloud_storage_security import (+ BEDROCK_MANAGED_S3_BATCH_PREFIX,+)from litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.llms.base_llm.batches.transformation import BaseBatchesConfigfrom litellm.llms.base_llm.chat.transformation import BaseLLMException@@ -26,6 +29,15 @@ from litellm.types.utils import LiteLLMBatch, LlmProvidersfrom ..base_aws_llm import BaseAWSLLMfrom ..common_utils import CommonBatchFilesUtils+# Bedrock batch input files are uploaded as+# s3://bucket/litellm-bedrock-files-{model, ":" -> "-"}-{uuid4}.jsonl (see+# BedrockFilesTransformation._get_s3_object_name). A uuid4 is always 36 hex/dash+# characters, so it can be stripped off the end unambiguously even though the+# model name itself may contain dashes.+_S3_BATCH_FILE_UUID_SUFFIX_PATTERN = re.compile(+ r"-[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\.jsonl$"+)+class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig):"""@@ -40,6 +52,41 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig):def custom_llm_provider(self) -> LlmProviders:return LlmProviders.BEDROCK+ @classmethod+ def _get_bare_model_name_from_s3_key(cls, object_key: str) -> Optional[str]:+ if not object_key.startswith(BEDROCK_MANAGED_S3_BATCH_PREFIX):+ return None+ model_part = object_key[len(BEDROCK_MANAGED_S3_BATCH_PREFIX) :]+ match = _S3_BATCH_FILE_UUID_SUFFIX_PATTERN.search(model_part)+ if not match or match.start() == 0:+ return None+ return model_part[: match.start()]++ @classmethod+ def is_unmanaged_s3_batch_input_file_id(cls, input_file_id: Optional[str]) -> bool:+ """+ Returns True if `input_file_id` is a raw s3:// Bedrock batch input file (i.e. not a+ LiteLLM-managed unified file id) whose object key embeds the model name in the+ `litellm-bedrock-files-{model}-{uuid}.jsonl` layout.+ """+ if input_file_id is None or not input_file_id.startswith("s3://"):+ return False+ object_key = input_file_id.rsplit("/", 1)[-1]+ return cls._get_bare_model_name_from_s3_key(object_key) is not None++ @classmethod+ def get_bare_model_name_from_s3_file(cls, input_file_id: str) -> str:+ """+ Extracts the bare model name (e.g. "us.anthropic.claude-sonnet-4-20250514-v1-0") from+ an unmanaged batch's s3:// input file id. Note any ":" in the original model id was+ replaced with "-" at upload time, so callers must fuzzy-match against configured+ deployments rather than expect an exact string match.+ """+ object_key = input_file_id.rsplit("/", 1)[-1]+ bare_model_name = cls._get_bare_model_name_from_s3_key(object_key)+ assert bare_model_name is not None # narrowed by is_unmanaged_s3_batch_input_file_id+ return bare_model_name+def validate_environment(self,headers: dict,diff --git a/litellm/proxy/dev_config.yaml b/litellm/proxy/dev_config.yamlindex 4e9c710d446..f78431f694b 100644--- a/litellm/proxy/dev_config.yaml+++ b/litellm/proxy/dev_config.yaml@@ -199,9 +199,10 @@ model_list:general_settings:master_key: sk-1234- # Opt-in: let CheckBatchCost track cost for unmanaged Vertex batches created with a raw gs:// input_file_id.- # Requires a vertex_ai deployment configured for the batched model. Defaults to false.- # track_unmanaged_vertex_batch_cost: true+ # Opt-in: let CheckBatchCost track cost for unmanaged batches created with a raw+ # gs:// (Vertex) or s3:// (Bedrock) input_file_id. Requires a matching deployment+ # configured for the batched model. Defaults to false.+ # track_unmanaged_batch_cost: truesandbox_tools:- sandbox_tool_name: e2b_sandboxdiff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex f0ca1f6396f..37f3d6e49e0 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -7882,7 +7882,7 @@ class ProxyStartupEvent:proxy_logging_obj=proxy_logging_obj,prisma_client=prisma_client,llm_router=llm_router,- track_unmanaged_vertex_batch_cost=general_settings.get("track_unmanaged_vertex_batch_cost", False),+ track_unmanaged_batch_cost=general_settings.get("track_unmanaged_batch_cost", False),)scheduler.add_job(check_batch_cost_job.check_batch_cost,diff --git a/tests/proxy_unit_tests/test_check_batch_cost.py b/tests/proxy_unit_tests/test_check_batch_cost.pyindex f8f15f2e008..b822799fb40 100644--- a/tests/proxy_unit_tests/test_check_batch_cost.py+++ b/tests/proxy_unit_tests/test_check_batch_cost.py@@ -2,7 +2,8 @@Unit tests for CheckBatchCost class.Covers: stale-row cleanup (file_purpose scoping), paginated find_many,the batch_processed-column fallback query, and routing of unmanaged-Vertex batches (raw gs:// input_file_id, no managed unified id).+Vertex (raw gs:// input_file_id) and Bedrock (raw s3:// input_file_id,+ARN unified_object_id) batches with no managed unified id."""from unittest.mock import AsyncMock, MagicMock, patch@@ -31,6 +32,28 @@ def _unmanaged_vertex_file_object().model_dump_json()+def _unmanaged_bedrock_file_object(+ input_file_id=(+ "s3://bucket/litellm-bedrock-files-us.anthropic.claude-sonnet-4-20250514-v1-0"+ "-74b61828-9191-4d80-addb-5a0f9ab0ec6a.jsonl"+ ),+ status="validating",+):+ """A LiteLLMBatch JSON blob shaped like what gets stored for an unmanaged Bedrock+ batch (raw s3:// input_file_id, ARN unified_object_id)."""+ from litellm.types.utils import LiteLLMBatch++ return LiteLLMBatch(+ id="arn:aws:bedrock:us-east-1:298249409318:model-invocation-job/1ofb47x17jua",+ completion_window="24h",+ created_at=1,+ endpoint="/v1/chat/completions",+ input_file_id=input_file_id,+ object="batch",+ status=status,+ ).model_dump_json()++class TestCheckBatchCost:"""Test suite for CheckBatchCost class"""@@ -684,7 +707,7 @@ class TestUnmanagedVertexRouting:proxy_logging_obj=MagicMock(),prisma_client=MagicMock(),llm_router=router,- track_unmanaged_vertex_batch_cost=track_unmanaged,+ track_unmanaged_batch_cost=track_unmanaged,)def _job(self, file_object=None):@@ -916,3 +939,285 @@ class TestUnmanagedVertexRouting:update_data = prisma.db.litellm_managedobjecttable.update.call_args[1]["data"]assert update_data["batch_processed"] is Trueassert update_data["status"] == "complete"+++class TestUnmanagedBedrockRouting:+ """Routing of unmanaged Bedrock batches whose unified_object_id is a raw model-invocation-job ARN."""++ _ARN = "arn:aws:bedrock:us-east-1:298249409318:model-invocation-job/1ofb47x17jua"++ def _instance(self, track_unmanaged, router):+ from litellm_enterprise.proxy.common_utils.check_batch_cost import (+ CheckBatchCost,+ )++ return CheckBatchCost(+ proxy_logging_obj=MagicMock(),+ prisma_client=MagicMock(),+ llm_router=router,+ track_unmanaged_batch_cost=track_unmanaged,+ )++ def _job(self, file_object=None):+ job = MagicMock()+ job.unified_object_id = self._ARN+ job.file_object = (+ file_object if file_object is not None else _unmanaged_bedrock_file_object()+ )+ return job++ def _bedrock_deployment(self):+ deployment = MagicMock()+ deployment.litellm_params.custom_llm_provider = "bedrock"+ deployment.litellm_params.model = "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0"+ return deployment++ def test_flag_off_skips_arn_unified_id_unchanged(self):+ """Default (flag off): a raw ARN unified_object_id is skipped exactly as before; no+ model derivation or router lookup happens."""+ router = MagicMock()+ instance = self._instance(track_unmanaged=False, router=router)+ prom = MagicMock()++ with patch(_IS_B64, return_value=False):+ result = instance._resolve_job_routing(self._job(), prom)++ assert result is None+ prom.record_check_batch_cost_error.assert_called_once_with("invalid_unified_id")+ router.resolve_model_name_from_model_id.assert_not_called()+ router.get_model_ids.assert_not_called()++ def test_flag_on_routes_to_bedrock_deployment(self):+ """Flag on: derive the bare model from the s3:// object key (":" restored to "-" is+ matched fuzzily), resolve it to a deployment id, and use the raw ARN as the batch id."""+ router = MagicMock()+ router.resolve_model_name_from_model_id.return_value = "claude-sonnet-4"+ router.get_model_ids.return_value = ["deploy-1"]+ router.get_deployment = MagicMock(return_value=self._bedrock_deployment())+ instance = self._instance(track_unmanaged=True, router=router)++ with patch(_IS_B64, return_value=False):+ result = instance._resolve_job_routing(self._job(), MagicMock())++ assert result == ("deploy-1", self._ARN)++ def test_flag_on_skips_non_bedrock_deployment_sharing_model_group(self):+ """Flag on, but the only deployment for the model group is a non-bedrock provider:+ must not be selected, even though the model group name matches."""+ router = MagicMock()+ router.resolve_model_name_from_model_id.return_value = "claude-sonnet-4"+ router.get_model_ids.return_value = ["deploy-anthropic"]+ non_bedrock_deployment = MagicMock()+ non_bedrock_deployment.litellm_params.custom_llm_provider = "anthropic"+ non_bedrock_deployment.litellm_params.model = "claude-sonnet-4-20250514"+ router.get_deployment = MagicMock(return_value=non_bedrock_deployment)+ instance = self._instance(track_unmanaged=True, router=router)+ prom = MagicMock()++ with patch(_IS_B64, return_value=False):+ result = instance._resolve_job_routing(self._job(), prom)++ assert result is None+ prom.record_check_batch_cost_error.assert_called_once_with(+ "unmanaged_no_matching_deployment"+ )++ def test_flag_on_matches_deployment_despite_colon_dash_mismatch(self):+ """The S3 object key has ':' replaced with '-' (e.g. 'v1-0'), but the configured+ deployment's actual bedrock model id uses ':' (e.g. 'v1:0'). Routing must still match."""+ router = MagicMock()+ router.resolve_model_name_from_model_id.return_value = None+ router.get_model_ids.return_value = []+ router.get_model_list.return_value = [+ {+ "model_name": "claude-sonnet-4",+ "litellm_params": {+ "model": "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0",+ "custom_llm_provider": "bedrock",+ },+ "model_info": {"id": "deploy-bedrock"},+ }+ ]+ instance = self._instance(track_unmanaged=True, router=router)++ with patch(_IS_B64, return_value=False):+ result = instance._resolve_job_routing(self._job(), MagicMock())++ assert result == ("deploy-bedrock", self._ARN)++ def test_flag_on_no_matching_deployment_records_metric(self):+ """Flag on but no bedrock deployment for the model: skip with a distinct metric."""+ router = MagicMock()+ router.resolve_model_name_from_model_id.return_value = None+ router.get_model_ids.return_value = []+ router.get_model_list.return_value = []+ instance = self._instance(track_unmanaged=True, router=router)+ prom = MagicMock()++ with patch(_IS_B64, return_value=False):+ result = instance._resolve_job_routing(self._job(), prom)++ assert result is None+ prom.record_check_batch_cost_error.assert_called_once_with(+ "unmanaged_no_matching_deployment"+ )++ def test_flag_on_non_s3_input_is_not_unmanaged_bedrock(self):+ """Flag on, but input_file_id is not a litellm-bedrock-files- s3:// key: treat as+ unroutable, do not attempt model derivation."""+ router = MagicMock()+ instance = self._instance(track_unmanaged=True, router=router)+ prom = MagicMock()+ job = self._job(+ file_object=_unmanaged_bedrock_file_object(input_file_id="file-abc-123")+ )++ with patch(_IS_B64, return_value=False):+ result = instance._resolve_job_routing(job, prom)++ assert result is None+ prom.record_check_batch_cost_error.assert_called_once_with("invalid_unified_id")+ router.resolve_model_name_from_model_id.assert_not_called()++ @pytest.mark.asyncio+ async def test_end_to_end_costs_unmanaged_batch(self):+ """Flag on, completed unmanaged batch: the poller polls Bedrock with the raw ARN,+ computes cost, and marks batch_processed=True."""+ router = MagicMock()+ router.resolve_model_name_from_model_id.return_value = "claude-sonnet-4"+ router.get_model_ids.return_value = ["deploy-1"]++ mock_response = MagicMock()+ mock_response.status = "completed"+ mock_response.output_file_id = "s3://bucket/out/predictions.jsonl"+ mock_response.error_file_id = None+ mock_response.completed_at = None+ mock_response.created_at = None+ mock_response.model_dump_json.return_value = (+ f'{{"id":"{self._ARN}","status":"completed"}}'+ )+ router.aretrieve_batch = AsyncMock(return_value=mock_response)+ router.get_deployment_credentials_with_provider = MagicMock(+ return_value={"aws_region_name": "us-east-1"}+ )++ deployment = self._bedrock_deployment()+ deployment.model_name = "claude-sonnet-4"+ deployment.model_info.model_dump.return_value = {}+ router.get_deployment = MagicMock(return_value=deployment)++ instance = self._instance(track_unmanaged=True, router=router)+ instance.proxy_logging_obj.get_proxy_hook.return_value = None+ instance._has_batch_processed_column = True++ prisma = instance.prisma_client+ prisma.db = MagicMock()+ prisma.db.litellm_managedobjecttable = MagicMock()+ prisma.db.litellm_managedobjecttable.update_many = AsyncMock(return_value=0)+ prisma.db.litellm_managedobjecttable.update = AsyncMock()+ prisma.db.litellm_managedobjecttable.find_many = AsyncMock(+ return_value=[self._job()]+ )+ prisma.db.litellm_usertable = MagicMock()+ prisma.db.litellm_usertable.find_unique = AsyncMock(return_value=None)++ mock_file_content = MagicMock()+ mock_file_content.content = b'{"id":"req-1"}'++ with (+ patch(_IS_B64, side_effect=[False, None]),+ patch(+ "litellm.files.main.afile_content",+ new_callable=AsyncMock,+ return_value=mock_file_content,+ ),+ patch(+ "litellm.batches.batch_utils._get_file_content_as_dictionary",+ return_value=[{"id": "req-1"}],+ ),+ patch(+ "litellm.batches.batch_utils.calculate_batch_cost_and_usage",+ new_callable=AsyncMock,+ return_value=(+ 0.02,+ {"prompt_tokens": 10, "completion_tokens": 5},+ ["claude-sonnet-4"],+ ),+ ),+ patch(+ "litellm.litellm_core_utils.get_llm_provider_logic.get_llm_provider",+ return_value=("claude-sonnet-4", "bedrock", None, None),+ ),+ patch(+ "litellm.litellm_core_utils.litellm_logging.Logging"+ ) as mock_logging_cls,+ ):+ mock_logging_obj = MagicMock()+ mock_logging_obj.async_success_handler = AsyncMock()+ mock_logging_cls.return_value = mock_logging_obj++ await instance.check_batch_cost()++ router.aretrieve_batch.assert_awaited_once()+ assert router.aretrieve_batch.call_args[1]["model"] == "deploy-1"+ assert router.aretrieve_batch.call_args[1]["batch_id"] == self._ARN++ mock_logging_obj.async_success_handler.assert_awaited_once()+ assert mock_logging_obj.async_success_handler.call_args[1]["batch_cost"] == 0.02++ assert prisma.db.litellm_managedobjecttable.update.call_count == 1+ update_data = prisma.db.litellm_managedobjecttable.update.call_args[1]["data"]+ assert update_data["batch_processed"] is True+ assert update_data["status"] == "complete"+++class TestUnmanagedBatchCostFlagIsGeneralized:+ """The single track_unmanaged_batch_cost flag must cover both Vertex and Bedrock, not+ just the provider it was originally added for."""++ def test_one_flag_routes_both_vertex_and_bedrock_jobs(self):+ from litellm_enterprise.proxy.common_utils.check_batch_cost import (+ CheckBatchCost,+ )++ router = MagicMock()+ router.resolve_model_name_from_model_id.side_effect = [+ "gemini-2.5-flash",+ "claude-sonnet-4",+ ]+ router.get_model_ids.side_effect = [["deploy-vertex"], ["deploy-bedrock"]]++ def _get_deployment(model_id):+ if model_id == "deploy-vertex":+ deployment = MagicMock()+ deployment.litellm_params.custom_llm_provider = "vertex_ai"+ deployment.litellm_params.model = "vertex_ai/gemini-2.5-flash"+ return deployment+ deployment = MagicMock()+ deployment.litellm_params.custom_llm_provider = "bedrock"+ deployment.litellm_params.model = "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0"+ return deployment++ router.get_deployment = MagicMock(side_effect=_get_deployment)++ instance = CheckBatchCost(+ proxy_logging_obj=MagicMock(),+ prisma_client=MagicMock(),+ llm_router=router,+ track_unmanaged_batch_cost=True,+ )++ vertex_job = MagicMock()+ vertex_job.unified_object_id = "8823717160934178816"+ vertex_job.file_object = _unmanaged_vertex_file_object()++ bedrock_job = MagicMock()+ bedrock_job.unified_object_id = TestUnmanagedBedrockRouting._ARN+ bedrock_job.file_object = _unmanaged_bedrock_file_object()++ with patch(_IS_B64, return_value=False):+ vertex_result = instance._resolve_job_routing(vertex_job, MagicMock())+ bedrock_result = instance._resolve_job_routing(bedrock_job, MagicMock())++ assert vertex_result == ("deploy-vertex", "8823717160934178816")+ assert bedrock_result == ("deploy-bedrock", TestUnmanagedBedrockRouting._ARN)diff --git a/tests/test_litellm/batches/test_batch_utils.py b/tests/test_litellm/batches/test_batch_utils.pyindex 9de5cd69b1e..c7aecac477e 100644--- a/tests/test_litellm/batches/test_batch_utils.py+++ b/tests/test_litellm/batches/test_batch_utils.py@@ -818,6 +818,29 @@ def test_anthropic_usage_conversion_includes_cache_tokens():assert usage.prompt_tokens_details.cache_creation_tokens == 2000+def test_bedrock_model_output_line_success_check():+ row = {+ "recordId": "1",+ "modelOutput": {"model": "claude-sonnet-4-6", "usage": {"input_tokens": 13, "output_tokens": 5}},+ }+ assert bu._batch_response_was_successful(row, custom_llm_provider="bedrock") is True+ assert bu._get_response_from_batch_job_output_file(row, custom_llm_provider="bedrock")["model"] == "claude-sonnet-4-6"+++def test_bedrock_cost_uses_deployment_model_name():+ row = {+ "recordId": "1",+ "modelOutput": {"model": "claude-sonnet-4-6", "usage": {"input_tokens": 13, "output_tokens": 5}},+ }+ cost = bu._get_batch_job_cost_from_file_content(+ file_content_dictionary=[row],+ custom_llm_provider="bedrock",+ model_name="us.anthropic.claude-sonnet-4-6",+ model_info={},+ )+ assert cost > 0++def test_anthropic_total_usage_sums_succeeded_only():rows = [_anthropic_succeeded_row(usage=_anthropic_usage(10, 5)),