litellm/tests/unit/batches/test_main.py
mika-lt c74b785396
fix(router,files,batches)!: never resend a file or batch create the provider may already have (#51315)
* fix(files,batches): never resend a timed-out file or batch create

A file upload or batch create that hit the caller's timeout was sent again by the OpenAI SDK's retries and then by the router's retries and same-group fallbacks, so Azure and OpenAI kept up to 3 billed copies the caller never heard about. Creates now go out with SDK retries off, and the router re-raises a timed-out create instead of retrying or falling back

* fix(router): stop resending a create that times out on a retry or a fallback

A file or batch create that timed out after it was sent is no longer retried
or sent to the next order fallback, wherever the timeout happens. A connect
or pool timeout means the request never left LiteLLM, so it is still retried
and sent to a fallback like a connection error

* fix(files,batches): resend a create only when a resend cannot make a duplicate

File and batch creates sent without the router lost every SDK retry on this branch. They now go out with SDK retries off, and LiteLLM resends them itself only when a resend cannot create a second object. That is when the provider answered with a status the SDK would retry (x-should-retry wins, else 408, 409, 429 or 5xx), or when the request never left (a connect error, connect timeout or pool timeout). The budget is the client's own max_retries, and the wait comes from calculate_retry_after. The router uses the same "timed out after send" check, so the two layers cannot disagree

The httpx handler now chains the httpx error as the cause of litellm.Timeout, so a connect timeout on an Anthropic, Bedrock, Mistral or xAI upload is retried again like on main. A timed-out create through a model group keeps the "No fallback was attempted" note, and the router logs one info line when it stops

The proxy create-file and create-batch routes add x-should-retry false to a create that timed out after it was sent, so OpenAI and Anthropic SDK callers do not resend it. Status and body stay the same

Uploading a file to every deployment now waits for all of them and raises the after-send timeout when there is one, so a fast 429 from one deployment can no longer hide it and trigger a resend to the slow one

Tests cover the resend rules for sync and async on OpenAI and Azure, the Anthropic upload retries, the fallback note and log, the proxy header, the multi-deployment upload, and the aiohttp timeout classes

* fix(router,files,batches)!: do not resend a create the provider may already have made

A file or batch create is no longer resent by the SDK, the router's retries, or a router fallback when the provider may already have it. That covers a timeout after the request was sent, a connection that dropped after it was sent, a 504, and any answer that says x-should-retry: false. Creates on the httpx handler (Mistral and Bedrock batches, Gemini, Vertex AI and Manus uploads) now keep the transport error as the cause of the provider error, so the router sees the timeout too

A create that cannot have made anything is still resent, and a proxy write timeout or a refused egress proxy now count as that. A real 408 answer, 500, 502 and 503 keep the same handling as before

The proxy create-file and create-batch routes answer such a failure with x-should-retry: false and add a sentence to the error message that tells the caller to list their files or batches before they send it again

BREAKING CHANGE: a 504 on a file or batch create is no longer resent by the SDK or retried by the router unless the answer says x-should-retry: true

* fix(router,files,batches): keep retries and fallbacks after a create the provider rejected

Anthropic sends x-should-retry: false on every 4xx, so a model group upload with a bad key on its
first deployment stopped there with a 401 and a note saying the file may already exist. A 4xx other
than 408 now counts as nothing created, whatever the header says, so the router retries and falls
back the way it did before and the proxy adds no note or header to it

* fix(files,batches): number each resent create and keep stream timeouts as litellm.Timeout

Each resend of a file or batch create now carries its attempt number in
x-stainless-retry-count and keeps the caller's extra headers, the way the
SDK numbered its own resends. The httpx handler's timeout keeps base's
shape, so a Gemini stream that times out at open still raises
litellm.Timeout, and the create check follows the timeout's context to the
httpx error instead. A proxy integration test counts upstream POSTs for a
timed-out /v1/files and /v1/batches create on the default transport.

* fix(files,batches): stop resending a group upload that one deployment already created

A group upload where some deployments created the file and another failed now counts as a create that may exist, so the router does not resend it and the caller gets the notice. A failed GET never counts as may exist, and a write error or a local protocol error is resent, since the body never fully arrived. The notice now says to check the newest files or batches

* fix(router): keep the provider error when a group upload partly fails

A group upload where some deployments created the file and another failed now raises the failing deployment's own error, with a marker in its cause chain that says the file may exist. The caller gets the provider's message and the router's note again, instead of a generic error that showed the deployment's URL

* fix(router): keep the no-fallback note on every provider error from a create that may exist

A group upload that one Anthropic, Vertex AI, Gemini or Manus deployment rejected lost the router's note, since the note was added only to OpenAI errors

* fix(router): leave out the no-fallback note when a create stops after an order fallback

A create that fails at a later order level after an earlier level fell back now ends without
the "No fallback was attempted" note, since a fallback did run. The proxy's notice that the
provider may already hold the file or batch still comes through

* test: allowlist the bounded _cause_chain recursion in the recursion detector

* fix(router): keep retrying a create whose retry never connected, and keep the caller's create headers

The router's retry loop overwrote a retry error's __context__ with the hop's first error, which dropped the httpx ConnectTimeout behind an http-handler litellm.Timeout. The second attempt then read as a create that may already exist, so an Anthropic upload that never connected stopped retrying and skipped a healthy order fallback. The first error now goes at the end of the context chain

A create's extra_headers sent as a list are passed through unchanged again instead of being dropped, and a caller's own retry-count header in any case is no longer sent next to ours

Also applies cargo fmt to call.rs for the rust-lint job

* fix(files): treat a failed read as no create, whatever error wraps it

A GET that failed with an openai.APIStatusError no longer counts as a create that may already exist, so reads stay retryable. Tests now record the resend wait instead of timing it, and the duplicate Anthropic file fixture is gone

* fix(router,files): keep a create that may exist after a redirect or a fallback from being sent again

A gateway that takes an upload, answers 303 and fails the followed GET with a 504 now counts as a create that may exist, since the check reads the request the redirect started from

A fallbacks hop whose create may exist now ends the walk and is the error the caller gets, and a weighted failover whose create may exist skips the regular fallbacks

* test(router): mark the create-may-exist fallback tests with rstest

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-25 07:20:51 +00:00

1684 lines
63 KiB
Python

"""
Provider-dispatch contract tests for litellm/batches/main.py
main.py is the SDK layer beneath the proxy batch endpoints: each of
create/retrieve/list/cancel_batch is a switch on `custom_llm_provider` (and, for
create/retrieve, on whether a provider-config + model is present) that hands off
to exactly one provider handler. These tests lock that dispatch:
1. DISPATCH - exactly which provider seam fired (openai_batches_instance vs
azure vs vertex vs anthropic vs base_llm_http_handler vs the
Bedrock ARN handlers), with every sibling seam asserted NOT
called. A reordered/negated branch flips this.
2. PAYLOAD - the request object (CreateBatchRequest/RetrieveBatchRequest/...)
and the _is_async flag forwarded to the handler.
3. RESULT - the handler's return value is what the function returns.
4. DELEGATION - the async wrappers (a*_batch) forward to the sync function in an
executor with the right "_is_async" flag, and pass the result
back untouched.
Only the provider handler instances are mocked (true network boundaries). The
real public functions run (including the @client decorator) so dispatch reflects
production. Provider env vars are not required: missing creds resolve to None and
flow through harmlessly because the handler is mocked.
"""
from contextlib import ExitStack
from dataclasses import dataclass
from typing import Any, Dict
from types import MappingProxyType
from unittest.mock import MagicMock, patch
import pytest
import litellm
import litellm.batches.main as bm
import asyncio
import datetime
import json
from collections.abc import Awaitable, Callable, Mapping, Sequence
from typing import Final
import httpx
import openai
import respx
from pydantic import TypeAdapter, ValidationError
from typing_extensions import ReadOnly, TypedDict
from litellm.integrations.custom_logger import CustomLogger
from openai.types.batch import Batch
from litellm.types.utils import LiteLLMBatch, admin_api_key_secret_reference
# --------------------------------------------------------------------------- #
# Seam harness - one mock per provider handler instance + the Bedrock ARN
# handler. Each handler method auto-returns a unique sentinel (its
# return_value), so "result is seam.<method>.return_value" verifies dispatch.
# --------------------------------------------------------------------------- #
@dataclass
class Seams:
openai: MagicMock
azure: MagicMock
vertex: MagicMock
anthropic: MagicMock
base_http: MagicMock
bedrock_arn: MagicMock
@pytest.fixture
def seams():
openai_i = MagicMock(name="openai_batches_instance")
azure_i = MagicMock(name="azure_batches_instance")
vertex_i = MagicMock(name="vertex_ai_batches_instance")
anthropic_i = MagicMock(name="anthropic_batches_instance")
base_http = MagicMock(name="base_llm_http_handler")
bedrock_arn = MagicMock(name="BedrockBatchesHandler")
with ExitStack() as stack:
stack.enter_context(patch.object(bm, "openai_batches_instance", openai_i))
stack.enter_context(patch.object(bm, "azure_batches_instance", azure_i))
stack.enter_context(patch.object(bm, "vertex_ai_batches_instance", vertex_i))
stack.enter_context(patch.object(bm, "anthropic_batches_instance", anthropic_i))
stack.enter_context(patch.object(bm, "base_llm_http_handler", base_http))
stack.enter_context(patch.object(bm, "BedrockBatchesHandler", bedrock_arn))
yield Seams(
openai=openai_i,
azure=azure_i,
vertex=vertex_i,
anthropic=anthropic_i,
base_http=base_http,
bedrock_arn=bedrock_arn,
)
# Every <op> handler method across all provider instances - used to assert
# "no sibling seam fired" exhaustively.
def _all_seam_methods(seams: Seams, op: str):
return [
getattr(seams.openai, op),
getattr(seams.azure, op),
getattr(seams.vertex, op),
getattr(seams.anthropic, op),
getattr(seams.base_http, op),
]
def _assert_only(fired, seams: Seams, op: str):
"""Assert `fired` was called exactly once and every other op seam was not."""
assert fired.call_count == 1
for m in _all_seam_methods(seams, op):
if m is not fired:
m.assert_not_called()
CREATE_KW: Dict[str, Any] = dict(
completion_window="24h",
endpoint="/v1/chat/completions",
input_file_id="file-abc",
)
# =========================================================================== #
# create_batch
# =========================================================================== #
def test_create__openai_dispatch_and_payload(seams):
result = bm.create_batch(**CREATE_KW, custom_llm_provider="openai")
# DISPATCH + RESULT
assert result is seams.openai.create_batch.return_value
_assert_only(seams.openai.create_batch, seams, "create_batch")
seams.bedrock_arn.handle_async_invoke_status.assert_not_called()
# PAYLOAD - request object built from the call, sync flag off.
kw = seams.openai.create_batch.call_args.kwargs
assert kw["create_batch_data"] == {
"completion_window": "24h",
"endpoint": "/v1/chat/completions",
"input_file_id": "file-abc",
"metadata": None,
"extra_headers": None,
"extra_body": None,
}
assert kw["_is_async"] is False
assert kw["timeout"] == 600.0
def test_create__hosted_vllm_routes_to_openai_instance(seams):
"""hosted_vllm is in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS, so it shares
the openai handler. Locks that set membership."""
result = bm.create_batch(**CREATE_KW, custom_llm_provider="hosted_vllm")
assert result is seams.openai.create_batch.return_value
_assert_only(seams.openai.create_batch, seams, "create_batch")
def test_create__azure_dispatch(seams):
result = bm.create_batch(**CREATE_KW, custom_llm_provider="azure")
assert result is seams.azure.create_batch.return_value
_assert_only(seams.azure.create_batch, seams, "create_batch")
def test_create__vertex_ai_dispatch(seams):
result = bm.create_batch(**CREATE_KW, custom_llm_provider="vertex_ai")
assert result is seams.vertex.create_batch.return_value
_assert_only(seams.vertex.create_batch, seams, "create_batch")
def test_create__vertex_ai_forwards_custom_endpoint(seams):
"""The vertex handler owns the custom_endpoint batch rejection (LIT-6899), so the dispatcher
must forward the flag for the handler to act on."""
bm.create_batch(**CREATE_KW, custom_llm_provider="vertex_ai", custom_endpoint=True)
assert seams.vertex.create_batch.call_args.kwargs["custom_endpoint"] is True
def test_create__provider_config_routes_to_base_http_handler(seams):
"""model + a provider batches config (bedrock-style) routes to the generic
base_llm_http_handler, NOT the per-provider instance."""
with patch.object(
bm.ProviderConfigManager,
"get_provider_batches_config",
return_value=MagicMock(name="provider_config"),
):
result = bm.create_batch(**CREATE_KW, custom_llm_provider="bedrock", model="bedrock/my-batch-model")
assert result is seams.base_http.create_batch.return_value
_assert_only(seams.base_http.create_batch, seams, "create_batch")
def test_create__unsupported_provider_raises_badrequest(seams):
with pytest.raises(litellm.exceptions.BadRequestError):
bm.create_batch(**CREATE_KW, custom_llm_provider="cohere") # type: ignore[arg-type]
for m in _all_seam_methods(seams, "create_batch"):
m.assert_not_called()
@pytest.mark.asyncio
async def test_create__async_path_propagates_is_async(seams):
"""Through the real async wrapper, the handler is invoked with _is_async=True.
(Calling the @client sync create_batch with acreate_batch=True directly is not
a real code path - logging-obj setup only happens on the async wrapper path.)"""
await bm.acreate_batch(**CREATE_KW, custom_llm_provider="openai")
assert seams.openai.create_batch.call_args.kwargs["_is_async"] is True
# =========================================================================== #
# retrieve_batch
# =========================================================================== #
def test_retrieve__openai_dispatch_and_payload(seams):
result = bm.retrieve_batch(batch_id="batch-1", custom_llm_provider="openai")
assert result is seams.openai.retrieve_batch.return_value
_assert_only(seams.openai.retrieve_batch, seams, "retrieve_batch")
kw = seams.openai.retrieve_batch.call_args.kwargs
assert kw["retrieve_batch_data"] == {
"batch_id": "batch-1",
"extra_headers": None,
"extra_body": None,
}
assert kw["_is_async"] is False
def test_retrieve__hosted_vllm_routes_to_openai_instance(seams):
result = bm.retrieve_batch(batch_id="batch-1", custom_llm_provider="hosted_vllm")
assert result is seams.openai.retrieve_batch.return_value
_assert_only(seams.openai.retrieve_batch, seams, "retrieve_batch")
def test_retrieve__azure_dispatch(seams):
result = bm.retrieve_batch(batch_id="batch-1", custom_llm_provider="azure")
assert result is seams.azure.retrieve_batch.return_value
_assert_only(seams.azure.retrieve_batch, seams, "retrieve_batch")
def test_retrieve__vertex_ai_dispatch(seams):
result = bm.retrieve_batch(batch_id="batch-1", custom_llm_provider="vertex_ai")
assert result is seams.vertex.retrieve_batch.return_value
_assert_only(seams.vertex.retrieve_batch, seams, "retrieve_batch")
def test_retrieve__anthropic_dispatch(seams):
"""anthropic is retrieve-capable (not in create's provider set)."""
result = bm.retrieve_batch(batch_id="batch-1", custom_llm_provider="anthropic")
assert result is seams.anthropic.retrieve_batch.return_value
_assert_only(seams.anthropic.retrieve_batch, seams, "retrieve_batch")
def test_retrieve__provider_config_routes_to_base_http_handler(seams):
with patch.object(
bm.ProviderConfigManager,
"get_provider_batches_config",
return_value=MagicMock(name="provider_config"),
):
result = bm.retrieve_batch(
batch_id="batch-1",
custom_llm_provider="bedrock",
model="bedrock/my-batch-model",
)
assert result is seams.base_http.retrieve_batch.return_value
_assert_only(seams.base_http.retrieve_batch, seams, "retrieve_batch")
def test_retrieve__bedrock_async_invoke_arn(seams):
arn = "arn:aws:bedrock:us-east-1:123456789012:async-invoke/abc123"
result = bm.retrieve_batch(batch_id=arn, custom_llm_provider="bedrock")
seams.bedrock_arn.handle_async_invoke_status.assert_called_once()
assert result is seams.bedrock_arn.handle_async_invoke_status.return_value
# provider instances untouched.
for m in _all_seam_methods(seams, "retrieve_batch"):
m.assert_not_called()
def test_retrieve__bedrock_model_invocation_job_arn(seams):
arn = "arn:aws:bedrock:us-east-1:123456789012:model-invocation-job/xyz789"
result = bm.retrieve_batch(batch_id=arn, custom_llm_provider="bedrock")
seams.bedrock_arn.handle_model_invocation_job_status.assert_called_once()
assert result is seams.bedrock_arn.handle_model_invocation_job_status.return_value
seams.bedrock_arn.handle_async_invoke_status.assert_not_called()
def test_retrieve__unsupported_provider_raises_badrequest(seams):
with pytest.raises(litellm.exceptions.BadRequestError):
bm.retrieve_batch(batch_id="batch-1", custom_llm_provider="cohere") # type: ignore[arg-type]
for m in _all_seam_methods(seams, "retrieve_batch"):
m.assert_not_called()
# =========================================================================== #
# list_batches (supported: openai, hosted_vllm, azure, vertex_ai)
# =========================================================================== #
def test_list__openai_dispatch_and_payload(seams):
result = bm.list_batches(custom_llm_provider="openai", after="cur", limit=5)
assert result is seams.openai.list_batches.return_value
_assert_only(seams.openai.list_batches, seams, "list_batches")
kw = seams.openai.list_batches.call_args.kwargs
assert kw["after"] == "cur"
assert kw["limit"] == 5
assert kw["_is_async"] is False
def test_list__hosted_vllm_routes_to_openai_instance(seams):
result = bm.list_batches(custom_llm_provider="hosted_vllm")
assert result is seams.openai.list_batches.return_value
_assert_only(seams.openai.list_batches, seams, "list_batches")
def test_list__azure_dispatch(seams):
result = bm.list_batches(custom_llm_provider="azure")
assert result is seams.azure.list_batches.return_value
_assert_only(seams.azure.list_batches, seams, "list_batches")
def test_list__vertex_ai_dispatch(seams):
result = bm.list_batches(custom_llm_provider="vertex_ai")
assert result is seams.vertex.list_batches.return_value
_assert_only(seams.vertex.list_batches, seams, "list_batches")
def test_list__unsupported_provider_raises_badrequest(seams):
# anthropic supports retrieve but NOT list - good negative case.
with pytest.raises(litellm.exceptions.BadRequestError):
bm.list_batches(custom_llm_provider="anthropic") # type: ignore[arg-type]
for m in _all_seam_methods(seams, "list_batches"):
m.assert_not_called()
# =========================================================================== #
# cancel_batch (supported: openai, hosted_vllm, azure, vertex_ai; no @client)
# =========================================================================== #
def test_cancel__openai_dispatch_and_payload(seams):
result = bm.cancel_batch(batch_id="batch-1", custom_llm_provider="openai")
assert result is seams.openai.cancel_batch.return_value
_assert_only(seams.openai.cancel_batch, seams, "cancel_batch")
kw = seams.openai.cancel_batch.call_args.kwargs
assert kw["cancel_batch_data"] == {
"batch_id": "batch-1",
"extra_headers": None,
"extra_body": None,
}
assert kw["_is_async"] is False
def test_cancel__azure_dispatch(seams):
result = bm.cancel_batch(batch_id="batch-1", custom_llm_provider="azure")
assert result is seams.azure.cancel_batch.return_value
_assert_only(seams.azure.cancel_batch, seams, "cancel_batch")
def test_cancel__vertex_ai_dispatch(seams):
result = bm.cancel_batch(batch_id="batch-1", custom_llm_provider="vertex_ai")
assert result is seams.vertex.cancel_batch.return_value
_assert_only(seams.vertex.cancel_batch, seams, "cancel_batch")
def test_cancel__unsupported_provider_raises_badrequest(seams):
with pytest.raises(litellm.exceptions.BadRequestError):
bm.cancel_batch(batch_id="batch-1", custom_llm_provider="cohere")
for m in _all_seam_methods(seams, "cancel_batch"):
m.assert_not_called()
def test_cancel__async_flag_propagates_is_async(seams):
bm.cancel_batch(batch_id="batch-1", custom_llm_provider="openai", acancel_batch=True)
assert seams.openai.cancel_batch.call_args.kwargs["_is_async"] is True
# =========================================================================== #
# Async wrappers - delegate to the sync function in an executor, set the right
# "_is_async" flag, and return the result untouched.
# =========================================================================== #
@pytest.mark.asyncio
async def test_acreate_batch_delegates_to_create_batch():
with patch.object(bm, "create_batch", MagicMock(return_value="SENTINEL")) as m:
result = await bm.acreate_batch(**CREATE_KW, custom_llm_provider="openai")
assert result == "SENTINEL"
assert m.call_count == 1
assert m.call_args.kwargs.get("acreate_batch") is True
# positional handoff: (completion_window, endpoint, input_file_id, provider, ...)
assert m.call_args.args[0] == "24h"
assert m.call_args.args[2] == "file-abc"
assert m.call_args.args[3] == "openai"
@pytest.mark.asyncio
async def test_aretrieve_batch_delegates_to_retrieve_batch():
with patch.object(bm, "retrieve_batch", MagicMock(return_value="SENTINEL")) as m:
result = await bm.aretrieve_batch(batch_id="batch-1", custom_llm_provider="azure")
assert result == "SENTINEL"
assert m.call_count == 1
assert m.call_args.kwargs.get("aretrieve_batch") is True
assert m.call_args.args[0] == "batch-1"
assert m.call_args.args[1] == "azure"
@pytest.mark.asyncio
async def test_alist_batches_delegates_to_list_batches():
with patch.object(bm, "list_batches", MagicMock(return_value="SENTINEL")) as m:
result = await bm.alist_batches(after="cur", limit=3, custom_llm_provider="vertex_ai")
assert result == "SENTINEL"
assert m.call_count == 1
assert m.call_args.kwargs.get("alist_batches") is True
assert m.call_args.args[0] == "cur"
assert m.call_args.args[1] == 3
assert m.call_args.args[2] == "vertex_ai"
@pytest.mark.asyncio
async def test_acancel_batch_delegates_to_cancel_batch():
with patch.object(bm, "cancel_batch", MagicMock(return_value="SENTINEL")) as m:
result = await bm.acancel_batch(batch_id="batch-1", custom_llm_provider="openai")
assert result == "SENTINEL"
assert m.call_count == 1
assert m.call_args.kwargs.get("acancel_batch") is True
assert m.call_args.args[0] == "batch-1"
# =========================================================================== #
# Credential passthrough - when the caller supplies credentials in kwargs, they
# must reach the provider handler. Explicit kwargs win over litellm.* globals and
# env vars (they are first in each `optional_params.x or litellm.x or env` chain),
# so these assertions are deterministic regardless of the test environment.
#
# The credential-resolution blocks are copy-pasted per provider in EACH of
# create/retrieve/list/cancel, so a regression can land in any one independently;
# every function is checked.
# =========================================================================== #
# Distinct values so a cross-wired field (e.g. api_key forwarded as api_base) is
# impossible to miss.
OPENAI_CREDS: Dict[str, Any] = dict(
api_key="sk-user-openai",
api_base="https://openai.user.test",
organization="org-user-123",
max_retries=7,
)
AZURE_CREDS: Dict[str, Any] = dict(
api_key="sk-user-azure",
api_base="https://azure.user.test",
api_version="2024-12-99",
)
VERTEX_CREDS: Dict[str, Any] = dict(
vertex_project="proj-user",
vertex_location="loc-user",
vertex_credentials="cred-user",
api_base="https://vertex.user.test",
)
def _sent(mock_method, *keys):
"""Subset of the call kwargs limited to `keys`, for exact comparison."""
kw = mock_method.call_args.kwargs
return {k: kw.get(k) for k in keys}
# ---- create_batch ---------------------------------------------------------- #
def test_create__openai_credentials_passthrough(seams):
bm.create_batch(**CREATE_KW, custom_llm_provider="openai", **OPENAI_CREDS)
assert _sent(seams.openai.create_batch, "api_key", "api_base", "organization", "max_retries") == {
"api_key": "sk-user-openai",
"api_base": "https://openai.user.test",
"organization": "org-user-123",
"max_retries": 7,
}
def test_create__azure_credentials_passthrough(seams):
bm.create_batch(**CREATE_KW, custom_llm_provider="azure", **AZURE_CREDS)
assert _sent(seams.azure.create_batch, "api_key", "api_base", "api_version") == {
"api_key": "sk-user-azure",
"api_base": "https://azure.user.test",
"api_version": "2024-12-99",
}
def test_create__vertex_credentials_passthrough(seams):
bm.create_batch(**CREATE_KW, custom_llm_provider="vertex_ai", **VERTEX_CREDS)
assert _sent(
seams.vertex.create_batch,
"vertex_project",
"vertex_location",
"vertex_credentials",
"api_base",
) == {
"vertex_project": "proj-user",
"vertex_location": "loc-user",
"vertex_credentials": "cred-user",
"api_base": "https://vertex.user.test",
}
def test_create__provider_config_credentials_passthrough(seams):
with patch.object(
bm.ProviderConfigManager,
"get_provider_batches_config",
return_value=MagicMock(name="provider_config"),
):
bm.create_batch(
**CREATE_KW,
custom_llm_provider="bedrock",
model="bedrock/my-batch-model",
api_key="sk-user-bedrock",
api_base="https://bedrock.user.test",
)
assert _sent(seams.base_http.create_batch, "api_key", "api_base") == {
"api_key": "sk-user-bedrock",
"api_base": "https://bedrock.user.test",
}
# ---- retrieve_batch -------------------------------------------------------- #
def test_retrieve__openai_credentials_passthrough(seams):
bm.retrieve_batch(batch_id="b1", custom_llm_provider="openai", **OPENAI_CREDS)
assert _sent(seams.openai.retrieve_batch, "api_key", "api_base", "organization") == {
"api_key": "sk-user-openai",
"api_base": "https://openai.user.test",
"organization": "org-user-123",
}
def test_retrieve__azure_credentials_passthrough(seams):
bm.retrieve_batch(batch_id="b1", custom_llm_provider="azure", **AZURE_CREDS)
assert _sent(seams.azure.retrieve_batch, "api_key", "api_base", "api_version") == {
"api_key": "sk-user-azure",
"api_base": "https://azure.user.test",
"api_version": "2024-12-99",
}
def test_retrieve__vertex_credentials_passthrough(seams):
bm.retrieve_batch(batch_id="b1", custom_llm_provider="vertex_ai", **VERTEX_CREDS)
assert _sent(
seams.vertex.retrieve_batch,
"vertex_project",
"vertex_location",
"vertex_credentials",
) == {
"vertex_project": "proj-user",
"vertex_location": "loc-user",
"vertex_credentials": "cred-user",
}
def test_retrieve__anthropic_credentials_passthrough(seams):
bm.retrieve_batch(
batch_id="b1",
custom_llm_provider="anthropic",
api_key="sk-user-anthropic",
api_base="https://anthropic.user.test",
)
assert _sent(seams.anthropic.retrieve_batch, "api_key", "api_base") == {
"api_key": "sk-user-anthropic",
"api_base": "https://anthropic.user.test",
}
def test_retrieve__provider_config_credentials_passthrough(seams):
with patch.object(
bm.ProviderConfigManager,
"get_provider_batches_config",
return_value=MagicMock(name="provider_config"),
):
bm.retrieve_batch(
batch_id="b1",
custom_llm_provider="bedrock",
model="bedrock/my-batch-model",
api_key="sk-user-bedrock",
api_base="https://bedrock.user.test",
)
assert _sent(seams.base_http.retrieve_batch, "api_key", "api_base") == {
"api_key": "sk-user-bedrock",
"api_base": "https://bedrock.user.test",
}
# ---- list_batches ---------------------------------------------------------- #
def test_list__openai_credentials_passthrough(seams):
bm.list_batches(custom_llm_provider="openai", **OPENAI_CREDS)
assert _sent(seams.openai.list_batches, "api_key", "api_base", "organization") == {
"api_key": "sk-user-openai",
"api_base": "https://openai.user.test",
"organization": "org-user-123",
}
def test_list__azure_credentials_passthrough(seams):
bm.list_batches(custom_llm_provider="azure", **AZURE_CREDS)
assert _sent(seams.azure.list_batches, "api_key", "api_base", "api_version") == {
"api_key": "sk-user-azure",
"api_base": "https://azure.user.test",
"api_version": "2024-12-99",
}
def test_list__vertex_credentials_passthrough(seams):
bm.list_batches(custom_llm_provider="vertex_ai", **VERTEX_CREDS)
assert _sent(
seams.vertex.list_batches,
"vertex_project",
"vertex_location",
"vertex_credentials",
) == {
"vertex_project": "proj-user",
"vertex_location": "loc-user",
"vertex_credentials": "cred-user",
}
# ---- cancel_batch ---------------------------------------------------------- #
def test_cancel__openai_credentials_passthrough(seams):
bm.cancel_batch(batch_id="b1", custom_llm_provider="openai", **OPENAI_CREDS)
assert _sent(seams.openai.cancel_batch, "api_key", "api_base", "organization") == {
"api_key": "sk-user-openai",
"api_base": "https://openai.user.test",
"organization": "org-user-123",
}
def test_cancel__azure_credentials_passthrough(seams):
bm.cancel_batch(batch_id="b1", custom_llm_provider="azure", **AZURE_CREDS)
assert _sent(seams.azure.cancel_batch, "api_key", "api_base", "api_version") == {
"api_key": "sk-user-azure",
"api_base": "https://azure.user.test",
"api_version": "2024-12-99",
}
def test_cancel__vertex_credentials_passthrough(seams):
bm.cancel_batch(batch_id="b1", custom_llm_provider="vertex_ai", **VERTEX_CREDS)
assert _sent(
seams.vertex.cancel_batch,
"vertex_project",
"vertex_location",
"vertex_credentials",
) == {
"vertex_project": "proj-user",
"vertex_location": "loc-user",
"vertex_credentials": "cred-user",
}
# =========================================================================== #
# _resolve_timeout - pure helper (used by create_batch).
# =========================================================================== #
def _params(**kw):
from litellm.types.router import GenericLiteLLMParams
return GenericLiteLLMParams(**kw)
def test_resolve_timeout__explicit_numeric():
assert bm._resolve_timeout(_params(timeout=30), {}, "openai") == 30.0
def test_resolve_timeout__default_when_unset():
assert bm._resolve_timeout(_params(), {}, "openai") == 600.0
def test_resolve_timeout__request_timeout_kwarg_fallback():
assert bm._resolve_timeout(_params(), {"request_timeout": 45}, "openai") == 45.0
def test_resolve_timeout__httpx_timeout_returns_float_read():
import httpx
t = httpx.Timeout(99.0, connect=5.0)
resolved = bm._resolve_timeout(_params(timeout=t), {}, "openai")
assert isinstance(resolved, float)
assert resolved == 99.0
def test_retrieve__keeps_the_deployment_bucket_settings_in_litellm_params(seams: Seams) -> None:
"""The batch's cost is computed by reading its output file after the retrieve, and
that read finds the Bedrock bucket in these litellm_params. Dropping them fails cost
accounting on a bucket the deployment has configured."""
logging_obj = MagicMock()
bm.retrieve_batch(
batch_id="batch-1",
custom_llm_provider="openai",
litellm_logging_obj=logging_obj,
s3_bucket_name="configured-bucket",
s3_output_bucket_name="output-bucket",
allow_legacy_cloud_file_ids=True,
)
litellm_params = logging_obj.update_from_kwargs.call_args.kwargs["litellm_params"]
assert {
key: litellm_params[key]
for key in ("s3_bucket_name", "s3_output_bucket_name", "allow_legacy_cloud_file_ids")
} == {
"s3_bucket_name": "configured-bucket",
"s3_output_bucket_name": "output-bucket",
"allow_legacy_cloud_file_ids": True,
}
# =========================================================================== #
# mistral - a provider-config provider, like bedrock, so it requires `model`
# =========================================================================== #
def test_create__mistral_ocr_routes_to_base_http_handler_with_mistral_config(seams):
result = bm.create_batch(
completion_window="24h",
endpoint="/v1/ocr",
input_file_id="file-abc",
custom_llm_provider="mistral",
model="mistral/mistral-ocr-latest",
)
assert result is seams.base_http.create_batch.return_value
_assert_only(seams.base_http.create_batch, seams, "create_batch")
forwarded = seams.base_http.create_batch.call_args.kwargs
assert type(forwarded["provider_config"]).__name__ == "MistralBatchesConfig"
assert forwarded["model"] == "mistral-ocr-latest"
assert forwarded["create_batch_data"]["endpoint"] == "/v1/ocr"
def test_create__mistral_without_model_raises_badrequest(seams):
with pytest.raises(litellm.exceptions.BadRequestError):
bm.create_batch(**CREATE_KW, custom_llm_provider="mistral")
for m in _all_seam_methods(seams, "create_batch"):
m.assert_not_called()
def test_retrieve__mistral_routes_to_base_http_handler_with_mistral_config(seams):
result = bm.retrieve_batch(batch_id="job-1", custom_llm_provider="mistral", model="mistral/mistral-ocr-latest")
assert result is seams.base_http.retrieve_batch.return_value
_assert_only(seams.base_http.retrieve_batch, seams, "retrieve_batch")
forwarded = seams.base_http.retrieve_batch.call_args.kwargs
assert type(forwarded["provider_config"]).__name__ == "MistralBatchesConfig"
assert forwarded["batch_id"] == "job-1"
@pytest.mark.asyncio()
async def test_batch_logging_azure_credentials_regression():
"""
Regression test: LoggingWorker Missing Azure Credentials When Fetching Batch Output
This test ensures that Azure credentials are properly passed when fetching batch
output files during logging, preventing "Missing credentials" errors.
Bug: The LoggingWorker failed when processing completed Azure batches because
it attempted to fetch batch output file content without Azure credentials.
Fix: Pass litellm_params (containing credentials) from the logging object
through to the file content retrieval functions.
"""
from unittest.mock import AsyncMock, MagicMock, patch
from litellm.batches.batch_utils import (
extract_file_access_credentials,
_fetch_batch_output_file_content,
handle_completed_batch,
)
from litellm.types.llms.openai import Batch, HttpxBinaryResponseContent
import httpx
print("\n=== Regression Test: Azure Batch Logging Credentials ===")
mock_batch = Batch(
id="batch-azure-test",
object="batch",
endpoint="/v1/chat/completions",
errors=None,
input_file_id="file-input-azure",
completion_window="24h",
status="completed",
output_file_id="file-output-azure",
error_file_id=None,
created_at=1234567890,
in_progress_at=1234567900,
expires_at=1234654290,
finalizing_at=1234568000,
completed_at=1234568100,
failed_at=None,
expired_at=None,
cancelling_at=None,
cancelled_at=None,
request_counts=None,
metadata=None,
)
azure_credentials = {
"api_key": "test-azure-key-regression",
"api_base": "https://test-regression.openai.azure.com",
"api_version": "2024-02-15-preview",
"organization": "test-org",
"timeout": 600,
}
batch_output = b'{"id": "batch_req_1", "custom_id": "request-1", "response": {"status_code": 200, "body": {"id": "chatcmpl-azure", "object": "chat.completion", "model": "gpt-4.1", "usage": {"prompt_tokens": 15, "completion_tokens": 25, "total_tokens": 40}}}}\n'
print("\n1. Testing credential extraction...")
extracted_creds = extract_file_access_credentials(azure_credentials)
assert "api_key" in extracted_creds, "api_key should be extracted"
assert (
extracted_creds["api_key"] == "test-azure-key-regression"
), "Incorrect api_key"
assert "api_base" in extracted_creds, "api_base should be extracted"
assert "api_version" in extracted_creds, "api_version should be extracted"
assert "timeout" in extracted_creds, "timeout should be extracted"
print(" ✓ Credentials extracted correctly")
print(f" ✓ Extracted keys: {list(extracted_creds.keys())}")
print("\n2. Testing credentials passed to afile_content...")
credentials_received = {"value": False, "params": None}
async def mock_afile_content_tracker(**kwargs):
if "api_key" in kwargs and "api_base" in kwargs and "api_version" in kwargs:
credentials_received["value"] = True
credentials_received["params"] = {
"api_key": kwargs.get("api_key"),
"api_base": kwargs.get("api_base"),
"api_version": kwargs.get("api_version"),
}
mock_response = httpx.Response(
status_code=200,
content=batch_output,
headers={"content-type": "application/octet-stream"},
)
return HttpxBinaryResponseContent(response=mock_response)
with patch(
"litellm.files.main.afile_content", side_effect=mock_afile_content_tracker
):
result = await _fetch_batch_output_file_content(
batch=mock_batch,
custom_llm_provider="azure",
litellm_params=azure_credentials,
)
assert credentials_received[
"value"
], "REGRESSION: Azure credentials not passed to afile_content! This causes 'Missing credentials' error."
assert (
credentials_received["params"]["api_key"] == "test-azure-key-regression"
), "REGRESSION: Incorrect api_key"
assert (
credentials_received["params"]["api_base"]
== "https://test-regression.openai.azure.com"
), "REGRESSION: Incorrect api_base"
print(" ✓ Credentials passed to afile_content")
print(f" ✓ api_key: {credentials_received['params']['api_key']}")
print(f" ✓ api_base: {credentials_received['params']['api_base']}")
print("\n3. Testing full logging flow...")
credentials_received["value"] = False
credentials_received["params"] = None
with patch(
"litellm.files.main.afile_content", side_effect=mock_afile_content_tracker
):
result = await handle_completed_batch(
batch=mock_batch,
custom_llm_provider="azure",
litellm_params=azure_credentials,
)
assert credentials_received[
"value"
], "REGRESSION: Credentials not passed through _handle_completed_batch"
assert result.cost > 0, "Cost should be calculated"
assert result.usage.total_tokens == 40, "Usage should be calculated correctly"
print(" ✓ Credentials passed through full flow")
print(f" ✓ Cost: {result.cost}")
print(f" ✓ Usage: {result.usage.total_tokens} tokens")
print(f" ✓ Models: {result.models}")
print("\n4. Testing 'Missing credentials' error prevention...")
with patch("litellm.files.main.afile_content") as mock_afile_content_fail:
mock_afile_content_fail.side_effect = Exception(
"Missing credentials. Please pass one of `api_key`, `azure_ad_token`, "
"`azure_ad_token_provider`, or the `AZURE_OPENAI_API_KEY` or "
"`AZURE_OPENAI_AD_TOKEN` environment variables."
)
with patch(
"litellm.files.main.afile_content", side_effect=mock_afile_content_tracker
):
try:
result = await handle_completed_batch(
batch=mock_batch,
custom_llm_provider="azure",
litellm_params=azure_credentials,
)
print(" ✓ No 'Missing credentials' error with fix")
except Exception as e:
if "Missing credentials" in str(e):
pytest.fail(
f"REGRESSION: 'Missing credentials' error occurred! "
f"Credentials not being passed. Error: {str(e)}"
)
raise
print("\n5. Testing backwards compatibility...")
with patch("litellm.files.main.afile_content") as mock_afile_content:
mock_response = httpx.Response(
status_code=200,
content=batch_output,
headers={"content-type": "application/octet-stream"},
)
mock_afile_content.return_value = HttpxBinaryResponseContent(
response=mock_response
)
result = await _fetch_batch_output_file_content(
batch=mock_batch,
custom_llm_provider="openai",
litellm_params=None,
)
assert len(result) > 0, "Should return file content"
print(" ✓ Backwards compatibility maintained")
print(" ✓ Works without litellm_params for OpenAI")
print("\n=== Regression Test Passed ===")
print("✓ Azure credentials properly passed from logging to file retrieval")
print("✓ 'Missing credentials' error prevented")
print("✓ Batch output files can be fetched with Azure credentials")
print("✓ Cost and usage tracking works for Azure batches")
print("✓ Backwards compatibility maintained\n")
_OPENAI_FILE_JSON: Final = MappingProxyType(
{
"id": "file-abc123",
"object": "file",
"purpose": "batch",
"filename": "batch.jsonl",
"bytes": 416,
"created_at": 1739598666,
"status": "processed",
}
)
_OPENAI_BATCH_JSON: Final = MappingProxyType(
{
"id": "batch_abc123",
"object": "batch",
"endpoint": "/v1/chat/completions",
"input_file_id": "file-abc123",
"status": "validating",
"completion_window": "24h",
"created_at": 1739598666,
}
)
class _KeyAliasMetadata(TypedDict):
user_api_key_alias: ReadOnly[str | None]
user_api_key_team_alias: ReadOnly[str | None]
class _LoggedCall(TypedDict):
call_type: ReadOnly[str]
metadata: ReadOnly[_KeyAliasMetadata]
_LOGGED_CALL: Final = TypeAdapter(_LoggedCall)
class _SuccessPayloadRecorder(CustomLogger):
def __init__(self, call_type: str) -> None:
super().__init__()
self._call_type: Final = call_type
self.logged: Final = asyncio.Event()
self.payload: _LoggedCall | None = None
async def async_log_success_event(
self,
kwargs: Mapping[str, object],
response_obj: object,
start_time: datetime.datetime,
end_time: datetime.datetime,
) -> None:
payload: Final = _LOGGED_CALL.validate_python(kwargs["standard_logging_object"])
if payload["call_type"] != self._call_type:
return
self.payload = payload
self.logged.set()
@pytest.mark.asyncio
async def test_acreate_batch_full_crud_and_logging_metadata(
respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
litellm.logging_callback_manager._reset_all_callbacks()
recorder: Final = _SuccessPayloadRecorder("acreate_batch")
monkeypatch.setattr(litellm, "callbacks", [recorder])
upload_route: Final = respx_mock.post("https://api.openai.com/v1/files").mock(
return_value=httpx.Response(200, json=dict(_OPENAI_FILE_JSON))
)
create_route: Final = respx_mock.post("https://api.openai.com/v1/batches").mock(
return_value=httpx.Response(200, json=dict(_OPENAI_BATCH_JSON))
)
retrieve_route: Final = respx_mock.get("https://api.openai.com/v1/batches/batch_abc123").mock(
return_value=httpx.Response(200, json=dict(_OPENAI_BATCH_JSON))
)
list_batches_route: Final = respx_mock.get("https://api.openai.com/v1/batches").mock(
return_value=httpx.Response(200, json={"object": "list", "data": [dict(_OPENAI_BATCH_JSON)]})
)
respx_mock.get("https://api.openai.com/v1/files/file-abc123/content").mock(
return_value=httpx.Response(200, content=b'{"custom_id": "request-1"}\n')
)
respx_mock.get("https://api.openai.com/v1/files/file-abc123").mock(
return_value=httpx.Response(200, json=dict(_OPENAI_FILE_JSON))
)
respx_mock.delete("https://api.openai.com/v1/files/file-abc123").mock(
return_value=httpx.Response(200, json={"id": "file-abc123", "object": "file", "deleted": True})
)
list_files_route: Final = respx_mock.get("https://api.openai.com/v1/files").mock(
return_value=httpx.Response(200, json={"object": "list", "data": [dict(_OPENAI_FILE_JSON)]})
)
cancel_route: Final = respx_mock.post("https://api.openai.com/v1/batches/batch_abc123/cancel").mock(
return_value=httpx.Response(200, json={**_OPENAI_BATCH_JSON, "status": "cancelling"})
)
batch_file: Final = (
"batch.jsonl",
b'{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", '
b'"body": {"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]}}\n',
"application/jsonl",
)
file_obj: Final = await litellm.acreate_file(
file=batch_file, purpose="batch", custom_llm_provider="openai", api_key="fake-key"
)
assert file_obj.id == "file-abc123"
upload_body: Final = upload_route.calls.last.request.content
assert b'name="purpose"\r\n\r\nbatch' in upload_body
assert batch_file[1] in upload_body
extra_metadata_field: Final = {
"user_api_key_alias": "special_api_key_alias",
"user_api_key_team_alias": "special_team_alias",
}
create_batch_response: Final = await litellm.acreate_batch(
completion_window="24h",
endpoint="/v1/chat/completions",
input_file_id=file_obj.id,
custom_llm_provider="openai",
api_key="fake-key",
metadata={"key1": "value1", "key2": "value2"},
litellm_metadata=extra_metadata_field,
)
assert json.loads(create_route.calls.last.request.content) == {
"completion_window": "24h",
"endpoint": "/v1/chat/completions",
"input_file_id": "file-abc123",
"metadata": {"key1": "value1", "key2": "value2"},
}
assert create_batch_response.id == "batch_abc123"
assert create_batch_response.endpoint == "/v1/chat/completions"
assert create_batch_response.input_file_id == file_obj.id
await asyncio.wait_for(recorder.logged.wait(), timeout=10)
assert recorder.payload is not None
standard_logging_object: Final = recorder.payload
assert standard_logging_object["metadata"]["user_api_key_alias"] == extra_metadata_field["user_api_key_alias"]
assert (
standard_logging_object["metadata"]["user_api_key_team_alias"]
== extra_metadata_field["user_api_key_team_alias"]
)
retrieved_batch: Final = await litellm.aretrieve_batch(
batch_id=create_batch_response.id, custom_llm_provider="openai", api_key="fake-key"
)
assert retrieve_route.called
assert retrieved_batch.id == create_batch_response.id
list_batches: Final = await litellm.alist_batches(custom_llm_provider="openai", limit=2, api_key="fake-key")
assert list_batches_route.calls.last.request.url.params["limit"] == "2"
assert [batch.id for batch in list_batches.data] == ["batch_abc123"]
file_content: Final = await litellm.afile_content(
file_id=file_obj.id, custom_llm_provider="openai", api_key="fake-key"
)
assert file_content.content == b'{"custom_id": "request-1"}\n'
retrieved_file: Final = await litellm.afile_retrieve(
file_id=file_obj.id, custom_llm_provider="openai", api_key="fake-key"
)
assert retrieved_file.id == file_obj.id
delete_file_response: Final = await litellm.afile_delete(
file_id=file_obj.id, custom_llm_provider="openai", api_key="fake-key"
)
assert delete_file_response.id == file_obj.id
all_files_list: Final = await litellm.afile_list(custom_llm_provider="openai", api_key="fake-key")
assert list_files_route.called
assert [file.id for file in all_files_list.data] == ["file-abc123"]
cancel_batch_response: Final = await litellm.acancel_batch(
batch_id=create_batch_response.id, custom_llm_provider="openai", api_key="fake-key"
)
assert cancel_route.called
assert cancel_batch_response.id == create_batch_response.id
@pytest.mark.asyncio
async def test_delete_batch_output_file(respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
batch_with_output: Final = {
**_OPENAI_BATCH_JSON,
"status": "completed",
"output_file_id": "file-output123",
}
respx_mock.get("https://api.openai.com/v1/batches/batch_abc123").mock(
return_value=httpx.Response(200, json=batch_with_output)
)
delete_route: Final = respx_mock.delete("https://api.openai.com/v1/files/file-output123").mock(
return_value=httpx.Response(200, json={"id": "file-output123", "object": "file", "deleted": True})
)
batch: Final = await litellm.aretrieve_batch(
batch_id="batch_abc123", custom_llm_provider="openai", api_key="fake-key"
)
assert batch.output_file_id == "file-output123"
delete_response: Final = await litellm.afile_delete(
file_id=batch.output_file_id, custom_llm_provider="openai", api_key="fake-key"
)
assert delete_route.call_count == 1
assert delete_response.id == "file-output123"
assert delete_response.deleted is True
async def _create_batch(sync_mode: bool, batch: Mapping[str, object]) -> LiteLLMBatch:
if sync_mode:
return litellm.create_batch(**batch)
return await litellm.acreate_batch(**batch)
def _batch(custom_llm_provider: str, api_base: str, **overrides: object) -> Mapping[str, object]:
return MappingProxyType(
{
"completion_window": "24h",
"endpoint": "/v1/chat/completions",
"input_file_id": "file-abc123",
"custom_llm_provider": custom_llm_provider,
"api_key": "sk-test",
"api_base": api_base,
"api_version": "2025-04-01-preview",
**overrides,
}
)
def _created_batch() -> httpx.Response:
return httpx.Response(200, json=dict(_OPENAI_BATCH_JSON))
def _resend_at_once(**_: object) -> float:
return 0.0
@pytest.fixture
def resend_at_once(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
monkeypatch.setattr(litellm, "calculate_retry_after", _resend_at_once)
@pytest.mark.usefixtures("resend_at_once")
@pytest.mark.parametrize(
"first_answer",
[
pytest.param(lambda: httpx.Response(429, json={"error": {"message": "slow down"}}), id="429"),
pytest.param(lambda: httpx.Response(503, json={"error": {"message": "overloaded"}}), id="503"),
pytest.param(lambda: httpx.ConnectError("connection refused"), id="connect-error"),
pytest.param(lambda: httpx.ConnectTimeout("no connection in time"), id="connect-timeout"),
],
)
@pytest.mark.parametrize("custom_llm_provider", ["openai", "azure"])
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
async def test_a_batch_create_is_resent_when_a_resend_cannot_create_a_duplicate(
first_answer: Callable[[], httpx.Response | Exception],
custom_llm_provider: str,
sync_mode: bool,
request: pytest.FixtureRequest,
respx_mock: respx.MockRouter,
):
api_base: Final = f"https://{request.node.callspec.id.lower()}.batch.test"
create_route: Final = respx_mock.post(url__startswith=api_base).mock(side_effect=[first_answer(), _created_batch()])
created: Final = await _create_batch(sync_mode, _batch(custom_llm_provider, api_base))
assert create_route.call_count == 2
assert created.id == _OPENAI_BATCH_JSON["id"]
@pytest.mark.usefixtures("resend_at_once")
@pytest.mark.parametrize(
"first_answer, expected_error",
[
pytest.param(lambda: httpx.ReadTimeout("no answer in time"), openai.APITimeoutError, id="read-timeout"),
pytest.param(
lambda: httpx.RemoteProtocolError("connection dropped mid-answer"),
openai.APIConnectionError,
id="remote-protocol-error",
),
pytest.param(
lambda: httpx.Response(
503, headers={"x-should-retry": "false"}, json={"error": {"message": "do not resend"}}
),
openai.APIStatusError,
id="503-should-not-retry",
),
],
)
@pytest.mark.parametrize("custom_llm_provider", ["openai", "azure"])
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
async def test_a_batch_create_is_sent_once_when_the_provider_may_have_created_it(
first_answer: Callable[[], httpx.Response | Exception],
expected_error: type[Exception],
custom_llm_provider: str,
sync_mode: bool,
request: pytest.FixtureRequest,
respx_mock: respx.MockRouter,
):
api_base: Final = f"https://{request.node.callspec.id.lower()}.batch.test"
create_route: Final = respx_mock.post(url__startswith=api_base).mock(side_effect=[first_answer(), _created_batch()])
with pytest.raises(expected_error):
await _create_batch(sync_mode, _batch(custom_llm_provider, api_base))
assert create_route.call_count == 1
@pytest.mark.usefixtures("resend_at_once")
@pytest.mark.parametrize("max_retries, expected_posts", [(0, 1), (1, 2), (None, 3)])
@pytest.mark.parametrize("custom_llm_provider", ["openai", "azure"])
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
async def test_a_rate_limited_batch_create_is_resent_up_to_the_callers_max_retries(
max_retries: int | None,
expected_posts: int,
custom_llm_provider: str,
sync_mode: bool,
request: pytest.FixtureRequest,
respx_mock: respx.MockRouter,
):
api_base: Final = f"https://{request.node.callspec.id.lower()}.batch.test"
create_route: Final = respx_mock.post(url__startswith=api_base).mock(
return_value=httpx.Response(429, json={"error": {"message": "slow down"}})
)
explicit_max_retries: Final = {} if max_retries is None else {"max_retries": max_retries}
with pytest.raises(openai.RateLimitError):
await _create_batch(
sync_mode,
_batch(custom_llm_provider, api_base, extra_headers={"x-request-tag": "kept"}, **explicit_max_retries),
)
assert create_route.call_count == expected_posts
assert [call.request.headers["x-stainless-retry-count"] for call in create_route.calls] == [
str(retries_taken) for retries_taken in range(expected_posts)
]
assert {call.request.headers["x-request-tag"] for call in create_route.calls} == {"kept"}
@pytest.mark.asyncio
async def test_router_cancel_batch_sends_the_token_behind_an_admin_oidc_env_api_key_on_each_call(
respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
monkeypatch.setenv("OPENAI_SA_TOKEN", "env-token-one")
router: Final = litellm.Router(
model_list=[
{"model_name": "gpt", "litellm_params": {"model": "openai/gpt-4o", "api_key": "oidc/env/OPENAI_SA_TOKEN"}}
]
)
cancel_route: Final = respx_mock.post("https://api.openai.com/v1/batches/batch_abc123/cancel").mock(
return_value=httpx.Response(200, json={**_OPENAI_BATCH_JSON, "status": "cancelling"})
)
await router.acancel_batch(model="gpt", batch_id="batch_abc123")
monkeypatch.setenv("OPENAI_SA_TOKEN", "env-token-two")
cancelled: Final = await router.acancel_batch(model="gpt", batch_id="batch_abc123")
assert [call.request.headers["Authorization"] for call in cancel_route.calls] == [
"Bearer env-token-one",
"Bearer env-token-two",
]
assert cancelled.status == "cancelling"
def test_cancel_batch_sends_the_token_behind_an_admin_oidc_env_api_key(
respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setenv("OPENAI_SA_TOKEN", "env-token")
cancel_route: Final = respx_mock.post("https://api.openai.com/v1/batches/batch_abc123/cancel").mock(
return_value=httpx.Response(200, json={**_OPENAI_BATCH_JSON, "status": "cancelling"})
)
litellm.cancel_batch(
batch_id="batch_abc123",
custom_llm_provider="openai",
api_key=admin_api_key_secret_reference({"api_key": "oidc/env/OPENAI_SA_TOKEN"})["api_key"],
)
assert cancel_route.calls.last.request.headers["Authorization"] == "Bearer env-token"
VERTEX_LABEL_FIELDS: Final = ("user_api_key_alias", "user_api_key_team_alias", "spend_logs_metadata")
VERTEX_IDENTITY: Final = MappingProxyType(
{"user_api_key_alias": "chargeback-key", "user_api_key_team_alias": "ai-platform"}
)
VERTEX_PROXY_METADATA: Final = MappingProxyType({**VERTEX_IDENTITY, "spend_logs_metadata": {"cost-center": "cc-1"}})
VERTEX_BATCH_FILE: Final = "gs://bucket/publishers/google/models/gemini-3.8-flash/file-uuid"
VERTEX_SENT_JOB: Final = TypeAdapter(Mapping[str, object])
VERTEX_SENT_LABELS: Final = TypeAdapter(Mapping[str, str])
VERTEX_BATCH_JOBS_URL: Final = (
"https://us-central1-aiplatform.googleapis.com/v1/projects/proj/locations/us-central1/batchPredictionJobs"
)
async def _vertex_batch_job_sent(
monkeypatch: pytest.MonkeyPatch, is_async: bool, batch_metadata: Mapping[str, object]
) -> Mapping[str, object]:
import litellm.llms.vertex_ai.batches.handler as vertex_batches
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
reply: Final = MagicMock(
side_effect=lambda _request: httpx.Response(
200,
json={
"name": "projects/proj/locations/us-central1/batchPredictionJobs/123",
"state": "JOB_STATE_PENDING",
"createTime": "2026-10-29T00:00:00Z",
},
)
)
transport: Final = httpx.MockTransport(reply)
handler: Final = vertex_batches.VertexAIBatchPrediction(gcs_bucket_name="bucket")
monkeypatch.setattr(handler, "_ensure_access_token", lambda **_: ("token", "proj"))
monkeypatch.setattr(bm, "vertex_ai_batches_instance", handler)
monkeypatch.setattr(
vertex_batches, "get_httpx_client", lambda **_: HTTPHandler(client=httpx.Client(transport=transport))
)
monkeypatch.setattr(vertex_batches, "get_async_httpx_client", lambda **_: AsyncHTTPHandler(transport=transport))
batch: Final = {
"completion_window": "24h",
"endpoint": "/v1/chat/completions",
"input_file_id": VERTEX_BATCH_FILE,
"custom_llm_provider": "vertex_ai",
"vertex_location": "us-central1",
**batch_metadata,
}
if is_async:
await bm.acreate_batch(**batch)
else:
bm.create_batch(**batch)
sent: Final[httpx.Request] = reply.call_args.args[0]
assert str(sent.url) == VERTEX_BATCH_JOBS_URL
return VERTEX_SENT_JOB.validate_json(sent.content)
@pytest.mark.asyncio
@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"])
async def test_vertex_batch_job_carries_proxy_identity_never_the_callers_batch_metadata(
monkeypatch: pytest.MonkeyPatch, is_async: bool
):
monkeypatch.setattr(litellm, "vertex_request_label_fields", VERTEX_LABEL_FIELDS)
job: Final = await _vertex_batch_job_sent(
monkeypatch,
is_async,
{
"metadata": {"user_api_key_alias": "forged", "user_api_key_team_alias": "forged", "app": "bot"},
"litellm_metadata": dict(VERTEX_PROXY_METADATA),
},
)
labels: Final = VERTEX_SENT_LABELS.validate_python(job["labels"])
assert list(labels.items()) == [*VERTEX_IDENTITY.items(), ("cost-center", "cc-1")]
@pytest.mark.asyncio
@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"])
async def test_vertex_batch_metadata_alone_never_labels_the_job(monkeypatch: pytest.MonkeyPatch, is_async: bool):
monkeypatch.setattr(litellm, "vertex_request_label_fields", VERTEX_LABEL_FIELDS)
job: Final = await _vertex_batch_job_sent(
monkeypatch, is_async, {"metadata": {**VERTEX_IDENTITY, "spend_logs_metadata": "cc-1"}}
)
assert "labels" not in job
@pytest.mark.asyncio
@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"])
async def test_vertex_batch_job_with_the_setting_off_is_unlabelled(monkeypatch: pytest.MonkeyPatch, is_async: bool):
monkeypatch.setattr(litellm, "vertex_request_label_fields", None)
job: Final = await _vertex_batch_job_sent(
monkeypatch, is_async, {"metadata": {"app": "bot"}, "litellm_metadata": dict(VERTEX_PROXY_METADATA)}
)
assert "labels" not in job
VLLM_ROUTER_API_BASE: Final = "http://vllm-router.test/v1"
VLLM_ROUTER_BATCH: Final = MappingProxyType(
{
"id": "batch_5f8dac",
"status": "pending",
"input_file_id": "file-b73f4c",
"created_at": 1793239207,
"endpoint": "/v1/chat/completions",
"completion_window": "24h",
"output_file_id": None,
"total_requests": None,
"completed_requests": 0,
"failed_requests": 0,
"metadata": {},
}
)
async def _create_on_vllm_router() -> LiteLLMBatch:
return await litellm.acreate_batch(
completion_window="24h",
endpoint="/v1/chat/completions",
input_file_id="file-b73f4c",
custom_llm_provider="hosted_vllm",
api_key="sk-test",
api_base=VLLM_ROUTER_API_BASE,
)
async def _retrieve_from_vllm_router() -> LiteLLMBatch:
return await litellm.aretrieve_batch(
batch_id="batch_5f8dac", custom_llm_provider="hosted_vllm", api_key="sk-test", api_base=VLLM_ROUTER_API_BASE
)
VLLM_ROUTER_BATCH_CALLS: Final = (
pytest.param("POST", "/batches", _create_on_vllm_router, id="acreate_batch"),
pytest.param("GET", "/batches/batch_5f8dac", _retrieve_from_vllm_router, id="aretrieve_batch"),
)
@pytest.mark.parametrize("method, path, call_router", VLLM_ROUTER_BATCH_CALLS)
@pytest.mark.parametrize(
"router_status, openai_status",
(
("pending", "validating"),
("running", "in_progress"),
("completed", "completed"),
("failed", "failed"),
("cancelled", "cancelled"),
),
)
async def test_hosted_vllm_router_batch_comes_back_as_an_openai_batch(
respx_mock: respx.MockRouter,
method: str,
path: str,
call_router: Callable[[], Awaitable[LiteLLMBatch]],
router_status: str,
openai_status: str,
):
respx_mock.route(method=method, url=f"{VLLM_ROUTER_API_BASE}{path}").respond(
200, json={**VLLM_ROUTER_BATCH, "status": router_status}
)
batch: Final = await call_router()
assert (batch.id, batch.object, batch.status) == ("batch_5f8dac", "batch", openai_status)
@pytest.mark.parametrize("method, path, call_router", VLLM_ROUTER_BATCH_CALLS)
@pytest.mark.parametrize("field, value", (("status", "queued"), ("object", "file")))
async def test_hosted_vllm_router_batch_with_an_unknown_value_is_rejected(
respx_mock: respx.MockRouter,
method: str,
path: str,
call_router: Callable[[], Awaitable[LiteLLMBatch]],
field: str,
value: str,
):
respx_mock.route(method=method, url=f"{VLLM_ROUTER_API_BASE}{path}").respond(
200, json={**VLLM_ROUTER_BATCH, field: value}
)
with pytest.raises(ValidationError) as exc_info:
await call_router()
assert [error["loc"] for error in exc_info.value.errors()] == [(field,)]
async def _list_on_vllm_router() -> Sequence[Batch]:
page: Final = await litellm.alist_batches(
custom_llm_provider="hosted_vllm", api_key="sk-test", api_base=VLLM_ROUTER_API_BASE
)
return page.data
async def _list_on_vllm_router_sync() -> Sequence[Batch]:
return litellm.list_batches(custom_llm_provider="hosted_vllm", api_key="sk-test", api_base=VLLM_ROUTER_API_BASE).data
@pytest.mark.parametrize("list_router", (_list_on_vllm_router, _list_on_vllm_router_sync))
async def test_hosted_vllm_router_batch_list_comes_back_as_openai_batches(
respx_mock: respx.MockRouter, list_router: Callable[[], Awaitable[Sequence[Batch]]]
):
respx_mock.get(f"{VLLM_ROUTER_API_BASE}/batches").respond(
200,
json={
"object": "list",
"data": [
{**VLLM_ROUTER_BATCH, "id": "batch_5f8dac", "status": "pending"},
{**VLLM_ROUTER_BATCH, "id": "batch_c74802", "status": "running"},
],
"first_id": "batch_5f8dac",
"last_id": "batch_c74802",
"has_more": False,
},
)
batches: Final = await list_router()
assert [(batch.id, batch.object, batch.status) for batch in batches] == [
("batch_5f8dac", "batch", "validating"),
("batch_c74802", "batch", "in_progress"),
]
async def test_hosted_vllm_router_batch_list_passes_through_a_status_that_is_not_a_string(
respx_mock: respx.MockRouter,
):
respx_mock.get(f"{VLLM_ROUTER_API_BASE}/batches").respond(
200,
json={
"object": "list",
"data": [{**VLLM_ROUTER_BATCH, "status": ["pending"]}],
"first_id": "batch_5f8dac",
"last_id": "batch_5f8dac",
"has_more": False,
},
)
batches: Final = await _list_on_vllm_router()
assert [(batch.id, batch.object, batch.status) for batch in batches] == [("batch_5f8dac", "batch", ["pending"])]
async def test_openai_batch_list_items_come_back_as_openai_sent_them(respx_mock: respx.MockRouter):
respx_mock.get("http://openai.test/v1/batches").respond(
200,
json={
"object": "list",
"data": [
{
**_OPENAI_BATCH_JSON,
"status": "completed",
"usage": {
"input_tokens": 10,
"input_tokens_details": {"cached_tokens": 4},
"output_tokens": 5,
"output_tokens_details": {"reasoning_tokens": 2},
"total_tokens": 15,
},
},
{**_OPENAI_BATCH_JSON, "id": "batch_def456", "status": "queued"},
],
"first_id": "batch_abc123",
"last_id": "batch_def456",
"has_more": False,
},
)
page: Final = await litellm.alist_batches(
custom_llm_provider="openai", api_key="sk-test", api_base="http://openai.test/v1"
)
first, second = page.data
assert first.usage is not None
assert (first.usage.input_tokens_details.cached_tokens, first.usage.output_tokens_details.reasoning_tokens) == (4, 2)
assert (second.id, second.object, second.status) == ("batch_def456", "batch", "queued")
# =========================================================================== #
# gemini - a provider-config provider, like mistral, so it requires `model`
# =========================================================================== #
def test_create__gemini_routes_to_base_http_handler_with_gemini_config(seams):
result = bm.create_batch(**CREATE_KW, custom_llm_provider="gemini", model="gemini/gemini-3.8-flash")
assert result is seams.base_http.create_batch.return_value
_assert_only(seams.base_http.create_batch, seams, "create_batch")
forwarded = seams.base_http.create_batch.call_args.kwargs
assert type(forwarded["provider_config"]).__name__ == "GeminiBatchesConfig"
assert forwarded["model"] == "gemini-3.8-flash"
def test_retrieve__gemini_routes_to_base_http_handler_with_gemini_config(seams):
result = bm.retrieve_batch(batch_id="la6", custom_llm_provider="gemini", model="gemini/gemini-3.8-flash")
assert result is seams.base_http.retrieve_batch.return_value
_assert_only(seams.base_http.retrieve_batch, seams, "retrieve_batch")
forwarded = seams.base_http.retrieve_batch.call_args.kwargs
assert type(forwarded["provider_config"]).__name__ == "GeminiBatchesConfig"
assert forwarded["batch_id"] == "la6"