mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-30 01:08:33 +00:00
* feat(anthropic): workload identity federation and pluggable identity sources Backend half of #38818 (internal copy of the fork PR #38013), rebuilt as one commit on top of litellm_internal_staging without the dashboard changes. Deployments on anthropic/ without a static api_key can exchange an OIDC workload assertion for a short-lived sk-ant-oat01 token through a shared RFC 7523 JWT-bearer engine. The assertion comes from a mounted token file, an env token, a LiteLLM-signed issuer, or Keycloak, chosen per deployment, per named credential, or through ANTHROPIC_IDENTITY_SOURCE. The federation fields are server-owned: refused inline in request bodies and on POST /model/new, proxy-admin only on credentials, and the token exchange is pinned to api.anthropic.com unless LITELLM_ANTHROPIC_WIF_ALLOWED_HOSTS adds a host. GET /credentials/{name}/jwks exports the public key set of a LiteLLM-signed credential for the Claude Console. The OpenAI federation trio from #39613 rides along on the backend side with the same server-owned handling. Fixes #28607 Resolves LIT-6107 Co-authored-by: derhornspieler <15236687+derhornspieler@users.noreply.github.com> * fix(anthropic): let batch-result downloads mint from deployment params and accept host:port allowlist entries The files handler enabled workload identity on batch-result downloads but never received the deployment's litellm_params, so a deployment authenticating through a named credential could only mint from process-wide env vars. It now threads litellm_params through to the auth header the way the batch retrieve path already does. LITELLM_ANTHROPIC_WIF_ALLOWED_HOSTS entries written as host:port were read by urlsplit as a scheme, so the allowlist kept the raw entry while the exchange compared bare hostnames and refused the gateway. Entries are now parsed as network locations whether or not they carry a scheme. * fix(types): move the WIF kwargs key sets to a leaf module so the kwargs funnel imports without a cycle * test(anthropic): pin case-insensitive matching of WIF exchange-host allowlist entries * fix(anthropic): end workload identity federation errors without a period so the router suffix reads cleanly * fix(proxy): decrypt stored litellm_params before the WIF write gate * fix(proxy): hide WIF secret references from /health output * fix(proxy): keep the proxy error shape on credential endpoint refusals * fix(proxy): hide identity token file paths from /health output * feat(openai): honor per-deployment workload identity on non-chat routes Image generation, audio speech and transcription, moderation, text completions, files, batches, and fine-tuning built their OpenAI client from the env vars alone, so a keyless deployment carrying openai_identity_provider_id, openai_service_account_id, and openai_identity_token_file failed with the api_key error on every route other than chat, Responses, and embeddings. Those handlers now build their client through the shared workload identity resolver, and the managed batch file-access credential extraction keeps the trio * fix(openai): cache workload identity clients and let deployment identity outrank process-wide keys Non-chat handlers built a fresh SDK client per call, so files, batches, fine-tuning, text completion and sync moderation exchanged the OIDC token on every request. The builders now reuse the cached workload identity client per identity, base, timeout, retries and organization; static-key clients are still built fresh. A process-wide OPENAI_API_KEY (or litellm.api_key / litellm.openai_key) no longer silently overrides a deployment's openai_identity_* params. An explicit distinct api_key on the deployment or call still wins. * fix(openai): keep shared workload identity clients on the process http session The workload identity client is cached and shared across requests, so it must never borrow the transport a single caller passed in. Static-key clients keep using the caller's http client; federated clients always ride the process-wide session. Also makes the http client helpers on BaseOpenAILLM public since the builder now needs them from outside the class. * test(openai): pin partial deployment identity beating the process key * test(openai): type the managed-object invoke callback * fix(anthropic): rename the federation workspace param so Bedrock's anthropic_workspace_id keeps working The Bedrock Claude Platform route already reads anthropic_workspace_id from optional_params, so banning that spelling as a server-owned federation parameter broke a pre-existing client capability. The federation field is now anthropic_federation_workspace_id (env ANTHROPIC_FEDERATION_WORKSPACE_ID), which restores the base branch's behavior for Bedrock callers, drops the Bedrock-specific hint from the refusal message, and deletes the unconditional ban constant that no longer had a reader * fix(auth): share one exchanged token across workers reading the same assertion Anthropic accepts each identity assertion exactly once, so two uvicorn workers reading the same token file both minting from it means the second exchange is denied with jti_reused. Minted tokens now land in a per-user 0700 cache directory guarded by a file lock, so workers on the same host reuse one exchange until the token expires or the assertion rotates. A 401 is only retried when the re-read assertion actually differs, and the denial hint explains jti_reused. LITELLM_TOKEN_EXCHANGE_CACHE_DIR moves the cache and an empty value disables it * feat(openai): honor deployment workload identity on image edits, vector stores, containers, videos, and evals The httpx-based OpenAI handlers built their Authorization header from the deployment api_key or OPENAI_API_KEY alone, so a keyless deployment carrying openai_identity_provider_id, openai_service_account_id, and openai_identity_token_file sent "Bearer None". They now resolve the bearer through resolve_openai_bearer_token, which exchanges the deployment's identity token the same way the SDK-based routes do. A deployment that carries only part of the identity trio now raises a 500 naming the missing field instead of silently falling back to the process key, and the SDK client builders take a factory for the static-key http client so the federated branch never touches litellm.client_session. * fix: keep anthropic federation from being shadowed or leaked An empty or whitespace-only ANTHROPIC_API_KEY counted as set, so a federated deployment sent an empty x-api-key on every call instead of minting a token. Blank values now read as unset, and a real static key on a federated deployment logs once that it outranks federation and nothing is being federated. The exchange-host allowlist matched hostnames only, so a second process on another port of an allowed host was trusted with the workload's identity token. An entry that names a port now trusts that port alone, while a bare host still trusts every port. The shared token store exists so the workers reading one projected token file do not each spend its single-use jti. A source that mints its own assertion per exchange shares nothing with another worker, so it no longer writes a live token to disk for a lookup that can never hit. * feat(openai): resolve per-deployment workload identity for the assistants routes OpenAIAssistantsAPI built its OpenAI and AsyncOpenAI clients from a locals() scrape, so a deployment carrying openai_identity_provider_id, openai_service_account_id and openai_identity_token_file never exchanged a token. Thread litellm_params through the class and build both clients with the shared workload identity builders. * fix: unlink a staged token file a failed write leaves behind The 401 denial hint now also says federation ignores ANTHROPIC_WORKSPACE_ID, which the Bedrock Claude platform provider already reads. * refactor: move anthropic jwks derivation behind a provider-owned tagged union * feat(openai): resolve per-deployment workload identity for image variations Build the image variations client through the shared workload identity builders instead of scraping locals(), and give the async path the async http session it was missing. Let a federation trio serve the model-less batch fallback, and hold the standard LRU size of exchanged tokens. * fix: unlink the staged token file when its write fails at close A buffered write only reaches the disk when the handle closes, so a full disk surfaces at close and left the staging file behind holding a usable token. * fix(anthropic): close the staging descriptor before writing the shared token file * fix(wif): judge federation writes by what they set, not what is stored The admin gate read the stored deployment, so a team admin lost edit, delete and Test Connection on any deployment carrying federation params. It now returns early unless the submitted fields touch the federation surface, and a Test Connection probe that points the deployment at its own api_base is still refused, with the 403 no longer wrapped into a 500 The rest of the same review pass: POST /model/new refuses only a blocking value of `blocked`, so a client that always sends `blocked: false` is not turned away; a request body can no longer pick which federated identity to mint as by naming a stored credential; an advisory refresh the executor refuses disarms the entry instead of wedging the identity until the follower timeout; the static-key shadow warning resolves its env fallback inside the cache instead of once per request; credential writes drop nulls before storing them; the token exchange validates the endpoint URL before reading an assertion and keeps refusing redirects across a client heal; /health hides every server-owned federation field from non-admins; and the async create_file and create_batch paths say which setting is missing when the provider resolves no URL * style(tests): keep two blank lines before the batch_cost_is_final block * test(batches): type the workload identity fallback test fixtures * fix(moderation): stop validating unrelated kwargs on the sync workload identity path * fix(auth): refuse server-owned workload identity keys in array form and inside a client router config * fix(openai): keep a deployment's own key ahead of workload identity on every route Thread the caller's own api_key into the identity resolver for embedding, transcription, moderation, image generation, and assistants so a deployment key equal to the process key still wins. A partial identity trio now falls back to a configured static key, unset max_retries keeps the SDK default, and /v1/decisions plus OpenAI count_tokens resolve the exchanged bearer for identity-only deployments * fix(containers): pass deployment params to container file auth headers Container file routes built their auth headers without the deployment's litellm_params, so a keyless deployment with an OpenAI workload identity sent Bearer None on upload, list, retrieve, delete and content calls * fix(openai): keep process-wide key precedence and move token exchange off the event loop Restore the merge base order where an explicit or process-wide OpenAI key wins over federation, so exporting OPENAI_API_KEY keeps working the way it did before. Run the header-building validate_environment calls (image edit, videos, containers, vector stores, vector store files) and the decisions and System One request preparation in a worker thread, so a slow token exchange no longer stalls the loop. Federate realtime websocket sessions, live sessions, realtime client secrets and transcription sessions, and the OpenAI moderation guardrail when no key is set. * fix(openai): answer 401 for a partial identity trio and federate realtime health checks A deployment with part of the workload identity trio and no static key now fails as an auth error naming the missing params, so the router does not retry it as a server error. The realtime health check sends the exchanged bearer for a keyless federated OpenAI deployment, and API token counting reads the same static keys as every other route before minting. * fix(openai): keep local token counting without an identity trio and federate the moderation guardrail from its own config * fix(openai): skip a partial-trio moderation guardrail and let vault keys win in token counting * test(integration): refuse caller-chosen identity params in user_config and bracketed form keys * fix(openai): send the honored secret manager key from SDK client builders A deployment whose OPENAI_API_KEY lives only in the secret manager now sends that key on image, assistants, files, batches, and other SDK-built routes instead of failing with no api_key, matching what the workload identity resolver already treats as a static key * test(openai): check the token exchange runs off the event loop instead of timing the loop --------- Co-authored-by: derhornspieler <15236687+derhornspieler@users.noreply.github.com>
548 lines
20 KiB
Python
548 lines
20 KiB
Python
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, 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": "dall-e-3", "prompt": "A beautiful sunset over mountains"},
|
|
),
|
|
(
|
|
"image_generation",
|
|
True,
|
|
{"model": "dall-e-3", "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
|
|
|
|
|
|
@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,
|
|
}
|
|
|
|
|
|
@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.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"), 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
|