mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +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>
451 lines
18 KiB
Python
451 lines
18 KiB
Python
import asyncio
|
|
import time
|
|
from collections.abc import Awaitable, Callable, Mapping
|
|
from types import MappingProxyType
|
|
from typing import Final
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
import httpx
|
|
import openai
|
|
import pytest
|
|
import respx
|
|
from pydantic import ValidationError
|
|
|
|
import litellm
|
|
from litellm.constants import JITTER
|
|
from litellm.llms.custom_httpx.http_handler import HTTPHandler
|
|
from litellm.types.llms.openai import OpenAIFileObject
|
|
|
|
NATIVE_VERTEX_ROWS: Final = (
|
|
b'{"request": {"contents": [{"role": "user", "parts": [{"text": "Who won the 2024 Tour de France?"}]}],'
|
|
b' "tools": [{"googleSearch": {"excludeDomains": ["example.com"]}}]}}\n'
|
|
b'{"request": {"contents": [{"role": "user", "parts": [{"text": "What is the tallest building in Tokyo?"}]}],'
|
|
b' "tools": [{"googleSearch": {}}]}}\n'
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"custom_llm_provider, purpose",
|
|
[("openai", "batch"), ("vertex_ai", "assistants")],
|
|
ids=["non-vertex-provider", "non-batch-purpose"],
|
|
)
|
|
def test_create_file_passthrough_is_rejected_outside_a_vertex_batch(custom_llm_provider, purpose):
|
|
with pytest.raises(litellm.BadRequestError) as exc_info:
|
|
litellm.create_file(
|
|
file=("batch.jsonl", b'{"request": {"contents": []}}\n', "application/jsonl"),
|
|
purpose=purpose,
|
|
custom_llm_provider=custom_llm_provider,
|
|
passthrough=True,
|
|
api_key="sk-test",
|
|
api_base="http://127.0.0.1:9",
|
|
)
|
|
|
|
assert "vertex_ai" in str(exc_info.value)
|
|
assert "batch" in str(exc_info.value)
|
|
|
|
|
|
def _gcs_upload_transport(uploads: list[httpx.Request]) -> httpx.MockTransport:
|
|
def respond(request: httpx.Request) -> httpx.Response:
|
|
uploads.append(request)
|
|
object_name: Final = parse_qs(urlparse(str(request.url)).query)["name"][0]
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"id": f"my-bucket/{object_name}/1758585600000000",
|
|
"name": object_name,
|
|
"size": str(len(request.read())),
|
|
"timeCreated": "2026-09-23T00:00:00.000Z",
|
|
},
|
|
)
|
|
|
|
return httpx.MockTransport(respond)
|
|
|
|
|
|
def test_create_file_passthrough_kwarg_ships_native_rows_byte_for_byte_under_the_passthrough_prefix():
|
|
uploads: Final[list[httpx.Request]] = []
|
|
file_object = litellm.create_file(
|
|
file=("batch.jsonl", NATIVE_VERTEX_ROWS, "application/jsonl"),
|
|
purpose="batch",
|
|
custom_llm_provider="vertex_ai",
|
|
passthrough=True,
|
|
model="vertex_ai/gemini-2.5-flash",
|
|
gcs_bucket_name="my-bucket",
|
|
api_key="test-token",
|
|
client=HTTPHandler(client=httpx.Client(transport=_gcs_upload_transport(uploads))),
|
|
)
|
|
(upload,) = uploads
|
|
object_name: Final = parse_qs(urlparse(str(upload.url)).query)["name"][0]
|
|
assert upload.read() == NATIVE_VERTEX_ROWS
|
|
assert object_name.startswith("litellm-vertex-files/passthrough/publishers/google/models/gemini-2.5-flash/")
|
|
assert file_object.id == f"gs://my-bucket/{object_name}"
|
|
|
|
|
|
OPENAI_FILES_API_BASE: Final = "https://files.test/v1"
|
|
PROVIDER_FILE: Final = {
|
|
"id": "file-abc123",
|
|
"bytes": 120,
|
|
"created_at": 1700000000,
|
|
"filename": "batch.jsonl",
|
|
"object": "file",
|
|
"purpose": "batch",
|
|
}
|
|
UNSET_OPTIONAL_FIELDS: Final = {"status": None, "expires_at": None, "status_details": None}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"provider_extras, expected",
|
|
[
|
|
({}, {**PROVIDER_FILE, **UNSET_OPTIONAL_FIELDS}),
|
|
(
|
|
{"status": "processed", "expires_at": 1800000000, "status_details": "ok", "provider_only": {"a": [1]}},
|
|
{**PROVIDER_FILE, "status": "processed", "expires_at": 1800000000, "status_details": "ok"},
|
|
),
|
|
],
|
|
ids=["required-fields-only", "optional-and-unknown-fields"],
|
|
)
|
|
@respx.mock
|
|
async def test_afile_retrieve_returns_the_provider_file_as_an_openai_file_object(provider_extras, expected):
|
|
respx.get(f"{OPENAI_FILES_API_BASE}/files/file-abc123").respond(200, json={**PROVIDER_FILE, **provider_extras})
|
|
|
|
file_object: Final = await litellm.afile_retrieve(
|
|
file_id="file-abc123", custom_llm_provider="openai", api_key="sk-test", api_base=OPENAI_FILES_API_BASE
|
|
)
|
|
|
|
assert type(file_object) is OpenAIFileObject
|
|
assert file_object.model_dump() == expected
|
|
|
|
|
|
@respx.mock
|
|
async def test_afile_retrieve_rejects_a_provider_file_without_its_size():
|
|
provider_file: Final = {key: value for key, value in PROVIDER_FILE.items() if key != "bytes"}
|
|
respx.get(f"{OPENAI_FILES_API_BASE}/files/file-abc123").respond(200, json=provider_file)
|
|
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
await litellm.afile_retrieve(
|
|
file_id="file-abc123", custom_llm_provider="openai", api_key="sk-test", api_base=OPENAI_FILES_API_BASE
|
|
)
|
|
|
|
assert exc_info.value.title == "OpenAIFileObject"
|
|
assert [error["loc"] for error in exc_info.value.errors()] == [("bytes",)]
|
|
|
|
|
|
VLLM_ROUTER_API_BASE: Final = "http://vllm-router.test/v1"
|
|
VLLM_ROUTER_FILE: Final = MappingProxyType(
|
|
{"id": "file-b73f4c", "bytes": 156, "created_at": 1793238707, "filename": "batch_requests.jsonl", "purpose": "batch"}
|
|
)
|
|
|
|
|
|
async def _upload_to_vllm_router() -> OpenAIFileObject:
|
|
return await litellm.acreate_file(
|
|
file=("batch_requests.jsonl", b'{"custom_id": "request-1"}'),
|
|
purpose="batch",
|
|
custom_llm_provider="hosted_vllm",
|
|
api_key="sk-test",
|
|
api_base=VLLM_ROUTER_API_BASE,
|
|
)
|
|
|
|
|
|
async def _retrieve_from_vllm_router() -> OpenAIFileObject:
|
|
return await litellm.afile_retrieve(
|
|
file_id="file-b73f4c", custom_llm_provider="hosted_vllm", api_key="sk-test", api_base=VLLM_ROUTER_API_BASE
|
|
)
|
|
|
|
|
|
VLLM_ROUTER_FILE_CALLS: Final = (
|
|
pytest.param("POST", "/files", _upload_to_vllm_router, id="acreate_file"),
|
|
pytest.param("GET", "/files/file-b73f4c", _retrieve_from_vllm_router, id="afile_retrieve"),
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("method, path, call_router", VLLM_ROUTER_FILE_CALLS)
|
|
@respx.mock
|
|
async def test_hosted_vllm_file_without_an_object_type_comes_back_as_a_file(
|
|
method: str, path: str, call_router: Callable[[], Awaitable[OpenAIFileObject]]
|
|
):
|
|
respx.route(method=method, url=f"{VLLM_ROUTER_API_BASE}{path}").respond(200, json=dict(VLLM_ROUTER_FILE))
|
|
|
|
file_object: Final = await call_router()
|
|
|
|
assert file_object.model_dump(exclude_none=True) == {**VLLM_ROUTER_FILE, "object": "file"}
|
|
|
|
|
|
@pytest.mark.parametrize("method, path, call_router", VLLM_ROUTER_FILE_CALLS)
|
|
@respx.mock
|
|
async def test_hosted_vllm_file_with_a_different_object_type_is_rejected(
|
|
method: str, path: str, call_router: Callable[[], Awaitable[OpenAIFileObject]]
|
|
):
|
|
respx.route(method=method, url=f"{VLLM_ROUTER_API_BASE}{path}").respond(
|
|
200, json={**VLLM_ROUTER_FILE, "object": "batch"}
|
|
)
|
|
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
await call_router()
|
|
|
|
assert [error["loc"] for error in exc_info.value.errors()] == [("object",)]
|
|
|
|
|
|
_FILE_BODY: Final = b'{"prompt": "Hello", "completion": "Hi"}'
|
|
_FINE_TUNE_FILE_JSON: Final = MappingProxyType(
|
|
{
|
|
"id": "file-abc123",
|
|
"object": "file",
|
|
"bytes": len(_FILE_BODY),
|
|
"created_at": 1699000000,
|
|
"filename": "mydata.jsonl",
|
|
"purpose": "fine-tune",
|
|
}
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_openai_file_operations_roundtrip(respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
|
|
files_route: Final = respx_mock.post("https://api.openai.com/v1/files").mock(
|
|
return_value=httpx.Response(200, json=dict(_FINE_TUNE_FILE_JSON))
|
|
)
|
|
list_route: Final = respx_mock.get("https://api.openai.com/v1/files").mock(
|
|
return_value=httpx.Response(200, json={"object": "list", "data": [dict(_FINE_TUNE_FILE_JSON)]})
|
|
)
|
|
retrieve_route: Final = respx_mock.get("https://api.openai.com/v1/files/file-abc123").mock(
|
|
return_value=httpx.Response(200, json=dict(_FINE_TUNE_FILE_JSON))
|
|
)
|
|
content_route: Final = respx_mock.get("https://api.openai.com/v1/files/file-abc123/content").mock(
|
|
return_value=httpx.Response(200, content=_FILE_BODY)
|
|
)
|
|
delete_route: Final = 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})
|
|
)
|
|
|
|
uploaded: Final = await litellm.acreate_file(
|
|
file=("mydata.jsonl", _FILE_BODY), purpose="fine-tune", custom_llm_provider="openai", api_key="fake-key"
|
|
)
|
|
assert files_route.call_count == 1
|
|
upload_body: Final = files_route.calls.last.request.content
|
|
assert b'name="purpose"\r\n\r\nfine-tune' in upload_body
|
|
assert b'filename="mydata.jsonl"' in upload_body
|
|
assert _FILE_BODY in upload_body
|
|
assert uploaded.id == "file-abc123"
|
|
|
|
listed: Final = await litellm.afile_list(custom_llm_provider="openai", api_key="fake-key")
|
|
assert list_route.call_count == 1
|
|
assert [file.id for file in listed.data] == ["file-abc123"]
|
|
|
|
retrieved: Final = await litellm.afile_retrieve(
|
|
file_id="file-abc123", custom_llm_provider="openai", api_key="fake-key"
|
|
)
|
|
assert retrieve_route.call_count == 1
|
|
assert retrieved.filename == "mydata.jsonl"
|
|
assert retrieved.purpose == "fine-tune"
|
|
|
|
content: Final = await litellm.afile_content(
|
|
file_id="file-abc123", custom_llm_provider="openai", api_key="fake-key"
|
|
)
|
|
assert content_route.call_count == 1
|
|
assert content.content == _FILE_BODY
|
|
|
|
deleted: Final = await litellm.afile_delete(file_id="file-abc123", custom_llm_provider="openai", api_key="fake-key")
|
|
assert delete_route.call_count == 1
|
|
assert deleted.id == "file-abc123"
|
|
assert deleted.deleted is True
|
|
|
|
|
|
async def _create_file(sync_mode: bool, upload: Mapping[str, object]) -> OpenAIFileObject:
|
|
if sync_mode:
|
|
return litellm.create_file(**upload)
|
|
return await litellm.acreate_file(**upload)
|
|
|
|
|
|
def _upload(custom_llm_provider: str, api_base: str, **overrides: object) -> Mapping[str, object]:
|
|
return MappingProxyType(
|
|
{
|
|
"file": ("batch.jsonl", b'{"custom_id": "1"}\n', "application/jsonl"),
|
|
"purpose": "batch",
|
|
"custom_llm_provider": custom_llm_provider,
|
|
"api_key": "sk-test",
|
|
"api_base": api_base,
|
|
"api_version": "2025-04-01-preview",
|
|
**overrides,
|
|
}
|
|
)
|
|
|
|
|
|
def _created_file() -> httpx.Response:
|
|
return httpx.Response(200, json={**_FINE_TUNE_FILE_JSON, "purpose": "batch"})
|
|
|
|
|
|
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)
|
|
|
|
|
|
_ANSWERS_A_RESEND_CANNOT_DUPLICATE: Final = (
|
|
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.Response(504, headers={"x-should-retry": "true"}, json={"error": {"message": "send it again"}}),
|
|
id="504-should-retry",
|
|
),
|
|
pytest.param(lambda: httpx.ConnectError("connection refused"), id="connect-error"),
|
|
pytest.param(lambda: httpx.ConnectTimeout("no connection in time"), id="connect-timeout"),
|
|
pytest.param(lambda: httpx.ProxyError("the egress proxy refused the connection"), id="proxy-error"),
|
|
pytest.param(lambda: httpx.WriteTimeout("the body was not written in time"), id="write-timeout"),
|
|
pytest.param(lambda: httpx.WriteError("the connection reset while the body was sent"), id="write-error"),
|
|
pytest.param(lambda: httpx.LocalProtocolError("the request could not be sent"), id="local-protocol-error"),
|
|
pytest.param(lambda: httpx.UnsupportedProtocol("the URL scheme is not supported"), id="unsupported-protocol"),
|
|
)
|
|
|
|
_ANSWERS_AFTER_THE_PROVIDER_MAY_HAVE_CREATED_IT: Final = (
|
|
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.param(
|
|
lambda: httpx.Response(504, json={"error": {"message": "the gateway gave up waiting"}}),
|
|
openai.APIStatusError,
|
|
id="504",
|
|
),
|
|
)
|
|
|
|
|
|
@pytest.mark.usefixtures("resend_at_once")
|
|
@pytest.mark.parametrize("first_answer", _ANSWERS_A_RESEND_CANNOT_DUPLICATE)
|
|
@pytest.mark.parametrize("custom_llm_provider", ["openai", "azure"])
|
|
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
|
|
async def test_a_file_upload_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()}.upload.test"
|
|
upload_route: Final = respx_mock.post(url__startswith=api_base).mock(side_effect=[first_answer(), _created_file()])
|
|
|
|
created: Final = await _create_file(sync_mode, _upload(custom_llm_provider, api_base))
|
|
|
|
assert upload_route.call_count == 2
|
|
assert created.id == _FINE_TUNE_FILE_JSON["id"]
|
|
|
|
|
|
@pytest.mark.usefixtures("resend_at_once")
|
|
@pytest.mark.parametrize("first_answer, expected_error", _ANSWERS_AFTER_THE_PROVIDER_MAY_HAVE_CREATED_IT)
|
|
@pytest.mark.parametrize("custom_llm_provider", ["openai", "azure"])
|
|
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
|
|
async def test_a_file_upload_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()}.upload.test"
|
|
upload_route: Final = respx_mock.post(url__startswith=api_base).mock(side_effect=[first_answer(), _created_file()])
|
|
|
|
with pytest.raises(expected_error):
|
|
await _create_file(sync_mode, _upload(custom_llm_provider, api_base))
|
|
|
|
assert upload_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_file_upload_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()}.upload.test"
|
|
upload_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_file(
|
|
sync_mode,
|
|
_upload(custom_llm_provider, api_base, extra_headers={"x-request-tag": "kept"}, **explicit_max_retries),
|
|
)
|
|
|
|
assert upload_route.call_count == expected_posts
|
|
assert [call.request.headers["x-stainless-retry-count"] for call in upload_route.calls] == [
|
|
str(retries_taken) for retries_taken in range(expected_posts)
|
|
]
|
|
assert {call.request.headers["x-request-tag"] for call in upload_route.calls} == {"kept"}
|
|
|
|
|
|
@pytest.mark.usefixtures("resend_at_once")
|
|
@pytest.mark.parametrize("custom_llm_provider", ["openai", "azure"])
|
|
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
|
|
async def test_a_resent_file_upload_carries_only_the_retry_count_the_caller_set(
|
|
custom_llm_provider: str, sync_mode: bool, request: pytest.FixtureRequest, respx_mock: respx.MockRouter
|
|
):
|
|
api_base: Final = f"https://{request.node.callspec.id.lower()}.upload.test"
|
|
upload_route: Final = respx_mock.post(url__startswith=api_base).mock(
|
|
return_value=httpx.Response(429, json={"error": {"message": "slow down"}})
|
|
)
|
|
|
|
with pytest.raises(openai.RateLimitError):
|
|
await _create_file(
|
|
sync_mode, _upload(custom_llm_provider, api_base, extra_headers={"X-Stainless-Retry-Count": "7"})
|
|
)
|
|
|
|
assert upload_route.call_count == 3
|
|
assert {tuple(call.request.headers.get_list("x-stainless-retry-count")) for call in upload_route.calls} == {
|
|
("7",)
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
|
|
async def test_a_file_upload_is_never_sent_without_headers_the_caller_passed_as_a_list(
|
|
sync_mode: bool, request: pytest.FixtureRequest, respx_mock: respx.MockRouter
|
|
):
|
|
api_base: Final = f"https://{request.node.callspec.id.lower()}.upload.test"
|
|
upload_route: Final = respx_mock.post(url__startswith=api_base).mock(return_value=_created_file())
|
|
|
|
with pytest.raises(TypeError):
|
|
await _create_file(sync_mode, _upload("openai", api_base, extra_headers=[["x-request-tag", "kept"]]))
|
|
|
|
assert upload_route.call_count == 0
|
|
|
|
|
|
@pytest.mark.parametrize("sync_mode", [True, False], ids=["sync", "async"])
|
|
async def test_a_rate_limited_file_upload_waits_the_providers_retry_after_before_the_resend(
|
|
sync_mode: bool, request: pytest.FixtureRequest, respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
|
|
api_base: Final = f"https://{request.node.callspec.id.lower()}.upload.test"
|
|
upload_route: Final = respx_mock.post(url__startswith=api_base).mock(
|
|
side_effect=[
|
|
httpx.Response(429, headers={"retry-after": "2"}, json={"error": {"message": "slow down"}}),
|
|
_created_file(),
|
|
]
|
|
)
|
|
sync_sleep: Final = MagicMock()
|
|
async_sleep: Final = AsyncMock()
|
|
monkeypatch.setattr(time, "sleep", sync_sleep)
|
|
monkeypatch.setattr(asyncio, "sleep", async_sleep)
|
|
|
|
await _create_file(sync_mode, _upload("openai", api_base))
|
|
|
|
waits: Final = tuple(call.args[0] for call in (*sync_sleep.call_args_list, *async_sleep.call_args_list))
|
|
assert upload_route.call_count == 2
|
|
assert any(2 <= wait <= 2 + JITTER for wait in waits), waits
|