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
fix(batches): price anthropic passthrough message batches correctly in batch cost job (#32307)
Mateo Wang9076c3334760
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.jsonindex 7e3f6a20281..cb3427bed4d 100644--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@ -99,7 +99,7 @@"limit": 0},"reportUnknownArgumentType": {- "limit": 45895+ "limit": 45894},"reportUnknownLambdaType": {"limit": 113diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.pyindex 831a23ff3cd..b9ac98f515c 100644--- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py+++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py@@ -17,6 +17,7 @@ if TYPE_CHECKING:from litellm.proxy._types import LiteLLM_ManagedObjectTablefrom litellm.proxy.utils import PrismaClient, ProxyLoggingfrom litellm.router import Router+ from litellm.types.utils import LiteLLMBatchCHECK_BATCH_COST_USER_AGENT = "LiteLLM Proxy/CheckBatchCost"@@ -277,13 +278,20 @@ class CheckBatchCost:except Exception:return None- async def check_batch_cost(self):+ async def _track_completed_batch_cost(+ self,+ job: "LiteLLM_ManagedObjectTable",+ response: "LiteLLMBatch",+ model_id: str,+ batch_id: str,+ prom_logger: Optional["PrometheusLogger"],+ ) -> Optional[Tuple[Optional[str], Optional[str]]]:"""- Check if the batch JOB has been tracked.- - get all status="validating" and file_purpose="batch" jobs- - check if batch is now complete- - if not, return False- - if so, return True+ Fetch a completed batch's results, compute cost/usage, and emit the+ aretrieve_batch spend log. Returns (model_name, llm_provider) on+ success, None when the job can't be routed to a deployment. Raises on+ results-fetch or cost-computation failures so the caller can leave the+ job unprocessed and retry it on a later poll."""from litellm.batches.batch_utils import (_get_file_content_as_dictionary,@@ -296,6 +304,184 @@ class CheckBatchCost:_is_base64_encoded_unified_file_id,)+ verbose_proxy_logger.info(+ f"Batch ID: {batch_id} is complete, tracking cost and usage"+ )++ # aretrieve_batch is called with the raw provider batch ID, so response.id+ # is the raw provider value (e.g. "batch_20260223-0518.234"). We need the+ # unified base64 ID in the S3 log so downstream consumers can correlate it+ # back to the batch they submitted via the proxy.+ #+ # CheckBatchCost builds its own LiteLLMLogging object (logging_obj below) and+ # calls async_success_handler(result=response) directly. That handler calls+ # _build_standard_logging_payload(response, ...) which reads response.id at+ # that point — so setting response.id here is sufficient.+ #+ # The HTTP endpoint does this substitution via the managed files hook+ # (async_post_call_success_hook). CheckBatchCost bypasses that hook entirely,+ # so we do it explicitly here.+ response.id = job.unified_object_id++ # This background job runs as default_user_id, so going through the HTTP endpoint+ # would trigger check_managed_file_id_access and get 403. Instead, extract the raw+ # provider file ID and call afile_content directly with deployment credentials.+ raw_output_file_id = response.output_file_id+ decoded = _is_base64_encoded_unified_file_id(raw_output_file_id)+ if decoded:+ try:+ raw_output_file_id = decoded.split("llm_output_file_id,")[1].split(";")[0]+ except (IndexError, AttributeError):+ pass++ credentials = self.llm_router.get_deployment_credentials_with_provider(model_id) or {}+ _file_content = await afile_content(+ file_id=raw_output_file_id,+ **credentials,+ )++ # Access content - handle both direct attribute and method call+ if hasattr(_file_content, 'content'):+ content_bytes = _file_content.content # type: ignore[union-attr]+ elif hasattr(_file_content, 'read'):+ content_bytes = await _file_content.read() # type: ignore[misc]+ else:+ content_bytes = _file_content # type: ignore[assignment]++ file_content_as_dict = _get_file_content_as_dictionary(+ content_bytes # type: ignore[arg-type]+ )++ # Record output file size+ if prom_logger and content_bytes:+ try:+ prom_logger.record_managed_file_size(+ size_bytes=len(content_bytes), # type: ignore+ purpose="batch",+ file_type="output",+ model=model_id,+ )+ except Exception:+ pass++ deployment_info = self.llm_router.get_deployment(model_id=model_id)+ if deployment_info is None:+ verbose_proxy_logger.info(+ f"Skipping job {job.unified_object_id} because it is not a valid deployment info"+ )+ self._record_error(prom_logger, "deployment_not_found")+ return None+ custom_llm_provider = deployment_info.litellm_params.custom_llm_provider+ litellm_model_name = deployment_info.litellm_params.model++ model_name, llm_provider, _, _ = get_llm_provider(+ model=litellm_model_name,+ custom_llm_provider=custom_llm_provider,+ )++ # CheckBatchCost bypasses async_post_call_success_hook, so convert raw+ # output/error file IDs to managed base64 IDs before the DB write here.+ managed_files_hook = self.proxy_logging_obj.get_proxy_hook("managed_files")+ if managed_files_hook is not None:+ from litellm.proxy._types import UserAPIKeyAuth+ _minimal_auth = UserAPIKeyAuth(+ user_id=job.created_by or "default-user-id",+ team_id=getattr(job, "team_id", None),+ )+ for _file_attr in ["output_file_id", "error_file_id"]:+ _raw_file_id = getattr(response, _file_attr, None)+ if _raw_file_id and not _is_base64_encoded_unified_file_id(_raw_file_id):+ try:+ _unified_file_id = managed_files_hook.get_unified_output_file_id(+ output_file_id=_raw_file_id,+ model_id=model_id,+ model_name=str(model_name) if model_name else deployment_info.model_name or None,+ )+ await managed_files_hook.store_unified_file_id(+ file_id=_unified_file_id,+ file_object=None,+ litellm_parent_otel_span=None,+ model_mappings={model_id: _raw_file_id},+ user_api_key_dict=_minimal_auth,+ )+ setattr(response, _file_attr, _unified_file_id)+ verbose_proxy_logger.info(+ f"CheckBatchCost: converted {_file_attr} "+ f"{_raw_file_id!r} -> managed ID for batch {batch_id}"+ )+ except Exception as _e:+ verbose_proxy_logger.warning(+ f"CheckBatchCost: failed to create managed file ID for "+ f"{_file_attr}={_raw_file_id!r}: {_e}"+ )++ # Pass deployment model_info so custom batch pricing+ # (input_cost_per_token_batches etc.) is used for cost calc+ deployment_model_info = deployment_info.model_info.model_dump() if deployment_info.model_info else {}+ batch_cost, batch_usage, batch_models = (+ await calculate_batch_cost_and_usage(+ file_content_dictionary=file_content_as_dict,+ custom_llm_provider=llm_provider, # type: ignore+ model_name=model_name,+ model_info=deployment_model_info, # type: ignore[arg-type]+ )+ )+ logging_obj = LiteLLMLogging(+ model=batch_models[0],+ messages=[{"role": "user", "content": "<retrieve_batch>"}],+ stream=False,+ call_type="aretrieve_batch",+ start_time=datetime.now(),+ litellm_call_id=str(uuid.uuid4()),+ function_id=str(uuid.uuid4()),+ )++ creator_user_id = job.created_by+ user_info = await self._get_user_info(batch_id, job.created_by)++ logging_obj.update_environment_variables(+ litellm_params={+ # set the user-agent header so that S3 callback consumers can easily identify CheckBatchCost callbacks+ "proxy_server_request": {+ "headers": {+ "user-agent": CHECK_BATCH_COST_USER_AGENT,+ }+ },+ "metadata": {+ "user_api_key_user_id": creator_user_id,+ **user_info,+ },+ },+ optional_params={},+ )++ await logging_obj.async_success_handler(+ result=response,+ batch_cost=batch_cost,+ batch_usage=batch_usage,+ batch_models=batch_models,+ )++ # Record batch duration (completed_at - created_at)+ if prom_logger and response.completed_at and response.created_at:+ duration_seconds = float(response.completed_at - response.created_at)+ if duration_seconds >= 0:+ prom_logger.record_managed_batch_duration(+ duration_seconds=duration_seconds,+ model=model_name,+ api_provider=str(llm_provider) if llm_provider else None,+ )++ return model_name, str(llm_provider) if llm_provider else None++ async def check_batch_cost(self):+ """+ Check if the batch JOB has been tracked.+ - get all status="validating" and file_purpose="batch" jobs+ - check if batch is now complete+ - if not, return False+ - if so, return True+ """try:from litellm.integrations.prometheus import PrometheusLoggerprom_logger = PrometheusLogger.get_instance()@@ -381,177 +567,26 @@ class CheckBatchCost:response.status == "completed"and response.output_file_id is not None):- verbose_proxy_logger.info(- f"Batch ID: {batch_id} is complete, tracking cost and usage"- )-- # aretrieve_batch is called with the raw provider batch ID, so response.id- # is the raw provider value (e.g. "batch_20260223-0518.234"). We need the- # unified base64 ID in the S3 log so downstream consumers can correlate it- # back to the batch they submitted via the proxy.- #- # CheckBatchCost builds its own LiteLLMLogging object (logging_obj below) and- # calls async_success_handler(result=response) directly. That handler calls- # _build_standard_logging_payload(response, ...) which reads response.id at- # that point — so setting response.id here is sufficient.- #- # The HTTP endpoint does this substitution via the managed files hook- # (async_post_call_success_hook). CheckBatchCost bypasses that hook entirely,- # so we do it explicitly here.- response.id = job.unified_object_id-- # This background job runs as default_user_id, so going through the HTTP endpoint- # would trigger check_managed_file_id_access and get 403. Instead, extract the raw- # provider file ID and call afile_content directly with deployment credentials.- raw_output_file_id = response.output_file_id- decoded = _is_base64_encoded_unified_file_id(raw_output_file_id)- if decoded:- try:- raw_output_file_id = decoded.split("llm_output_file_id,")[1].split(";")[0]- except (IndexError, AttributeError):- pass-- credentials = self.llm_router.get_deployment_credentials_with_provider(model_id) or {}- _file_content = await afile_content(- file_id=raw_output_file_id,- **credentials,- )-- # Access content - handle both direct attribute and method call- if hasattr(_file_content, 'content'):- content_bytes = _file_content.content # type: ignore[union-attr]- elif hasattr(_file_content, 'read'):- content_bytes = await _file_content.read() # type: ignore[misc]- else:- content_bytes = _file_content # type: ignore[assignment]-- file_content_as_dict = _get_file_content_as_dictionary(- content_bytes # type: ignore[arg-type]- )-- # Record output file size- if prom_logger and content_bytes:- try:- prom_logger.record_managed_file_size(- size_bytes=len(content_bytes), # type: ignore- purpose="batch",- file_type="output",- model=model_id,- )- except Exception:- pass-- deployment_info = self.llm_router.get_deployment(model_id=model_id)- if deployment_info is None:- verbose_proxy_logger.info(- f"Skipping job {job.unified_object_id} because it is not a valid deployment info"- )- if prom_logger:- prom_logger.record_check_batch_cost_error("deployment_not_found")- continue- custom_llm_provider = deployment_info.litellm_params.custom_llm_provider- litellm_model_name = deployment_info.litellm_params.model-- model_name, llm_provider, _, _ = get_llm_provider(- model=litellm_model_name,- custom_llm_provider=custom_llm_provider,- )-- # CheckBatchCost bypasses async_post_call_success_hook, so convert raw- # output/error file IDs to managed base64 IDs before the DB write here.- managed_files_hook = self.proxy_logging_obj.get_proxy_hook("managed_files")- if managed_files_hook is not None:- from litellm.proxy._types import UserAPIKeyAuth- _minimal_auth = UserAPIKeyAuth(- user_id=job.created_by or "default-user-id",- team_id=getattr(job, "team_id", None),+ try:+ tracked = await self._track_completed_batch_cost(+ job=job,+ response=response,+ model_id=model_id,+ batch_id=batch_id,+ prom_logger=prom_logger,)- for _file_attr in ["output_file_id", "error_file_id"]:- _raw_file_id = getattr(response, _file_attr, None)- if _raw_file_id and not _is_base64_encoded_unified_file_id(_raw_file_id):- try:- _unified_file_id = managed_files_hook.get_unified_output_file_id(- output_file_id=_raw_file_id,- model_id=model_id,- model_name=str(model_name) if model_name else deployment_info.model_name or None,- )- await managed_files_hook.store_unified_file_id(- file_id=_unified_file_id,- file_object=None,- litellm_parent_otel_span=None,- model_mappings={model_id: _raw_file_id},- user_api_key_dict=_minimal_auth,- )- setattr(response, _file_attr, _unified_file_id)- verbose_proxy_logger.info(- f"CheckBatchCost: converted {_file_attr} "- f"{_raw_file_id!r} -> managed ID for batch {batch_id}"- )- except Exception as _e:- verbose_proxy_logger.warning(- f"CheckBatchCost: failed to create managed file ID for "- f"{_file_attr}={_raw_file_id!r}: {_e}"- )-- # Pass deployment model_info so custom batch pricing- # (input_cost_per_token_batches etc.) is used for cost calc- deployment_model_info = deployment_info.model_info.model_dump() if deployment_info.model_info else {}- batch_cost, batch_usage, batch_models = (- await calculate_batch_cost_and_usage(- file_content_dictionary=file_content_as_dict,- custom_llm_provider=llm_provider, # type: ignore- model_name=model_name,- model_info=deployment_model_info, # type: ignore[arg-type]+ except Exception as tracking_err:+ verbose_proxy_logger.error(+ f"CheckBatchCost: failed to track cost for batch {batch_id} "+ f"(job {job.id}); leaving it unprocessed so the next poll retries: {tracking_err}")- )- logging_obj = LiteLLMLogging(- model=batch_models[0],- messages=[{"role": "user", "content": "<retrieve_batch>"}],- stream=False,- call_type="aretrieve_batch",- start_time=datetime.now(),- litellm_call_id=str(uuid.uuid4()),- function_id=str(uuid.uuid4()),- )-- creator_user_id = job.created_by- user_info = await self._get_user_info(batch_id, job.created_by)-- logging_obj.update_environment_variables(- litellm_params={- # set the user-agent header so that S3 callback consumers can easily identify CheckBatchCost callbacks- "proxy_server_request": {- "headers": {- "user-agent": CHECK_BATCH_COST_USER_AGENT,- }- },- "metadata": {- "user_api_key_user_id": creator_user_id,- **user_info,- },- },- optional_params={},- )-- await logging_obj.async_success_handler(- result=response,- batch_cost=batch_cost,- batch_usage=batch_usage,- batch_models=batch_models,- )-- # Record batch duration (completed_at - created_at)- if prom_logger and response.completed_at and response.created_at:- duration_seconds = float(response.completed_at - response.created_at)- if duration_seconds >= 0:- prom_logger.record_managed_batch_duration(- duration_seconds=duration_seconds,- model=model_name,- api_provider=str(llm_provider) if llm_provider else None,- )+ self._record_error(prom_logger, "cost_tracking_error")+ continue+ if tracked is None:+ continue# Track this job for the final metrics summary- processed_models.append((model_name, str(llm_provider) if llm_provider else None))+ processed_models.append(tracked)# mark the job as completetry:diff --git a/litellm/batches/batch_utils.py b/litellm/batches/batch_utils.pyindex 985198ce7ce..11b07d39981 100644--- a/litellm/batches/batch_utils.py+++ b/litellm/batches/batch_utils.py@@ -3,6 +3,7 @@ from typing import Any, Iterator, List, Literal, Optional, Tupleimport litellmfrom litellm._logging import verbose_logger+from litellm.litellm_core_utils.llm_cost_calc.utils import _parse_prompt_tokens_detailsfrom litellm.types.llms.openai import Batchfrom litellm.types.utils import CallTypes, ModelInfo, Usagefrom litellm.utils import token_counter@@ -34,7 +35,7 @@ async def calculate_batch_cost_and_usage(custom_llm_provider=custom_llm_provider,model_name=model_name,)- batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name)+ batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name, custom_llm_provider)return batch_cost, batch_usage, batch_models@@ -70,7 +71,7 @@ async def _handle_completed_batch(model_name=model_name,)- batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name)+ batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name, custom_llm_provider)return batch_cost, batch_usage, batch_models@@ -78,6 +79,7 @@ async def _handle_completed_batch(def _get_batch_models_from_file_content(file_content_dictionary: List[dict],model_name: Optional[str] = None,+ custom_llm_provider: str = "openai",) -> List[str]:"""Get the models from the file content@@ -86,8 +88,8 @@ def _get_batch_models_from_file_content(return [model_name]batch_models = []for _item in file_content_dictionary:- if _batch_response_was_successful(_item):- _response_body = _get_response_from_batch_job_output_file(_item)+ if _batch_response_was_successful(_item, custom_llm_provider):+ _response_body = _get_response_from_batch_job_output_file(_item, custom_llm_provider)_model = _response_body.get("model")if _model:batch_models.append(_model)@@ -373,10 +375,10 @@ def _get_batch_job_cost_from_file_content(# parse the file content as jsonverbose_logger.debug("file_content_dictionary=%s", json.dumps(file_content_dictionary, indent=4))for _item in file_content_dictionary:- if _batch_response_was_successful(_item):- _response_body = _get_response_from_batch_job_output_file(_item)- if model_info is not None:- usage = _get_batch_job_usage_from_response_body(_response_body)+ 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":+ usage = _get_batch_job_usage_from_response_body(_response_body, custom_llm_provider)model = _response_body.get("model", "")prompt_cost, completion_cost = batch_cost_calculator(usage=usage,@@ -418,17 +420,31 @@ def _get_batch_job_total_usage_from_file_content(total_tokens: int = 0prompt_tokens: int = 0completion_tokens: int = 0+ cache_read_tokens: int = 0+ cache_creation_tokens: int = 0for _item in file_content_dictionary:- if _batch_response_was_successful(_item):- _response_body = _get_response_from_batch_job_output_file(_item)- usage: Usage = _get_batch_job_usage_from_response_body(_response_body)+ if _batch_response_was_successful(_item, custom_llm_provider):+ _response_body = _get_response_from_batch_job_output_file(_item, custom_llm_provider)+ usage: Usage = _get_batch_job_usage_from_response_body(_response_body, custom_llm_provider)total_tokens += usage.total_tokensprompt_tokens += usage.prompt_tokenscompletion_tokens += usage.completion_tokens+ prompt_details = _parse_prompt_tokens_details(usage)+ cache_read_tokens += prompt_details["cache_hit_tokens"]+ cache_creation_tokens += prompt_details["cache_creation_tokens"]+ cache_token_params = {+ key: tokens+ for key, tokens in (+ ("cache_read_input_tokens", cache_read_tokens),+ ("cache_creation_input_tokens", cache_creation_tokens),+ )+ if tokens > 0+ }return Usage(total_tokens=total_tokens,prompt_tokens=prompt_tokens,completion_tokens=completion_tokens,+ **cache_token_params,)@@ -465,27 +481,51 @@ def _count_prompt_or_input_tokens(model: str, value: Any) -> int:return 0-def _get_batch_job_usage_from_response_body(response_body: dict) -> Usage:+def _get_batch_job_usage_from_response_body(response_body: dict, custom_llm_provider: str = "openai") -> Usage:"""Get the tokens of a batch job from the response body"""+ if custom_llm_provider == "anthropic":+ from litellm.llms.anthropic.chat.transformation import AnthropicConfig++ return AnthropicConfig().calculate_usage(+ usage_object=response_body.get("usage", None) or {},+ reasoning_content=None,+ )_usage_dict = response_body.get("usage", None) or {}usage: Usage = Usage(**_usage_dict)return usage-def _get_response_from_batch_job_output_file(batch_job_output_file: dict) -> Any:+def _get_anthropic_result_from_batch_results_line(batch_results_line: dict) -> dict:+ """+ Get the ``result`` object from a line of an Anthropic message batch results JSONL file.++ Anthropic batch results lines look like:+ ``{"custom_id": ..., "result": {"type": "succeeded", "message": {..., "usage": {...}}}}``+ """+ return batch_results_line.get("result", None) or {}+++def _get_response_from_batch_job_output_file(batch_job_output_file: dict, custom_llm_provider: str = "openai") -> Any:"""Get the response from the batch job output file"""+ if custom_llm_provider == "anthropic":+ return _get_anthropic_result_from_batch_results_line(batch_job_output_file).get("message", None) or {}_response: dict = batch_job_output_file.get("response", None) or {}_response_body = _response.get("body", None) or {}return _response_body-def _batch_response_was_successful(batch_job_output_file: dict) -> bool:+def _batch_response_was_successful(batch_job_output_file: dict, custom_llm_provider: str = "openai") -> bool:"""- Check if the batch job response status == 200+ Check if the batch job response was successful++ OpenAI-shaped output rows report ``response.status_code == 200``; Anthropic+ message batch results lines report ``result.type == "succeeded"``."""+ if custom_llm_provider == "anthropic":+ return _get_anthropic_result_from_batch_results_line(batch_job_output_file).get("type") == "succeeded"_response: dict = batch_job_output_file.get("response", None) or {}return _response.get("status_code", None) == 200diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex 63ffe9d308b..74dc0e19da3 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -2155,17 +2155,23 @@ def batch_cost_calculator(if input_cost_per_token_batches:total_prompt_cost = usage.prompt_tokens * input_cost_per_token_batcheselif input_cost_per_token:+ details = _parse_prompt_tokens_details(usage)+ cache_read_tokens = details["cache_hit_tokens"]+ cache_creation_tokens = details["cache_creation_tokens"]+# Subtract cached tokens from prompt_tokens before calculating cost# Fixes issue where cached tokens are being charged again+ base_input_tokens = get_billable_input_tokens(usage) - cache_creation_tokenstotal_prompt_cost = (- get_billable_input_tokens(usage) * (input_cost_per_token) / 2+ base_input_tokens * (input_cost_per_token) / 2) # batch cost is usually half of the regular token cost# Add cache read cost if applicable- details = _parse_prompt_tokens_details(usage)- cache_read_tokens = details["cache_hit_tokens"]cache_read_cost_key = _get_service_tier_cost_key("cache_read_input_token_cost", None)total_prompt_cost += calculate_cost_component(model_info, cache_read_cost_key, cache_read_tokens) / 2++ cache_creation_cost = model_info.get("cache_creation_input_token_cost") or input_cost_per_token+ total_prompt_cost += cache_creation_tokens * cache_creation_cost / 2if output_cost_per_token_batches:total_completion_cost = usage.completion_tokens * output_cost_per_token_batcheselif output_cost_per_token:diff --git a/litellm/llms/anthropic/files/transformation.py b/litellm/llms/anthropic/files/transformation.pyindex cf12ad9ab32..0fa01e09492 100644--- a/litellm/llms/anthropic/files/transformation.py+++ b/litellm/llms/anthropic/files/transformation.py@@ -39,6 +39,7 @@ from ..common_utils import AnthropicError, AnthropicModelInfoANTHROPIC_FILES_API_BASE = "https://api.anthropic.com"ANTHROPIC_FILES_BETA_HEADER = "files-api-2025-04-14"+ANTHROPIC_MESSAGE_BATCH_ID_PREFIX = "msgbatch_"class AnthropicFilesConfig(BaseFilesConfig):@@ -258,6 +259,8 @@ class AnthropicFilesConfig(BaseFilesConfig):file_id = file_content_request.get("file_id")api_base = AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) or ANTHROPIC_FILES_API_BASEencoded_file_id = encode_url_path_segment(file_id, field_name="file_id")+ if file_id.startswith(ANTHROPIC_MESSAGE_BATCH_ID_PREFIX):+ return f"{api_base.rstrip('/')}/v1/messages/batches/{encoded_file_id}/results", {}return f"{api_base.rstrip('/')}/v1/files/{encoded_file_id}/content", {}def transform_file_content_response(diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex e48011f23f1..6b3f5beb37d 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -4735,6 +4735,13 @@ class BaseLLMHTTPHandler:except Exception as e:raise self._handle_error(e=e, provider_config=provider_config)+ if response.status_code >= 400:+ raise provider_config.get_error_class(+ error_message=response.text,+ status_code=response.status_code,+ headers=response.headers,+ )+return provider_config.transform_file_content_response(raw_response=response,logging_obj=logging_obj,@@ -4791,6 +4798,13 @@ class BaseLLMHTTPHandler:except Exception as e:raise self._handle_error(e=e, provider_config=provider_config)+ if response.status_code >= 400:+ raise provider_config.get_error_class(+ error_message=response.text,+ status_code=response.status_code,+ headers=response.headers,+ )+return provider_config.transform_file_content_response(raw_response=response,logging_obj=logging_obj,diff --git a/tests/proxy_unit_tests/test_check_batch_cost.py b/tests/proxy_unit_tests/test_check_batch_cost.pyindex 63bbe147801..f8f15f2e008 100644--- a/tests/proxy_unit_tests/test_check_batch_cost.py+++ b/tests/proxy_unit_tests/test_check_batch_cost.py@@ -397,6 +397,72 @@ class TestCheckBatchCost:), "update() must include batch_processed=True when column is present"assert update_data["status"] == "complete"+ @pytest.mark.asyncio+ async def test_cost_tracking_failure_leaves_job_unprocessed(+ self, check_batch_cost_instance, mock_prisma_client, mock_llm_router+ ):+ """LIT-4008 regression: when fetching a completed batch's results fails+ (e.g. Anthropic rejecting a msgbatch_ id on the Files API), the job must+ NOT be marked complete/batch_processed. Pre-fix the $0 spend row was+ written and batch_processed=True made it permanent; the failure must+ instead leave the row untouched so the next poll retries, without+ aborting the poll cycle.+ """+ from unittest.mock import patch++ mock_prisma_client.db.litellm_managedobjecttable.update_many = AsyncMock(+ return_value=0+ )+ mock_prisma_client.db.litellm_managedobjecttable.update = AsyncMock()+ mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(+ return_value=None+ )++ mock_job = MagicMock()+ mock_job.id = "job-anthropic-1"+ mock_job.unified_object_id = "dW5pZmllZF9iYXRjaF9pZA=="+ mock_job.created_by = "user-1"++ mock_prisma_client.db.litellm_managedobjecttable.find_many = AsyncMock(+ return_value=[mock_job]+ )++ mock_response = MagicMock()+ mock_response.status = "completed"+ mock_response.output_file_id = "msgbatch_01WA5hdsa2Xx8w4zyPjV1frs"++ mock_llm_router.aretrieve_batch = AsyncMock(return_value=mock_response)+ mock_llm_router.get_deployment_credentials_with_provider = MagicMock(+ return_value={"api_key": "sk-test", "custom_llm_provider": "anthropic"}+ )++ decoded_id = "llm_model_id,model-123;llm_batch_id,msgbatch_01WA5hdsa2Xx8w4zyPjV1frs;"++ with (+ patch(+ "litellm.proxy.openai_files_endpoints.common_utils._is_base64_encoded_unified_file_id",+ side_effect=[decoded_id, None],+ ),+ patch(+ "litellm.proxy.openai_files_endpoints.common_utils.get_model_id_from_unified_batch_id",+ return_value="model-123",+ ),+ patch(+ "litellm.proxy.openai_files_endpoints.common_utils.get_batch_id_from_unified_batch_id",+ return_value="msgbatch_01WA5hdsa2Xx8w4zyPjV1frs",+ ),+ patch(+ "litellm.files.main.afile_content",+ new_callable=AsyncMock,+ side_effect=Exception("File id must have `file_` prefix."),+ ),+ ):+ await check_batch_cost_instance.check_batch_cost()++ assert (+ mock_prisma_client.db.litellm_managedobjecttable.update.call_count == 0+ ), "a failed cost tracking attempt must not mark the job processed"+@pytest.mark.asyncio@pytest.mark.parametrize("terminal_status", ["failed", "expired", "cancelled"])async def test_terminal_status_marks_job_processed(diff --git a/tests/test_litellm/batches/test_batch_utils.py b/tests/test_litellm/batches/test_batch_utils.pyindex 3aebfcb911e..9de5cd69b1e 100644--- a/tests/test_litellm/batches/test_batch_utils.py+++ b/tests/test_litellm/batches/test_batch_utils.py@@ -733,3 +733,192 @@ def test_total_usage_vertex_disable_transform_path(monkeypatch):usage = bu._get_batch_job_total_usage_from_file_content([], custom_llm_provider="vertex_ai", model_name="gemini-x")assert usage.total_tokens == 3+++def _anthropic_usage(input_tokens, output_tokens, cache_creation=0, cache_read=0):+ return {+ "input_tokens": input_tokens,+ "output_tokens": output_tokens,+ "cache_creation_input_tokens": cache_creation,+ "cache_read_input_tokens": cache_read,+ }+++def _anthropic_succeeded_row(model="claude-sonnet-4-5-20250929", usage=None):+ return {+ "custom_id": "req-1",+ "result": {+ "type": "succeeded",+ "message": {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "model": model,+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "usage": usage or _anthropic_usage(10, 5),+ },+ },+ }+++def _anthropic_errored_row():+ return {+ "custom_id": "req-2",+ "result": {+ "type": "errored",+ "error": {"type": "invalid_request_error", "message": "bad request"},+ },+ }+++_ANTHROPIC_MODEL_INFO = {+ "input_cost_per_token": 3e-6,+ "output_cost_per_token": 15e-6,+ "cache_read_input_token_cost": 3e-7,+ "cache_creation_input_token_cost": 3.75e-6,+}+++ "row,expected",+ [+ (_anthropic_succeeded_row(), True),+ (_anthropic_errored_row(), False),+ ({"custom_id": "x", "result": {"type": "canceled"}}, False),+ ({"custom_id": "x", "result": {"type": "expired"}}, False),+ ({"custom_id": "x"}, False),+ ({"custom_id": "x", "result": None}, False),+ ],+)+def test_anthropic_result_line_success_check(row, expected):+ """+ LIT-4008 regression: anthropic batch results JSONL lines are not+ OpenAI-shaped; success is result.type == "succeeded", not+ response.status_code == 200. Pre-fix every anthropic line parsed as+ unsuccessful, so completed batches were billed $0 forever.+ """+ assert bu._batch_response_was_successful(row, custom_llm_provider="anthropic") is expected+++def test_anthropic_response_body_is_result_message():+ row = _anthropic_succeeded_row(model="claude-sonnet-4-5-20250929")+ body = bu._get_response_from_batch_job_output_file(row, custom_llm_provider="anthropic")+ assert body["model"] == "claude-sonnet-4-5-20250929"+ assert body["usage"] == _anthropic_usage(10, 5)+++def test_anthropic_usage_conversion_includes_cache_tokens():+ body = {"model": "claude-sonnet-4-5-20250929", "usage": _anthropic_usage(1000, 200, cache_creation=2000, cache_read=8000)}+ usage = bu._get_batch_job_usage_from_response_body(body, custom_llm_provider="anthropic")+ assert usage.prompt_tokens == 11000+ assert usage.completion_tokens == 200+ assert usage.total_tokens == 11200+ assert usage.prompt_tokens_details.cached_tokens == 8000+ assert usage.prompt_tokens_details.cache_creation_tokens == 2000+++def test_anthropic_total_usage_sums_succeeded_only():+ rows = [+ _anthropic_succeeded_row(usage=_anthropic_usage(10, 5)),+ _anthropic_errored_row(),+ _anthropic_succeeded_row(usage=_anthropic_usage(20, 10, cache_read=100)),+ ]+ usage = bu._get_batch_job_total_usage_from_file_content(rows, custom_llm_provider="anthropic")+ assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (130, 15, 145)+++def test_anthropic_total_usage_aggregates_cache_token_details():+ rows = [+ _anthropic_succeeded_row(usage=_anthropic_usage(1000, 200, cache_creation=2000, cache_read=8000)),+ _anthropic_errored_row(),+ _anthropic_succeeded_row(usage=_anthropic_usage(50, 20, cache_creation=300, cache_read=700)),+ ]+ usage = bu._get_batch_job_total_usage_from_file_content(rows, custom_llm_provider="anthropic")+ assert usage.prompt_tokens_details.cached_tokens == 8700+ assert usage.prompt_tokens_details.cache_creation_tokens == 2300+ assert usage.cache_read_input_tokens == 8700+ assert usage.cache_creation_input_tokens == 2300+++def test_total_usage_without_cache_tokens_has_no_prompt_details():+ rows = [+ {+ "custom_id": "req-1",+ "response": {"status_code": 200, "body": {"model": "gpt-5.2", "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}},+ }+ ]+ usage = bu._get_batch_job_total_usage_from_file_content(rows, custom_llm_provider="openai")+ assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (10, 5, 15)+ assert usage.prompt_tokens_details is None+++def test_anthropic_cost_applies_batch_discount_and_cache_pricing():+ """Anthropic batches bill at 50% of the regular rate for base input,+ cache reads, cache writes, and output tokens alike."""+ rows = [+ _anthropic_succeeded_row(usage=_anthropic_usage(1000, 200, cache_creation=2000, cache_read=8000)),+ _anthropic_errored_row(),+ ]++ total = bu._get_batch_job_cost_from_file_content(+ rows,+ custom_llm_provider="anthropic",+ model_info=_ANTHROPIC_MODEL_INFO, # type: ignore[arg-type]+ )++ expected_half_price = (1000 * 3e-6 + 8000 * 3e-7 + 2000 * 3.75e-6 + 200 * 15e-6) / 2+ assert total == pytest.approx(expected_half_price)+++def test_anthropic_cost_without_model_info_uses_batch_cost_calculator(monkeypatch):+ import litellm.cost_calculator as cc++ seen = []++ def _fake_batch_cost_calculator(**kw):+ seen.append(kw)+ return (0.1, 0.2)++ monkeypatch.setattr(cc, "batch_cost_calculator", _fake_batch_cost_calculator)+ monkeypatch.setattr(+ litellm,+ "completion_cost",+ lambda **kw: pytest.fail("anthropic rows must not go through completion_cost"),+ )++ total = bu._get_batch_job_cost_from_file_content(+ [_anthropic_succeeded_row()], custom_llm_provider="anthropic"+ )++ assert total == pytest.approx(0.3)+ assert seen[0]["model"] == "claude-sonnet-4-5-20250929"+ assert seen[0]["custom_llm_provider"] == "anthropic"+ assert seen[0]["usage"].prompt_tokens == 10+++def test_anthropic_batch_models_collected_from_succeeded_rows():+ rows = [+ _anthropic_succeeded_row(model="claude-sonnet-4-5-20250929"),+ _anthropic_errored_row(),+ ]+ assert bu._get_batch_models_from_file_content(rows, None, "anthropic") == ["claude-sonnet-4-5-20250929"]+++async def test_calculate_batch_cost_and_usage_anthropic_end_to_end():+ rows = [+ _anthropic_succeeded_row(usage=_anthropic_usage(1000, 200, cache_creation=2000, cache_read=8000)),+ _anthropic_errored_row(),+ ]++ cost, usage, models = await bu.calculate_batch_cost_and_usage(+ file_content_dictionary=rows,+ custom_llm_provider="anthropic",+ model_name="claude-sonnet-4-5",+ model_info=_ANTHROPIC_MODEL_INFO, # type: ignore[arg-type]+ )++ assert cost == pytest.approx(1000 * 3e-6 / 2 + 8000 * 3e-7 / 2 + 2000 * 3.75e-6 / 2 + 200 * 15e-6 / 2)+ assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (11000, 200, 11200)+ assert models == ["claude-sonnet-4-5"]diff --git a/tests/test_litellm/llms/anthropic/files/test_anthropic_files_transformation.py b/tests/test_litellm/llms/anthropic/files/test_anthropic_files_transformation.pyindex 9fc4981510f..d9763f173a7 100644--- a/tests/test_litellm/llms/anthropic/files/test_anthropic_files_transformation.py+++ b/tests/test_litellm/llms/anthropic/files/test_anthropic_files_transformation.py@@ -309,6 +309,31 @@ class TestAnthropicFilesConfig:assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files/file-abc123/content"assert params == {}+ def test_transform_file_content_request_routes_message_batch_id_to_batch_results(self):+ """+ Regression test for anthropic passthrough batch cost tracking (LIT-4008).++ Anthropic batch results are exposed via output_file_id=<msgbatch_...>.+ The Files API rejects those ids ("File id must have `file_` prefix"),+ so file content for a msgbatch_ id must be fetched from the message+ batches results endpoint instead.+ """+ url, params = self.config.transform_file_content_request(+ file_content_request={"file_id": "msgbatch_01WA5hdsa2Xx8w4zyPjV1frs"},+ optional_params={},+ litellm_params={},+ )+ assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/messages/batches/msgbatch_01WA5hdsa2Xx8w4zyPjV1frs/results"+ assert params == {}++ def test_transform_file_content_request_message_batch_id_custom_api_base(self):+ url, _ = self.config.transform_file_content_request(+ file_content_request={"file_id": "msgbatch_abc"},+ optional_params={},+ litellm_params={"api_base": "https://custom.example.com/"},+ )+ assert url == "https://custom.example.com/v1/messages/batches/msgbatch_abc/results"+def test_transform_file_content_request_rejects_dot_segment(self):with pytest.raises(ValueError, match="file_id cannot be a dot path segment"):self.config.transform_file_content_request(diff --git a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.pyindex 961f95a0659..f7808d23858 100644--- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py+++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py@@ -1685,3 +1685,63 @@ async def test_async_audio_transcriptions_sends_dict_data_as_json_body():assert captured["content_type"] == "application/json"assert captured["body"] == {"config": {"model": "test-model"}, "content": "YXVkaW8="}assert response.text == "transcribed"+++async def test_async_retrieve_file_content_raises_on_http_error():+ """+ LIT-4008 regression: a provider error response (e.g. Anthropic's 400+ "File id must have `file_` prefix") must raise instead of being wrapped+ as file content, which downstream batch cost tracking would parse as an+ empty results file and bill $0.+ """+ from litellm.llms.anthropic.common_utils import AnthropicError+ from litellm.llms.anthropic.files.transformation import AnthropicFilesConfig++ handler = BaseLLMHTTPHandler()+ client = Mock(spec=AsyncHTTPHandler)+ client.get = AsyncMock(+ return_value=httpx.Response(+ status_code=400,+ content=b'{"type":"error","error":{"type":"invalid_request_error","message":"File id must have `file_` prefix."}}',+ )+ )++ with pytest.raises(AnthropicError) as exc_info:+ await handler.async_retrieve_file_content(+ file_content_request={"file_id": "msgbatch_123"},+ provider_config=AnthropicFilesConfig(),+ litellm_params={"api_key": "sk-test"},+ headers={},+ logging_obj=Mock(),+ client=client,+ )++ assert exc_info.value.status_code == 400+ assert "file_" in str(exc_info.value)+++def test_sync_retrieve_file_content_raises_on_http_error():+ from litellm.llms.anthropic.common_utils import AnthropicError+ from litellm.llms.anthropic.files.transformation import AnthropicFilesConfig++ handler = BaseLLMHTTPHandler()+ client = Mock(spec=HTTPHandler)+ client.get = Mock(+ return_value=httpx.Response(+ status_code=404,+ content=b'{"type":"error","error":{"type":"not_found_error","message":"not found"}}',+ )+ )++ with pytest.raises(AnthropicError) as exc_info:+ handler.retrieve_file_content(+ file_content_request={"file_id": "file-abc"},+ provider_config=AnthropicFilesConfig(),+ litellm_params={"api_key": "sk-test"},+ headers={},+ logging_obj=Mock(),+ client=client,+ )++ assert exc_info.value.status_code == 404diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.pyindex 93bdb40ae2b..751177014ce 100644--- a/tests/test_litellm/test_cost_calculator.py+++ b/tests/test_litellm/test_cost_calculator.py@@ -3318,3 +3318,60 @@ def test_cost_per_token_per_second_pricing(monkeypatch):assert prompt_cost == pytest.approx(0.02 * 1.5)assert completion_cost_value == pytest.approx(0.04 * 1.5)+++def _batch_cache_usage() -> Usage:+ return Usage(+ prompt_tokens=11000,+ completion_tokens=200,+ total_tokens=11200,+ prompt_tokens_details=PromptTokensDetailsWrapper(+ cached_tokens=8000,+ cache_creation_tokens=2000,+ text_tokens=1000,+ ),+ cache_creation_input_tokens=2000,+ cache_read_input_tokens=8000,+ )+++def test_batch_cost_calculator_prices_cache_creation_tokens_at_cache_write_rate():+ """+ LIT-4008 regression: anthropic batch usage is dominated by cache tokens.+ Cache creation tokens must be priced at cache_creation_input_token_cost / 2,+ not folded into the base input rate, and must not also be billed as base+ input tokens.+ """+ from litellm.cost_calculator import batch_cost_calculator++ prompt_cost, completion_cost_value = batch_cost_calculator(+ usage=_batch_cache_usage(),+ model="claude-sonnet-4-5-20250929",+ custom_llm_provider="anthropic",+ model_info={ # type: ignore[arg-type]+ "input_cost_per_token": 3e-6,+ "output_cost_per_token": 15e-6,+ "cache_read_input_token_cost": 3e-7,+ "cache_creation_input_token_cost": 3.75e-6,+ },+ )++ assert prompt_cost == pytest.approx((1000 * 3e-6 + 8000 * 3e-7 + 2000 * 3.75e-6) / 2)+ assert completion_cost_value == pytest.approx(200 * 15e-6 / 2)+++def test_batch_cost_calculator_cache_creation_falls_back_to_input_rate():+ from litellm.cost_calculator import batch_cost_calculator++ prompt_cost, _ = batch_cost_calculator(+ usage=_batch_cache_usage(),+ model="claude-sonnet-4-5-20250929",+ custom_llm_provider="anthropic",+ model_info={ # type: ignore[arg-type]+ "input_cost_per_token": 3e-6,+ "output_cost_per_token": 15e-6,+ "cache_read_input_token_cost": 3e-7,+ },+ )++ assert prompt_cost == pytest.approx((1000 * 3e-6 + 8000 * 3e-7 + 2000 * 3e-6) / 2)