mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-02 01:28: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>
752 lines
29 KiB
Python
752 lines
29 KiB
Python
import asyncio
|
|
import json
|
|
import logging
|
|
from typing import Final
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import httpx
|
|
import openai
|
|
import pytest
|
|
import respx
|
|
|
|
import litellm
|
|
from litellm.litellm_core_utils.token_counter import token_counter
|
|
from litellm.llms.openai.common_utils import (
|
|
BaseOpenAILLM,
|
|
create_may_already_exist,
|
|
drop_params_from_unprocessable_entity_error,
|
|
is_openai_backed_api_base,
|
|
)
|
|
|
|
# Test parameters for different API functions
|
|
API_FUNCTION_PARAMS = [
|
|
# (function_name, is_async, args)
|
|
(
|
|
"completion",
|
|
False,
|
|
{
|
|
"model": "gpt-4o-mini",
|
|
"messages": [{"role": "user", "content": "Hello"}],
|
|
"max_tokens": 10,
|
|
},
|
|
),
|
|
(
|
|
"completion",
|
|
True,
|
|
{
|
|
"model": "gpt-4o-mini",
|
|
"messages": [{"role": "user", "content": "Hello"}],
|
|
"max_tokens": 10,
|
|
},
|
|
),
|
|
(
|
|
"completion",
|
|
True,
|
|
{
|
|
"model": "gpt-4o-mini",
|
|
"messages": [{"role": "user", "content": "Hello"}],
|
|
"max_tokens": 10,
|
|
"stream": True,
|
|
},
|
|
),
|
|
("embedding", False, {"model": "text-embedding-ada-002", "input": "Hello world"}),
|
|
("embedding", True, {"model": "text-embedding-ada-002", "input": "Hello world"}),
|
|
(
|
|
"image_generation",
|
|
False,
|
|
{"model": "gpt-image-2.5-sunburst", "prompt": "A beautiful sunset over mountains"},
|
|
),
|
|
(
|
|
"image_generation",
|
|
True,
|
|
{"model": "gpt-image-2.5-sunburst", "prompt": "A beautiful sunset over mountains"},
|
|
),
|
|
(
|
|
"speech",
|
|
False,
|
|
{
|
|
"model": "tts-1",
|
|
"input": "Hello, this is a test of text to speech",
|
|
"voice": "alloy",
|
|
},
|
|
),
|
|
(
|
|
"speech",
|
|
True,
|
|
{
|
|
"model": "tts-1",
|
|
"input": "Hello, this is a test of text to speech",
|
|
"voice": "alloy",
|
|
},
|
|
),
|
|
("transcription", False, {"model": "whisper-1", "file": MagicMock()}),
|
|
("transcription", True, {"model": "whisper-1", "file": MagicMock()}),
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("function_name,is_async,args", API_FUNCTION_PARAMS)
|
|
@pytest.mark.asyncio
|
|
async def test_openai_client_reuse(function_name, is_async, args):
|
|
"""
|
|
Test that multiple API calls reuse the same OpenAI client
|
|
"""
|
|
|
|
# Determine which client class to mock based on whether the test is async
|
|
client_path = "litellm.llms.openai.openai.AsyncOpenAI" if is_async else "litellm.llms.openai.openai.OpenAI"
|
|
|
|
# Create the appropriate patches
|
|
with (
|
|
patch(client_path) as mock_client_class,
|
|
patch.object(BaseOpenAILLM, "set_cached_openai_client") as mock_set_cache,
|
|
patch.object(BaseOpenAILLM, "get_cached_openai_client") as mock_get_cache,
|
|
):
|
|
# Setup the mock to return None first time (cache miss) then a client for subsequent calls
|
|
mock_client = MagicMock()
|
|
mock_get_cache.side_effect = [None] + [mock_client] * 9 # First call returns None, rest return the mock client
|
|
|
|
# Make 10 API calls
|
|
for _ in range(10):
|
|
try:
|
|
# Call the appropriate function based on parameters
|
|
if is_async:
|
|
# Add 'a' prefix for async functions
|
|
func = getattr(litellm, f"a{function_name}")
|
|
await func(**args)
|
|
else:
|
|
func = getattr(litellm, function_name)
|
|
func(**args)
|
|
except Exception:
|
|
# We expect exceptions since we're mocking the client
|
|
pass
|
|
|
|
# Verify client was created only once
|
|
assert mock_client_class.call_count == 1, (
|
|
f"{'Async' if is_async else ''}OpenAI client should be created only once"
|
|
)
|
|
|
|
# Verify the client was cached
|
|
assert mock_set_cache.call_count == 1, "Client should be cached once"
|
|
|
|
# Verify we tried to get from cache 10 times (once per request)
|
|
assert mock_get_cache.call_count == 10, "Should check cache for each request"
|
|
|
|
|
|
def test_precomputed_init_params_match_inspect_signature():
|
|
"""
|
|
Verify that the pre-computed _OPENAI_INIT_PARAMS and _AZURE_OPENAI_INIT_PARAMS
|
|
match what inspect.signature() returns. If the OpenAI SDK changes its __init__
|
|
params, this test will fail — signaling the constants need updating.
|
|
"""
|
|
import inspect
|
|
|
|
from openai import AzureOpenAI, OpenAI
|
|
|
|
from litellm.llms.openai.common_utils import (
|
|
_AZURE_OPENAI_INIT_PARAMS,
|
|
_OPENAI_INIT_PARAMS,
|
|
)
|
|
|
|
expected_openai = tuple(p for p in inspect.signature(OpenAI.__init__).parameters if p != "self")
|
|
expected_azure = tuple(p for p in inspect.signature(AzureOpenAI.__init__).parameters if p != "self")
|
|
|
|
assert _OPENAI_INIT_PARAMS == expected_openai
|
|
assert _AZURE_OPENAI_INIT_PARAMS == expected_azure
|
|
|
|
|
|
@pytest.mark.parametrize("client_type", ["openai", "azure"])
|
|
def test_get_openai_client_initialization_param_fields(client_type):
|
|
"""Verify the method returns the correct pre-computed params for each client type."""
|
|
result = BaseOpenAILLM.get_openai_client_initialization_param_fields(client_type)
|
|
assert isinstance(result, tuple)
|
|
assert len(result) > 0
|
|
assert "self" not in result
|
|
|
|
|
|
def _loop_test_client_params(is_async: bool) -> dict[str, object]:
|
|
return {"api_key": "sk-loop-scope-test", "is_async": is_async}
|
|
|
|
|
|
async def _cache_openai_client(client: openai.OpenAI | openai.AsyncOpenAI, is_async: bool) -> None:
|
|
BaseOpenAILLM.set_cached_openai_client(client, "openai", _loop_test_client_params(is_async))
|
|
|
|
|
|
async def _cached_openai_client(is_async: bool) -> object:
|
|
return BaseOpenAILLM.get_cached_openai_client(_loop_test_client_params(is_async), "openai")
|
|
|
|
|
|
def test_sync_openai_client_cached_in_one_loop_is_reused_by_the_next_while_async_is_not():
|
|
sync_client: Final = openai.OpenAI(api_key="sk-loop-scope-test")
|
|
async_client: Final = openai.AsyncOpenAI(api_key="sk-loop-scope-test")
|
|
asyncio.run(_cache_openai_client(sync_client, is_async=False))
|
|
asyncio.run(_cache_openai_client(async_client, is_async=True))
|
|
|
|
assert asyncio.run(_cached_openai_client(is_async=False)) is sync_client
|
|
assert asyncio.run(_cached_openai_client(is_async=True)) is None
|
|
|
|
|
|
@pytest.mark.parametrize("client_type", ["openai", "azure"])
|
|
def test_get_openai_client_cache_key(client_type):
|
|
"""Verify get_openai_client_cache_key doesn't raise on tuple + tuple concatenation."""
|
|
key = BaseOpenAILLM.get_openai_client_cache_key(
|
|
client_initialization_params={"api_key": "sk-test"},
|
|
client_type=client_type,
|
|
)
|
|
assert isinstance(key, str)
|
|
assert "api_key=sk-test" in key
|
|
|
|
|
|
def test_evicting_a_client_built_on_the_callers_session_leaves_that_session_open(monkeypatch):
|
|
"""`litellm.aclient_session` belongs to the caller, who goes on using it.
|
|
|
|
`_get_async_http_client` hands that session straight back, so the SDK client
|
|
litellm builds around it is only a wrapper. The SDK's `close()` closes
|
|
whatever http client it was given, so treating the wrapper as litellm's to
|
|
close would close the caller's shared session out from under them.
|
|
"""
|
|
import httpx
|
|
|
|
from litellm.caching.evicted_client_closer import EvictedClientCloser
|
|
from litellm.caching.llm_caching_handler import LLMClientCache
|
|
from litellm.llms.openai.openai import OpenAIChatCompletion
|
|
|
|
shared_session = httpx.AsyncClient()
|
|
closer = EvictedClientCloser(grace_seconds=0.0)
|
|
monkeypatch.setattr(litellm, "aclient_session", shared_session)
|
|
monkeypatch.setattr(
|
|
litellm,
|
|
"in_memory_llm_clients_cache",
|
|
LLMClientCache(evicted_client_closer=closer),
|
|
)
|
|
|
|
wrapper = OpenAIChatCompletion().get_openai_client(
|
|
is_async=True,
|
|
api_key="sk-not-a-real-key",
|
|
api_base="https://api.openai.com/v1",
|
|
max_retries=2,
|
|
)
|
|
|
|
assert wrapper is not None
|
|
assert wrapper._client is shared_session, "the wrapper should be built on the caller's session"
|
|
|
|
closer.schedule(wrapper)
|
|
closer.reap()
|
|
|
|
assert closer.pending_count == 0, "a wrapper around the caller's session must never be queued"
|
|
assert shared_session.is_closed is False, "closed the session the caller configured"
|
|
|
|
|
|
def test_a_client_litellm_built_its_own_http_client_for_is_still_closed(monkeypatch):
|
|
"""The ownership check must not turn the reclaim off for the ordinary case."""
|
|
from litellm.caching.evicted_client_closer import EvictedClientCloser
|
|
from litellm.caching.llm_caching_handler import LLMClientCache
|
|
from litellm.llms.openai.openai import OpenAIChatCompletion
|
|
|
|
closer = EvictedClientCloser(grace_seconds=0.0)
|
|
monkeypatch.setattr(litellm, "aclient_session", None)
|
|
monkeypatch.setattr(litellm, "client_session", None)
|
|
monkeypatch.setattr(
|
|
litellm,
|
|
"in_memory_llm_clients_cache",
|
|
LLMClientCache(evicted_client_closer=closer),
|
|
)
|
|
|
|
wrapper = OpenAIChatCompletion().get_openai_client(
|
|
is_async=False,
|
|
api_key="sk-not-a-real-key",
|
|
api_base="https://api.openai.com/v1",
|
|
max_retries=2,
|
|
)
|
|
|
|
assert wrapper is not None
|
|
closer.schedule(wrapper)
|
|
|
|
assert closer.pending_count == 1, "litellm built this client's http client, so it owns it"
|
|
|
|
closer.reap()
|
|
|
|
assert wrapper.is_closed() is True
|
|
|
|
|
|
OUTPUT_LIMIT_400_MESSAGE = (
|
|
"Could not finish the message because max_tokens or model output limit was reached. "
|
|
"Please try again with higher max_tokens."
|
|
)
|
|
GENUINE_400_MESSAGE = "Invalid value for 'max_tokens': integer above maximum value. Expected <= 128000, got 999999999."
|
|
LONG_PROMPT = "please summarise the following notes for me: " + ("token " * 200)
|
|
|
|
CALL_KWARGS_BY_PROVIDER = {
|
|
"openai": {"model": "gpt-5.6-sol", "api_key": "sk-not-a-real-key"},
|
|
"azure": {
|
|
"model": "azure/gpt-5.6-sol",
|
|
"api_key": "not-a-real-key",
|
|
"api_base": "https://not-a-real-resource.openai.azure.com",
|
|
"api_version": "2024-10-21",
|
|
},
|
|
}
|
|
|
|
|
|
def _transport(message: str) -> httpx.MockTransport:
|
|
def _handler(_request: httpx.Request) -> httpx.Response:
|
|
return httpx.Response(400, json={"error": {"message": message, "type": "invalid_request_error"}})
|
|
|
|
return httpx.MockTransport(_handler)
|
|
|
|
|
|
def _sync_client_raising(provider: str, message: str):
|
|
http_client = httpx.Client(transport=_transport(message))
|
|
if provider == "azure":
|
|
return openai.AzureOpenAI(
|
|
api_key="not-a-real-key",
|
|
azure_endpoint="https://not-a-real-resource.openai.azure.com",
|
|
api_version="2024-10-21",
|
|
http_client=http_client,
|
|
)
|
|
return openai.OpenAI(api_key="sk-not-a-real-key", http_client=http_client)
|
|
|
|
|
|
def _async_client_raising(provider: str, message: str):
|
|
http_client = httpx.AsyncClient(transport=_transport(message))
|
|
if provider == "azure":
|
|
return openai.AsyncAzureOpenAI(
|
|
api_key="not-a-real-key",
|
|
azure_endpoint="https://not-a-real-resource.openai.azure.com",
|
|
api_version="2024-10-21",
|
|
http_client=http_client,
|
|
)
|
|
return openai.AsyncOpenAI(api_key="sk-not-a-real-key", http_client=http_client)
|
|
|
|
|
|
def _completion_kwargs(provider: str, client, **overrides) -> dict:
|
|
return {
|
|
**CALL_KWARGS_BY_PROVIDER[provider],
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"max_tokens": 1,
|
|
"client": client,
|
|
**overrides,
|
|
}
|
|
|
|
|
|
_REASONING_EFFORT_422: Final = {
|
|
"error": {
|
|
"message": json.dumps(
|
|
{"detail": [{"loc": ["body", "reasoning_effort"], "msg": "Extra inputs are not permitted"}]}
|
|
)
|
|
}
|
|
}
|
|
_CHAT_COMPLETION: Final = {
|
|
"id": "chatcmpl-1",
|
|
"object": "chat.completion",
|
|
"created": 1,
|
|
"model": "gpt-6.1-sol",
|
|
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
|
|
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
|
|
}
|
|
_CHAT_COMPLETION_STREAM: Final = (
|
|
'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","created":1,"model":"gpt-6.1-sol",'
|
|
'"choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}\n\n'
|
|
"data: [DONE]\n\n"
|
|
)
|
|
|
|
|
|
def _answer_422_while_reasoning_effort_is_sent(request: httpx.Request) -> httpx.Response:
|
|
body: Final = json.loads(request.content)
|
|
if "reasoning_effort" in body:
|
|
return httpx.Response(422, json=_REASONING_EFFORT_422)
|
|
if body.get("stream"):
|
|
return httpx.Response(200, text=_CHAT_COMPLETION_STREAM, headers={"content-type": "text/event-stream"})
|
|
return httpx.Response(200, json=_CHAT_COMPLETION)
|
|
|
|
|
|
async def _complete_through_the_422_retry(call_shape: str) -> str:
|
|
transport: Final = httpx.MockTransport(_answer_422_while_reasoning_effort_is_sent)
|
|
kwargs: Final = {
|
|
"model": "gpt-6.1-sol",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"reasoning_effort": "high",
|
|
}
|
|
if call_shape == "sync":
|
|
sync_client: Final = openai.OpenAI(api_key="sk-not-a-real-key", http_client=httpx.Client(transport=transport))
|
|
return litellm.completion(**kwargs, client=sync_client).choices[0].message.content
|
|
async_client: Final = openai.AsyncOpenAI(
|
|
api_key="sk-not-a-real-key", http_client=httpx.AsyncClient(transport=transport)
|
|
)
|
|
if call_shape == "async":
|
|
return (await litellm.acompletion(**kwargs, client=async_client)).choices[0].message.content
|
|
stream: Final = await litellm.acompletion(**kwargs, client=async_client, stream=True)
|
|
return "".join([chunk.choices[0].delta.content or "" async for chunk in stream])
|
|
|
|
|
|
@pytest.mark.parametrize("call_shape", ["sync", "async", "async_stream"])
|
|
def test_a_422_naming_reasoning_effort_drops_it_with_one_warning(
|
|
call_shape: str, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "drop_params", True)
|
|
with caplog.at_level(logging.WARNING, logger="LiteLLM"):
|
|
content: Final = asyncio.run(_complete_through_the_422_retry(call_shape))
|
|
drop_warnings: Final = [record.getMessage() for record in caplog.records if "Dropping" in record.getMessage()]
|
|
|
|
assert content == "ok"
|
|
assert len(drop_warnings) == 1
|
|
assert all(
|
|
fragment in drop_warnings[0]
|
|
for fragment in ("reasoning_effort='high'", "gpt-6.1-sol", "(drop_params=True)", "422")
|
|
)
|
|
|
|
|
|
def test_a_422_with_an_unhashable_loc_still_drops_reasoning_effort_with_one_warning(
|
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
detail: Final = [
|
|
{"loc": ["body", ["messages", 0]], "msg": "Invalid"},
|
|
{"loc": ["body", "reasoning_effort"], "msg": "Extra inputs are not permitted"},
|
|
]
|
|
|
|
def answer(request: httpx.Request) -> httpx.Response:
|
|
if "reasoning_effort" in json.loads(request.content):
|
|
return httpx.Response(422, json={"error": {"message": json.dumps({"detail": detail})}})
|
|
return httpx.Response(200, json=_CHAT_COMPLETION)
|
|
|
|
monkeypatch.setattr(litellm, "drop_params", True)
|
|
client: Final = openai.OpenAI(
|
|
api_key="sk-not-a-real-key", http_client=httpx.Client(transport=httpx.MockTransport(answer))
|
|
)
|
|
with caplog.at_level(logging.WARNING, logger="LiteLLM"):
|
|
response: Final = litellm.completion(
|
|
model="gpt-6.1-sol",
|
|
messages=[{"role": "user", "content": "hi"}],
|
|
reasoning_effort="high",
|
|
client=client,
|
|
)
|
|
drop_warnings: Final = [record.getMessage() for record in caplog.records if "Dropping" in record.getMessage()]
|
|
|
|
assert response.choices[0].message.content == "ok"
|
|
assert len(drop_warnings) == 1
|
|
assert "reasoning_effort='high'" in drop_warnings[0]
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
def test_sync_output_limit_400_maps_to_length_truncated_response(provider):
|
|
response = litellm.completion(
|
|
**_completion_kwargs(provider, _sync_client_raising(provider, OUTPUT_LIMIT_400_MESSAGE))
|
|
)
|
|
|
|
assert response.choices[0].finish_reason == "length"
|
|
assert response.choices[0].message.content == ""
|
|
assert response.usage.completion_tokens == 0
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
def test_mapped_response_still_bills_the_prompt_the_provider_processed(provider):
|
|
messages = [{"role": "user", "content": LONG_PROMPT}]
|
|
expected_prompt_tokens = token_counter(model="gpt-5.6-sol", messages=messages)
|
|
assert expected_prompt_tokens > 100, "the fixture prompt must be big enough for a zeroed count to stand out"
|
|
|
|
response = litellm.completion(
|
|
**_completion_kwargs(provider, _sync_client_raising(provider, OUTPUT_LIMIT_400_MESSAGE), messages=messages)
|
|
)
|
|
|
|
assert response.usage.prompt_tokens == expected_prompt_tokens
|
|
assert response.usage.completion_tokens == 0
|
|
assert litellm.completion_cost(completion_response=response) > 0
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
@pytest.mark.parametrize(
|
|
("base_model", "counted_as"), [("azure/gpt-6.1-sol", "azure/gpt-6.1-sol"), ("claude-sonnet-4-5", "my-gpt-6")]
|
|
)
|
|
@pytest.mark.asyncio
|
|
async def test_mapped_response_bills_a_custom_named_deployment_with_its_base_model_only_when_it_is_openai(
|
|
provider: str, base_model: str, counted_as: str
|
|
) -> None:
|
|
messages: Final = [{"role": "user", "content": "日本語のテキストとहिन्दी पाठ और русский текст. " * 20}]
|
|
overrides: Final = {"model": f"{provider}/my-gpt-6", "messages": messages, "base_model": base_model}
|
|
|
|
sync_response: Final = litellm.completion(
|
|
**_completion_kwargs(provider, _sync_client_raising(provider, OUTPUT_LIMIT_400_MESSAGE), **overrides)
|
|
)
|
|
async_response: Final = await litellm.acompletion(
|
|
**_completion_kwargs(provider, _async_client_raising(provider, OUTPUT_LIMIT_400_MESSAGE), **overrides)
|
|
)
|
|
|
|
expected: Final = token_counter(model=counted_as, messages=messages)
|
|
assert token_counter(model=base_model, messages=messages) != token_counter(model="my-gpt-6", messages=messages)
|
|
assert (sync_response.usage.prompt_tokens, async_response.usage.prompt_tokens) == (expected, expected)
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
@pytest.mark.asyncio
|
|
async def test_async_output_limit_400_maps_to_length_truncated_response(provider):
|
|
response = await litellm.acompletion(
|
|
**_completion_kwargs(provider, _async_client_raising(provider, OUTPUT_LIMIT_400_MESSAGE))
|
|
)
|
|
|
|
assert response.choices[0].finish_reason == "length"
|
|
assert response.choices[0].message.content == ""
|
|
assert response.usage.completion_tokens == 0
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
def test_sync_streaming_output_limit_400_maps_to_length_truncated_stream(provider):
|
|
stream = litellm.completion(
|
|
**_completion_kwargs(provider, _sync_client_raising(provider, OUTPUT_LIMIT_400_MESSAGE), stream=True)
|
|
)
|
|
chunks = list(stream)
|
|
|
|
assert [c.choices[0].finish_reason for c in chunks].count("length") == 1
|
|
assert all(not c.choices[0].delta.content for c in chunks)
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
@pytest.mark.asyncio
|
|
async def test_async_streaming_output_limit_400_maps_to_length_truncated_stream(provider):
|
|
stream = await litellm.acompletion(
|
|
**_completion_kwargs(provider, _async_client_raising(provider, OUTPUT_LIMIT_400_MESSAGE), stream=True)
|
|
)
|
|
chunks = [chunk async for chunk in stream]
|
|
|
|
assert [c.choices[0].finish_reason for c in chunks].count("length") == 1
|
|
assert all(not c.choices[0].delta.content for c in chunks)
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
@pytest.mark.parametrize("stream", [False, True])
|
|
def test_sync_genuine_bad_request_still_raises(provider, stream):
|
|
def _call_and_drain():
|
|
result = litellm.completion(
|
|
**_completion_kwargs(provider, _sync_client_raising(provider, GENUINE_400_MESSAGE), stream=stream)
|
|
)
|
|
list(result)
|
|
|
|
with pytest.raises(litellm.BadRequestError):
|
|
_call_and_drain()
|
|
|
|
|
|
@pytest.mark.parametrize("provider", ["openai", "azure"])
|
|
@pytest.mark.parametrize("stream", [False, True])
|
|
@pytest.mark.asyncio
|
|
async def test_async_genuine_bad_request_still_raises(provider, stream):
|
|
async def _call_and_drain():
|
|
result = await litellm.acompletion(
|
|
**_completion_kwargs(provider, _async_client_raising(provider, GENUINE_400_MESSAGE), stream=stream)
|
|
)
|
|
async for _ in result:
|
|
pass
|
|
|
|
with pytest.raises(litellm.BadRequestError):
|
|
await _call_and_drain()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("api_base", "expected"),
|
|
[
|
|
("https://api.openai.com/v1", True),
|
|
("https://api.openai.com:443/v1/", True),
|
|
("https://southcentralus.privatelink.api.openai.com/v1", True),
|
|
("https://eu.api.openai.com/v1", True),
|
|
("HTTPS://API.OPENAI.COM/v1", True),
|
|
("https://my-gateway.example/v1", False),
|
|
("https://api.openai.com.evil.example/v1", False),
|
|
("https://notapi.openai.com/v1", False),
|
|
("https://gateway.example/v1?upstream=api.openai.com", False),
|
|
("not a url", False),
|
|
],
|
|
)
|
|
def test_is_openai_backed_api_base_decides_by_hostname_only(api_base, expected):
|
|
assert is_openai_backed_api_base(api_base) is expected
|
|
|
|
|
|
def _sdk_api_client(
|
|
api: str,
|
|
is_async: bool,
|
|
timeout: float | httpx.Timeout | openai.Timeout | None,
|
|
client: openai.OpenAI | openai.AsyncOpenAI | None = None,
|
|
) -> openai.OpenAI | openai.AsyncOpenAI | None:
|
|
from litellm.llms.azure.common_utils import BaseAzureLLM
|
|
from litellm.llms.openai.fine_tuning.handler import OpenAIFineTuningAPI
|
|
from litellm.llms.openai.image_variations.handler import OpenAIImageVariationsHandler
|
|
from litellm.llms.openai.openai import OpenAIAssistantsAPI, OpenAIBatchesAPI, OpenAIFilesAPI
|
|
|
|
kwargs: Final = {
|
|
"api_key": "transport-only",
|
|
"api_base": "https://sdk-default.example/v1",
|
|
"timeout": timeout,
|
|
"max_retries": 0,
|
|
"organization": None,
|
|
"client": client,
|
|
}
|
|
if api == "assistants":
|
|
assistant_factory: Final = OpenAIAssistantsAPI()
|
|
return (
|
|
assistant_factory.async_get_openai_client(**kwargs)
|
|
if is_async
|
|
else assistant_factory.get_openai_client(**kwargs)
|
|
)
|
|
if api == "image_variations":
|
|
variation_factory: Final = OpenAIImageVariationsHandler()
|
|
return (
|
|
variation_factory.get_async_client(
|
|
client=client,
|
|
api_key="transport-only",
|
|
api_base="https://sdk-default.example/v1",
|
|
timeout=timeout,
|
|
max_retries=0,
|
|
organization=None,
|
|
litellm_params={},
|
|
)
|
|
if is_async
|
|
else variation_factory.get_sync_client(
|
|
client=client,
|
|
api_key="transport-only",
|
|
api_base="https://sdk-default.example/v1",
|
|
timeout=timeout,
|
|
max_retries=0,
|
|
organization=None,
|
|
litellm_params={},
|
|
)
|
|
)
|
|
if api == "azure_gateway":
|
|
return BaseAzureLLM()._init_azure_client_for_cloudflare_ai_gateway(
|
|
api_base="https://sdk-default.example",
|
|
model="deployment",
|
|
api_version="2024-02-01",
|
|
max_retries=0,
|
|
timeout=timeout,
|
|
litellm_params={},
|
|
api_key="transport-only",
|
|
azure_ad_token=None,
|
|
azure_ad_token_provider=None,
|
|
acompletion=is_async,
|
|
client=client,
|
|
)
|
|
factory: Final = {"files": OpenAIFilesAPI, "batches": OpenAIBatchesAPI, "fine_tuning": OpenAIFineTuningAPI}[api]()
|
|
return factory.get_openai_client(**kwargs, _is_async=is_async)
|
|
|
|
|
|
async def _list_model_ids(sdk_client: openai.OpenAI | openai.AsyncOpenAI) -> list[str]:
|
|
page: Final = (
|
|
await sdk_client.models.list() if isinstance(sdk_client, openai.AsyncOpenAI) else sdk_client.models.list()
|
|
)
|
|
return [model.id for model in page.data]
|
|
|
|
|
|
@pytest.mark.parametrize("api", ["files", "batches", "assistants", "fine_tuning", "image_variations", "azure_gateway"])
|
|
@pytest.mark.parametrize("is_async", [False, True])
|
|
@pytest.mark.asyncio
|
|
async def test_sdk_api_factories_keep_httpx_transport_and_request_timeouts(api: str, is_async: bool) -> None:
|
|
timeout: Final = openai.Timeout(connect=1, read=7, write=2, pool=3)
|
|
with respx.mock(assert_all_called=True) as mock:
|
|
mock.get(host="sdk-default.example", path__regex=r".*/models$").mock(
|
|
return_value=httpx.Response(307, headers={"location": "https://sdk-default.example/v1/moved-models"})
|
|
)
|
|
moved: Final = mock.get(host="sdk-default.example", path="/v1/moved-models").mock(
|
|
return_value=httpx.Response(
|
|
200,
|
|
json={
|
|
"object": "list",
|
|
"data": [{"id": "sdk-compat", "object": "model", "created": 0, "owned_by": "t"}],
|
|
},
|
|
)
|
|
)
|
|
sdk_client: Final = _sdk_api_client(api, is_async, timeout)
|
|
assert sdk_client is not None
|
|
try:
|
|
assert _sdk_api_client(api, is_async, 19, client=sdk_client) is sdk_client
|
|
model_ids: Final = await _list_model_ids(sdk_client)
|
|
finally:
|
|
if is_async:
|
|
await sdk_client.close()
|
|
else:
|
|
sdk_client.close()
|
|
assert model_ids == ["sdk-compat"]
|
|
assert moved.calls.last.request.extensions["timeout"] == {"connect": 1.0, "read": 7.0, "write": 2.0, "pool": 3.0}
|
|
|
|
|
|
@pytest.mark.parametrize("backend", ["httpx", "sdk_default"])
|
|
@pytest.mark.asyncio
|
|
async def test_azure_gateway_and_image_variations_use_the_callers_async_session(
|
|
backend: str, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
from importlib import import_module
|
|
from io import BytesIO
|
|
|
|
from openai._types import Response as SDKResponse
|
|
|
|
from litellm.images.main import aimage_variation
|
|
|
|
http_module: Final = httpx if backend == "httpx" else import_module(SDKResponse.__module__)
|
|
transport: Final = http_module.MockTransport(
|
|
lambda request: http_module.Response(
|
|
200, json={"created": 0, "data": [{"url": "https://example.com/image.png"}]}
|
|
)
|
|
)
|
|
async with http_module.AsyncClient(transport=transport) as session:
|
|
monkeypatch.setattr(litellm, "aclient_session", session)
|
|
monkeypatch.setattr(litellm, "client_session", None)
|
|
azure_client: Final = _sdk_api_client("azure_gateway", True, 7)
|
|
assert azure_client is not None
|
|
assert azure_client._client is session
|
|
response: Final = await aimage_variation(
|
|
image=BytesIO(b"image-bytes"),
|
|
custom_llm_provider="openai",
|
|
api_key="transport-only",
|
|
api_base="https://sdk-default.example/v1",
|
|
)
|
|
assert response.data[0].url == "https://example.com/image.png"
|
|
assert not session.is_closed
|
|
|
|
|
|
|
|
def test_reasoning_drop_warning_caps_a_large_caller_value(caplog: pytest.LogCaptureFixture) -> None:
|
|
error: Final = httpx.HTTPStatusError(
|
|
message="422",
|
|
request=httpx.Request("POST", "https://example.invalid/v1/chat/completions"),
|
|
response=httpx.Response(422, json=_REASONING_EFFORT_422),
|
|
)
|
|
data: Final[dict[str, object]] = {"model": "gpt-6.1-sol", "messages": [], "reasoning_effort": "x" * 5000}
|
|
|
|
with caplog.at_level(logging.WARNING, logger="LiteLLM"):
|
|
retried: Final = drop_params_from_unprocessable_entity_error(
|
|
error, data, model="gpt-6.1-sol", drop_params_gated=True
|
|
)
|
|
drop_warnings: Final = [record.getMessage() for record in caplog.records if "Dropping" in record.getMessage()]
|
|
|
|
assert "reasoning_effort" not in retried
|
|
assert len(drop_warnings) == 1
|
|
assert len(drop_warnings[0]) < 300
|
|
assert all(fragment in drop_warnings[0] for fragment in ("reasoning_effort='xxx", "'gpt-6.1-sol'", "422"))
|
|
|
|
|
|
@pytest.mark.parametrize("upstream_body", ["upstream is down", "<html>bad gateway</html>", "[1, 2]", "12345"])
|
|
@respx.mock
|
|
def test_an_error_body_that_is_not_a_json_object_keeps_the_upstream_status(upstream_body: str) -> None:
|
|
respx.post("https://errors.example.invalid/v1/chat/completions").mock(
|
|
return_value=httpx.Response(400, text=upstream_body)
|
|
)
|
|
|
|
with pytest.raises(litellm.BadRequestError) as raised:
|
|
litellm.completion(
|
|
model="openai/test-model",
|
|
api_base="https://errors.example.invalid/v1",
|
|
api_key="test-key",
|
|
messages=[{"role": "user", "content": "hi"}],
|
|
max_retries=0,
|
|
)
|
|
|
|
assert raised.value.status_code == 400
|
|
assert upstream_body in raised.value.message
|
|
|
|
|
|
@pytest.mark.parametrize(("method", "may_exist"), [("GET", False), ("POST", True)])
|
|
def test_a_gateway_timeout_says_a_create_may_exist_only_when_it_answered_a_write(method: str, may_exist: bool) -> None:
|
|
response: Final = httpx.Response(504, request=httpx.Request(method, "https://files.example.invalid/v1/files"))
|
|
|
|
assert create_may_already_exist(openai.APIStatusError("Gateway Timeout", response=response, body=None)) is may_exist
|
|
|
|
|
|
def test_a_gateway_timeout_on_a_followed_redirect_says_the_create_may_exist() -> None:
|
|
upload: Final = httpx.Response(303, request=httpx.Request("POST", "https://files.example.invalid/v1/files"))
|
|
followed: Final = httpx.Response(
|
|
504, request=httpx.Request("GET", "https://files.example.invalid/v1/files"), history=[upload]
|
|
)
|
|
|
|
assert create_may_already_exist(openai.APIStatusError("Gateway Timeout", response=followed, body=None))
|