mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
* refactor(types): type the kwargs reads in the responses, images, realtime, files, google_genai, rerank, passthrough, batches and fine_tuning entrypoints Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(responses): assert the returned response in the shared_session call-site test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(google_genai): pass a non-string litellm_call_id through as None instead of validating it Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(types): read a non-callable azure_ad_token_provider and an attribute-less user_api_key_dict as unset instead of raising Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(responses): refuse a user_api_key_dict without auth attributes at the read so token limits fail closed Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(rerank): assert the provider request for a wrong-typed instruction Replace the two tests that inspected get_optional_rerank_params call args with one that checks the body sent to hosted_vllm, mark the files raw_logging_obj reads Final, and drop a banner comment that repeated the test names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(images): read image_generation kwargs without a cast main's volcengine change cast the untyped **kwargs to a Mapping; this branch types them as object, so the cast is no longer needed Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(responses): keep a prompt_version sent as a numeric string aresponses narrowed prompt_version to int and dropped "2", which main forwards to the prompt hook and Dotprompt resolves to the .v2 template. Parse digit strings to int so the same template is selected Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(responses): parse prompt_version with isdecimal so a superscript digit does not raise Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
472 lines
19 KiB
Python
472 lines
19 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
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"litellm_call_id, expected",
|
|
[(None, "generated-call-id"), (123, "123")],
|
|
ids=["explicit-none-gets-a-generated-id", "non-string-is-stringified"],
|
|
)
|
|
def test_file_retrieve_gives_its_own_logging_object_a_string_call_id(
|
|
monkeypatch: pytest.MonkeyPatch, litellm_call_id: int | None, expected: str
|
|
) -> None:
|
|
from litellm.files import main as files_main
|
|
|
|
retrieve_file: Final = MagicMock(return_value="SENTINEL")
|
|
monkeypatch.setattr(files_main.base_llm_http_handler, "retrieve_file", retrieve_file)
|
|
monkeypatch.setattr(files_main.uuid_module, "uuid4", lambda: "generated-call-id")
|
|
|
|
files_main.file_retrieve.__wrapped__(
|
|
file_id="file-abc123", custom_llm_provider="anthropic", api_key="sk-test", litellm_call_id=litellm_call_id
|
|
)
|
|
|
|
assert retrieve_file.call_args.kwargs["logging_obj"].litellm_call_id == expected
|