mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-05 01:59:27 +00:00
* 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>
498 lines
18 KiB
Python
498 lines
18 KiB
Python
"""Unit tests for ``AzureBatchesAPI`` (litellm/llms/azure/batches/handler.py).
|
|
|
|
The Azure batches handler is HTTP/auth glue: each public method
|
|
(create/retrieve/cancel/list) resolves an Azure OpenAI client via the inherited
|
|
``get_azure_openai_client`` seam, branches on ``_is_async`` (returning the
|
|
``a*`` coroutine in the async case, calling the sync client otherwise), validates
|
|
the client type, and parses the SDK response into ``LiteLLMBatch``.
|
|
|
|
We mock only true boundaries:
|
|
* ``get_azure_openai_client`` - the credential/client-construction seam. We
|
|
assert the EXACT auth args (api_key / api_base / api_version / client /
|
|
_is_async / litellm_params) forwarded to it.
|
|
* the returned Azure OpenAI client's ``batches.*`` methods - the network call.
|
|
We assert the request data forwarded and that the SDK response is parsed
|
|
into ``LiteLLMBatch`` (sibling SDK methods asserted NOT called).
|
|
|
|
Pure logic (the _is_async branch, the isinstance guards, the model_dump parse)
|
|
runs for real.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
|
|
from openai import AsyncOpenAI, OpenAI # noqa: E402
|
|
|
|
from litellm.llms.azure.azure import AsyncAzureOpenAI, AzureOpenAI # noqa: E402
|
|
from litellm.llms.azure.batches.handler import AzureBatchesAPI # noqa: E402
|
|
from litellm.types.utils import LiteLLMBatch # noqa: E402
|
|
|
|
GET_CLIENT = "litellm.llms.azure.batches.handler.AzureBatchesAPI.get_azure_openai_client"
|
|
|
|
AUTH_KW = dict(
|
|
api_key="sk-azure-test",
|
|
api_base="https://my-azure.openai.azure.com",
|
|
api_version="2024-12-01",
|
|
timeout=600.0,
|
|
max_retries=3,
|
|
)
|
|
|
|
CREATE_DATA = {
|
|
"completion_window": "24h",
|
|
"endpoint": "/v1/chat/completions",
|
|
"input_file_id": "file-abc",
|
|
}
|
|
FIRST_TRY_HEADERS = {"x-stainless-retry-count": "0"}
|
|
RETRIEVE_DATA = {"batch_id": "batch-123"}
|
|
CANCEL_DATA = {"batch_id": "batch-123"}
|
|
|
|
|
|
def _batch_dict(batch_id: str = "batch-123", status: str = "completed") -> dict:
|
|
"""A minimal-but-valid dict for ``LiteLLMBatch(**response.model_dump())``."""
|
|
return {
|
|
"id": batch_id,
|
|
"completion_window": "24h",
|
|
"created_at": 1700000000,
|
|
"endpoint": "/v1/chat/completions",
|
|
"input_file_id": "file-abc",
|
|
"object": "batch",
|
|
"status": status,
|
|
"output_file_id": "file-out-xyz",
|
|
}
|
|
|
|
|
|
def _sdk_response(batch_dict: dict) -> MagicMock:
|
|
"""An object that mimics the OpenAI SDK Batch: only ``.model_dump()`` is used."""
|
|
resp = MagicMock()
|
|
resp.model_dump.return_value = batch_dict
|
|
return resp
|
|
|
|
|
|
def _sync_client() -> MagicMock:
|
|
"""A sync Azure client (passes ``isinstance(.., AzureOpenAI)``)."""
|
|
client = MagicMock(spec=AzureOpenAI)
|
|
client.with_options.return_value = client
|
|
client.max_retries = 2
|
|
return client
|
|
|
|
|
|
def _async_client() -> MagicMock:
|
|
"""An async Azure client (passes ``isinstance(.., AsyncAzureOpenAI)``).
|
|
|
|
The ``batches.*`` SDK methods are awaited by the handler, so they must be
|
|
AsyncMocks.
|
|
"""
|
|
client = MagicMock(spec=AsyncAzureOpenAI)
|
|
client.batches.create = AsyncMock()
|
|
client.batches.retrieve = AsyncMock()
|
|
client.batches.cancel = AsyncMock()
|
|
client.batches.list = AsyncMock()
|
|
client.with_options.return_value = client
|
|
client.max_retries = 2
|
|
return client
|
|
|
|
|
|
@pytest.fixture
|
|
def handler() -> AzureBatchesAPI:
|
|
return AzureBatchesAPI()
|
|
|
|
|
|
# =========================================================================== #
|
|
# create_batch - sync path
|
|
# =========================================================================== #
|
|
|
|
|
|
def test_create_sync_forwards_auth_to_client_seam(handler):
|
|
client = _sync_client()
|
|
client.batches.create.return_value = _sdk_response(_batch_dict())
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
result = handler.create_batch(
|
|
_is_async=False, create_batch_data=CREATE_DATA, **AUTH_KW
|
|
)
|
|
|
|
# EXACT auth args forwarded to the client-construction seam.
|
|
assert get_client.call_count == 1
|
|
kw = get_client.call_args.kwargs
|
|
assert kw["api_key"] == "sk-azure-test"
|
|
assert kw["api_base"] == "https://my-azure.openai.azure.com"
|
|
assert kw["api_version"] == "2024-12-01"
|
|
assert kw["_is_async"] is False
|
|
assert kw["client"] is None
|
|
# litellm_params defaults to {} (not None) when not supplied.
|
|
assert kw["litellm_params"] == {}
|
|
|
|
# PAYLOAD: request data forwarded verbatim to the SDK as kwargs.
|
|
client.batches.create.assert_called_once_with(**CREATE_DATA, extra_headers=FIRST_TRY_HEADERS)
|
|
# sibling SDK seams untouched.
|
|
client.batches.retrieve.assert_not_called()
|
|
client.batches.cancel.assert_not_called()
|
|
|
|
# RESULT: parsed into LiteLLMBatch from the SDK response's model_dump.
|
|
assert isinstance(result, LiteLLMBatch)
|
|
assert result.id == "batch-123"
|
|
assert result.status == "completed"
|
|
assert result.output_file_id == "file-out-xyz"
|
|
|
|
|
|
def test_create_sync_passes_litellm_params_through(handler):
|
|
client = _sync_client()
|
|
client.batches.create.return_value = _sdk_response(_batch_dict())
|
|
lp = {"azure_ad_token": "tok", "tenant_id": "t1"}
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
handler.create_batch(
|
|
_is_async=False,
|
|
create_batch_data=CREATE_DATA,
|
|
litellm_params=lp,
|
|
**AUTH_KW,
|
|
)
|
|
|
|
assert get_client.call_args.kwargs["litellm_params"] == lp
|
|
|
|
|
|
def test_create_sync_explicit_client_forwarded_to_seam(handler):
|
|
sentinel_client = _sync_client()
|
|
sentinel_client.batches.create.return_value = _sdk_response(_batch_dict())
|
|
|
|
with patch(GET_CLIENT, return_value=sentinel_client) as get_client:
|
|
handler.create_batch(
|
|
_is_async=False,
|
|
create_batch_data=CREATE_DATA,
|
|
client=sentinel_client,
|
|
**AUTH_KW,
|
|
)
|
|
|
|
assert get_client.call_args.kwargs["client"] is sentinel_client
|
|
|
|
|
|
def test_create_raises_when_client_is_none(handler):
|
|
with patch(GET_CLIENT, return_value=None):
|
|
with pytest.raises(ValueError, match="client is not initialized"):
|
|
handler.create_batch(
|
|
_is_async=False, create_batch_data=CREATE_DATA, **AUTH_KW
|
|
)
|
|
|
|
|
|
# =========================================================================== #
|
|
# create_batch - async path
|
|
# =========================================================================== #
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_async_returns_coroutine_and_awaits_async_client(handler):
|
|
client = _async_client()
|
|
client.batches.create.return_value = _sdk_response(_batch_dict())
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
coro = handler.create_batch(
|
|
_is_async=True, create_batch_data=CREATE_DATA, **AUTH_KW
|
|
)
|
|
assert asyncio.iscoroutine(coro)
|
|
result = await coro
|
|
|
|
assert get_client.call_args.kwargs["_is_async"] is True
|
|
client.batches.create.assert_awaited_once_with(**CREATE_DATA, extra_headers=FIRST_TRY_HEADERS)
|
|
assert isinstance(result, LiteLLMBatch)
|
|
assert result.id == "batch-123"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_async_rejects_sync_client(handler):
|
|
"""_is_async=True but seam returns a sync client -> ValueError, no network."""
|
|
sync_client = _sync_client()
|
|
|
|
with patch(GET_CLIENT, return_value=sync_client):
|
|
with pytest.raises(ValueError, match="not an instance of AsyncOpenAI"):
|
|
handler.create_batch(
|
|
_is_async=True, create_batch_data=CREATE_DATA, **AUTH_KW
|
|
)
|
|
|
|
sync_client.batches.create.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_acreate_batch_parses_response(handler):
|
|
client = _async_client()
|
|
client.batches.create.return_value = _sdk_response(_batch_dict(status="validating"))
|
|
|
|
result = await handler.acreate_batch(
|
|
create_batch_data=CREATE_DATA, azure_client=client
|
|
)
|
|
|
|
client.batches.create.assert_awaited_once_with(**CREATE_DATA, extra_headers=FIRST_TRY_HEADERS)
|
|
assert isinstance(result, LiteLLMBatch)
|
|
assert result.status == "validating"
|
|
|
|
|
|
# =========================================================================== #
|
|
# retrieve_batch
|
|
# =========================================================================== #
|
|
|
|
|
|
def test_retrieve_sync_dispatch_payload_and_result(handler):
|
|
client = _sync_client()
|
|
client.batches.retrieve.return_value = _sdk_response(_batch_dict())
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
result = handler.retrieve_batch(
|
|
_is_async=False, retrieve_batch_data=RETRIEVE_DATA, **AUTH_KW
|
|
)
|
|
|
|
assert get_client.call_args.kwargs["_is_async"] is False
|
|
client.batches.retrieve.assert_called_once_with(**RETRIEVE_DATA)
|
|
client.batches.create.assert_not_called()
|
|
client.batches.cancel.assert_not_called()
|
|
assert isinstance(result, LiteLLMBatch)
|
|
assert result.id == "batch-123"
|
|
|
|
|
|
def test_retrieve_raises_when_client_is_none(handler):
|
|
with patch(GET_CLIENT, return_value=None):
|
|
with pytest.raises(ValueError, match="client is not initialized"):
|
|
handler.retrieve_batch(
|
|
_is_async=False, retrieve_batch_data=RETRIEVE_DATA, **AUTH_KW
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retrieve_async_returns_coroutine_and_awaits(handler):
|
|
client = _async_client()
|
|
client.batches.retrieve.return_value = _sdk_response(_batch_dict())
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
coro = handler.retrieve_batch(
|
|
_is_async=True, retrieve_batch_data=RETRIEVE_DATA, **AUTH_KW
|
|
)
|
|
assert asyncio.iscoroutine(coro)
|
|
result = await coro
|
|
|
|
assert get_client.call_args.kwargs["_is_async"] is True
|
|
client.batches.retrieve.assert_awaited_once_with(**RETRIEVE_DATA)
|
|
assert isinstance(result, LiteLLMBatch)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retrieve_async_rejects_sync_client(handler):
|
|
sync_client = _sync_client()
|
|
with patch(GET_CLIENT, return_value=sync_client):
|
|
with pytest.raises(ValueError, match="not an instance of AsyncOpenAI"):
|
|
handler.retrieve_batch(
|
|
_is_async=True, retrieve_batch_data=RETRIEVE_DATA, **AUTH_KW
|
|
)
|
|
sync_client.batches.retrieve.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_parses_response(handler):
|
|
client = _async_client()
|
|
client.batches.retrieve.return_value = _sdk_response(_batch_dict())
|
|
|
|
result = await handler.aretrieve_batch(
|
|
retrieve_batch_data=RETRIEVE_DATA, client=client
|
|
)
|
|
|
|
client.batches.retrieve.assert_awaited_once_with(**RETRIEVE_DATA)
|
|
assert isinstance(result, LiteLLMBatch)
|
|
|
|
|
|
# =========================================================================== #
|
|
# cancel_batch (has an EXTRA sync-side isinstance guard the others lack)
|
|
# =========================================================================== #
|
|
|
|
|
|
def test_cancel_sync_dispatch_payload_and_result(handler):
|
|
client = _sync_client()
|
|
client.batches.cancel.return_value = _sdk_response(_batch_dict(status="cancelled"))
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
result = handler.cancel_batch(
|
|
_is_async=False, cancel_batch_data=CANCEL_DATA, **AUTH_KW
|
|
)
|
|
|
|
assert get_client.call_args.kwargs["_is_async"] is False
|
|
client.batches.cancel.assert_called_once_with(**CANCEL_DATA)
|
|
client.batches.create.assert_not_called()
|
|
client.batches.retrieve.assert_not_called()
|
|
assert isinstance(result, LiteLLMBatch)
|
|
assert result.status == "cancelled"
|
|
|
|
|
|
def test_cancel_raises_when_client_is_none(handler):
|
|
with patch(GET_CLIENT, return_value=None):
|
|
with pytest.raises(ValueError, match="client is not initialized"):
|
|
handler.cancel_batch(
|
|
_is_async=False, cancel_batch_data=CANCEL_DATA, **AUTH_KW
|
|
)
|
|
|
|
|
|
def test_cancel_sync_rejects_non_sync_client(handler):
|
|
"""cancel_batch has a unique sync-side guard: if _is_async is False but the
|
|
resolved client is async (neither AzureOpenAI nor OpenAI), it must raise
|
|
rather than call .cancel()."""
|
|
async_client = _async_client()
|
|
|
|
with patch(GET_CLIENT, return_value=async_client):
|
|
with pytest.raises(ValueError, match="sync client"):
|
|
handler.cancel_batch(
|
|
_is_async=False, cancel_batch_data=CANCEL_DATA, **AUTH_KW
|
|
)
|
|
|
|
async_client.batches.cancel.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_async_returns_coroutine_and_awaits(handler):
|
|
client = _async_client()
|
|
client.batches.cancel.return_value = _sdk_response(_batch_dict(status="cancelled"))
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
coro = handler.cancel_batch(
|
|
_is_async=True, cancel_batch_data=CANCEL_DATA, **AUTH_KW
|
|
)
|
|
assert asyncio.iscoroutine(coro)
|
|
result = await coro
|
|
|
|
assert get_client.call_args.kwargs["_is_async"] is True
|
|
client.batches.cancel.assert_awaited_once_with(**CANCEL_DATA)
|
|
assert isinstance(result, LiteLLMBatch)
|
|
assert result.status == "cancelled"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_async_rejects_sync_client(handler):
|
|
sync_client = _sync_client()
|
|
with patch(GET_CLIENT, return_value=sync_client):
|
|
with pytest.raises(ValueError, match="async client"):
|
|
handler.cancel_batch(
|
|
_is_async=True, cancel_batch_data=CANCEL_DATA, **AUTH_KW
|
|
)
|
|
sync_client.batches.cancel.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_acancel_batch_parses_response(handler):
|
|
client = _async_client()
|
|
client.batches.cancel.return_value = _sdk_response(_batch_dict(status="cancelled"))
|
|
|
|
result = await handler.acancel_batch(cancel_batch_data=CANCEL_DATA, client=client)
|
|
|
|
client.batches.cancel.assert_awaited_once_with(**CANCEL_DATA)
|
|
assert isinstance(result, LiteLLMBatch)
|
|
assert result.status == "cancelled"
|
|
|
|
|
|
# =========================================================================== #
|
|
# list_batches (returns the raw SDK response, NOT a LiteLLMBatch)
|
|
# =========================================================================== #
|
|
|
|
|
|
def test_list_sync_forwards_after_limit_and_returns_raw_response(handler):
|
|
client = _sync_client()
|
|
raw = MagicMock(name="raw_list_response")
|
|
client.batches.list.return_value = raw
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
result = handler.list_batches(
|
|
_is_async=False, after="cur-1", limit=20, **AUTH_KW
|
|
)
|
|
|
|
assert get_client.call_args.kwargs["_is_async"] is False
|
|
client.batches.list.assert_called_once_with(after="cur-1", limit=20)
|
|
# list returns the SDK response untouched (no LiteLLMBatch parsing).
|
|
assert result is raw
|
|
|
|
|
|
def test_list_sync_defaults_after_and_limit_to_none(handler):
|
|
client = _sync_client()
|
|
client.batches.list.return_value = MagicMock()
|
|
|
|
with patch(GET_CLIENT, return_value=client):
|
|
handler.list_batches(_is_async=False, **AUTH_KW)
|
|
|
|
client.batches.list.assert_called_once_with(after=None, limit=None)
|
|
|
|
|
|
def test_list_raises_when_client_is_none(handler):
|
|
with patch(GET_CLIENT, return_value=None):
|
|
with pytest.raises(ValueError, match="client is not initialized"):
|
|
handler.list_batches(_is_async=False, **AUTH_KW)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_async_returns_coroutine_and_awaits(handler):
|
|
client = _async_client()
|
|
raw = MagicMock(name="raw_async_list_response")
|
|
client.batches.list.return_value = raw
|
|
|
|
with patch(GET_CLIENT, return_value=client) as get_client:
|
|
coro = handler.list_batches(
|
|
_is_async=True, after="cur-2", limit=7, **AUTH_KW
|
|
)
|
|
assert asyncio.iscoroutine(coro)
|
|
result = await coro
|
|
|
|
assert get_client.call_args.kwargs["_is_async"] is True
|
|
client.batches.list.assert_awaited_once_with(after="cur-2", limit=7)
|
|
assert result is raw
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_async_rejects_sync_client(handler):
|
|
sync_client = _sync_client()
|
|
with patch(GET_CLIENT, return_value=sync_client):
|
|
with pytest.raises(ValueError, match="not an instance of AsyncOpenAI"):
|
|
handler.list_batches(_is_async=True, **AUTH_KW)
|
|
sync_client.batches.list.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_alist_batches_returns_raw_response(handler):
|
|
client = _async_client()
|
|
raw = MagicMock(name="raw")
|
|
client.batches.list.return_value = raw
|
|
|
|
result = await handler.alist_batches(client=client, after="a", limit=2)
|
|
|
|
client.batches.list.assert_awaited_once_with(after="a", limit=2)
|
|
assert result is raw
|
|
|
|
|
|
# =========================================================================== #
|
|
# Cross-cutting: an OpenAI (non-Azure) client also satisfies the type guards,
|
|
# since the Union allows OpenAI / AsyncOpenAI (Azure-v1 path returns these).
|
|
# =========================================================================== #
|
|
|
|
|
|
def test_create_sync_accepts_plain_openai_client(handler):
|
|
client = MagicMock(spec=OpenAI)
|
|
client.with_options.return_value = client
|
|
client.max_retries = 2
|
|
client.batches.create.return_value = _sdk_response(_batch_dict())
|
|
|
|
with patch(GET_CLIENT, return_value=client):
|
|
result = handler.create_batch(
|
|
_is_async=False, create_batch_data=CREATE_DATA, **AUTH_KW
|
|
)
|
|
|
|
assert isinstance(result, LiteLLMBatch)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_async_accepts_plain_async_openai_client(handler):
|
|
client = MagicMock(spec=AsyncOpenAI)
|
|
client.with_options.return_value = client
|
|
client.max_retries = 2
|
|
client.batches.create = AsyncMock(return_value=_sdk_response(_batch_dict()))
|
|
|
|
with patch(GET_CLIENT, return_value=client):
|
|
result = await handler.create_batch(
|
|
_is_async=True, create_batch_data=CREATE_DATA, **AUTH_KW
|
|
)
|
|
|
|
assert isinstance(result, LiteLLMBatch)
|