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
Merge remote-tracking branch 'berri/litellm_internal_staging' into litellm_managed_batches_observability
mubashir1osmani4401b85855a8
diff --cc litellm/batches/batch_utils.pyindex 4889be3c0f6,be23972de14..8a42efd6dc5--- a/litellm/batches/batch_utils.py+++ b/litellm/batches/batch_utils.py@@@ -70,29 -59,33 +70,40 @@@ async def _handle_completed_batchmodel_name: Optional model namelitellm_params: Optional litellm parameters containing credentials (api_key, api_base, etc.)"""+ # A completed batch whose request lines all failed has no output file - the+ # results are written to a separate error_file_id and output_file_id is None.+ # There is nothing to price or measure, so report an empty result set instead+ # of calling _fetch_batch_output_file_content, which raises on a missing+ # output file. Without this guard the logging worker crashes on every+ # aretrieve_batch poll and the completed batch's zero-cost accounting is lost.+ # The generic retrieval helper keeps raising for callers that explicitly ask+ # for a missing output file.+ if batch.output_file_id is None:+ return 0.0, Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0), []+file_content = await _fetch_batch_output_file_content(batch, custom_llm_provider, litellm_params=litellm_params)+ error_file_failed_requests: Final = await _count_error_file_failed_requests(+ batch, custom_llm_provider=custom_llm_provider, litellm_params=litellm_params+ )- if (- custom_llm_provider == "vertex_ai"- and model_name- and getattr(litellm, "disable_vertex_batch_output_transformation", False)- ):- batch_cost, batch_usage = calculate_vertex_ai_batch_cost_and_usage(- _get_file_content_as_dictionary(file_content), model_name+ output_file_result: Final = (+ calculate_vertex_ai_batch_cost_and_usage(_get_file_content_as_dictionary(file_content), model_name)+ if (+ custom_llm_provider == "vertex_ai"+ and model_name+ and getattr(litellm, "disable_vertex_batch_output_transformation", False))- return batch_cost, batch_usage, [model_name]+ else _aggregate_batch_cost_usage_models(+ entries=_iter_batch_input_entries(file_content),+ custom_llm_provider=custom_llm_provider,+ model_name=model_name,+ )+ )- return _aggregate_batch_cost_usage_models(- entries=_iter_batch_input_entries(file_content),- custom_llm_provider=custom_llm_provider,- model_name=model_name,+ if not error_file_failed_requests:+ return output_file_result+ return dataclasses_replace(+ output_file_result, failed_requests=output_file_result.failed_requests + error_file_failed_requests)diff --cc tests/test_litellm/batches/test_batch_utils.pyindex 06f42ce7b51,68e40ac2c81..daf3b91a26b--- a/tests/test_litellm/batches/test_batch_utils.py+++ b/tests/test_litellm/batches/test_batch_utils.py@@@ -1041,76 -971,34 +1042,97 @@@ async def test_handle_completed_batch_omonkeypatch.setattr(bu, "_fetch_batch_output_file_content", fake_fetch)monkeypatch.setattr(litellm, "completion_cost", lambda **kw: 3.3)- cost, usage, models = await bu._handle_completed_batch(_batch("of"), custom_llm_provider="openai")+ result = await bu._handle_completed_batch(_batch("of"), custom_llm_provider="openai")- assert cost == 3.3- assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (10, 5, 15)- assert models == ["gpt-4o"]+ assert result.cost == 3.3+ assert (result.usage.prompt_tokens, result.usage.completion_tokens, result.usage.total_tokens) == (10, 5, 15)+ assert result.models == ["gpt-4o"]+++async def test_handle_completed_batch_counts_error_file_failures(monkeypatch):+ """Regression test: OpenAI writes per-request failures (e.g. a rejected param)+ to a separate error_file_id, never into the output file - so failed_requests+ must include them or it silently undercounts real batch failures."""+ from litellm.types.llms.openai import Batch++ rows = [_success_row(model="gpt-5-mini", usage=_usage(24, 107))]+ error_rows = [+ {+ "id": "batch_req_err1",+ "custom_id": "req-2-bad",+ "response": {"status_code": 400, "body": {"error": {"message": "Invalid 'temperature'"}}},+ "error": None,+ }+ ]++ async def fake_fetch(batch, custom_llm_provider, litellm_params=None):+ return _vertex_jsonl(rows)++ async def fake_afile_content(**kw):+ return type("R", (), {"content": _vertex_jsonl(error_rows)})()++ import litellm.files.main as files_main++ monkeypatch.setattr(bu, "_fetch_batch_output_file_content", fake_fetch)+ monkeypatch.setattr(files_main, "afile_content", fake_afile_content)+ monkeypatch.setattr(litellm, "completion_cost", lambda **kw: 0.0)++ batch = Batch(+ id="b",+ completion_window="24h",+ created_at=1,+ endpoint="/v1/chat/completions",+ input_file_id="f",+ object="batch",+ status="completed",+ output_file_id="of",+ error_file_id="ef",+ )++ result = await bu._handle_completed_batch(batch, custom_llm_provider="openai")++ assert result.successful_requests == 1+ assert result.failed_requests == 1+++async def test_handle_completed_batch_no_error_file_id_reports_zero_error_failures(monkeypatch):+ rows = [_success_row(model="gpt-4o", usage=_usage(10, 5))]++ async def fake_fetch(batch, custom_llm_provider, litellm_params=None):+ return _vertex_jsonl(rows)++ monkeypatch.setattr(bu, "_fetch_batch_output_file_content", fake_fetch)+ monkeypatch.setattr(litellm, "completion_cost", lambda **kw: 0.0)++ result = await bu._handle_completed_batch(_batch("of"), custom_llm_provider="openai")++ assert result.successful_requests == 1+ assert result.failed_requests == 0+ @pytest.mark.asyncio+ async def test_handle_completed_batch_no_output_file_is_zero(monkeypatch):+ """+ Regression: an all-error batch completes with output_file_id=None (results go+ to a separate error_file_id). _handle_completed_batch must report an empty+ result set - zero cost, zero usage, no models - instead of letting the file+ fetch raise "Output file id is None" on every aretrieve_batch logging poll.+ """+ # The output-file fetch must not even be attempted when there is no output file.+ async def _must_not_fetch(*args, **kwargs):+ pytest.fail("_fetch_batch_output_file_content should not be called")++ monkeypatch.setattr(bu, "_fetch_batch_output_file_content", _must_not_fetch)++ cost, usage, models = await bu._handle_completed_batch(_batch(None), custom_llm_provider="openai")++ assert cost == 0.0+ assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (0, 0, 0)+ assert models == []++@pytest.mark.asyncioasync def test_handle_completed_batch_vertex_disable_transform_path(monkeypatch):raw_rows = [{"response": {"usageMetadata": {"promptTokenCount": 1, "candidatesTokenCount": 2}}}]