Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test(embeddings): move legacy intercepts to the wire for the omitted-format path

mateo-berri8e687f10047c
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.json
index 962d1266fd7..ba57fd1278b 100644
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@ -105,7 +105,7 @@
"limit": 109
},
"reportUnknownMemberType": {
- "limit": 38721
+ "limit": 38720
},
"reportUnknownParameterType": {
"limit": 19778
diff --git a/litellm/llms/hosted_vllm/embedding/README.md b/litellm/llms/hosted_vllm/embedding/README.md
index 32b7ea5c560..50474aabdeb 100644
--- a/litellm/llms/hosted_vllm/embedding/README.md
+++ b/litellm/llms/hosted_vllm/embedding/README.md
@@ -4,7 +4,7 @@ VLLM is a superset of OpenAI's `embedding` endpoint.
## `encoding_format`
-For OpenAI-compatible embedding calls (including `openai/...` with a custom `api_base` pointing at vLLM), LiteLLM resolves `encoding_format` when it is not set on the request:
+For OpenAI-compatible embedding calls (including `openai/...` with a custom `api_base` pointing at vLLM), LiteLLM resolves `encoding_format` when it is not set on the request. `hosted_vllm/...` models use a separate handler that never adds the field on its own, so this resolution applies to the `openai/...`-style routes only:
1. Explicit value on the embedding call (`encoding_format=...`).
2. Model config (`litellm_params.encoding_format` on the proxy `model_list` entry).
diff --git a/litellm/utils.py b/litellm/utils.py
index fa2226dbf2c..66a07d2e2db 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -3542,10 +3542,10 @@ def get_optional_params_embeddings(
non_default_params=non_default_params, optional_params={}, kwargs=kwargs
)
elif custom_llm_provider == "vertex_ai" or custom_llm_provider == "gemini":
- # OpenAI SDKs (and litellm's own client) send encoding_format="float"
- # by default; float lists are exactly what the vertex API returns, so
- # the param is a no-op — don't reject the provider default. Other
- # values (e.g. "base64") stay on the unsupported-param path below.
+ # OpenAI SDKs send encoding_format="float" by default; float lists are
+ # exactly what the vertex API returns, so the param is a no-op — don't
+ # reject the provider default. Other values (e.g. "base64") stay on
+ # the unsupported-param path below.
if non_default_params.get("encoding_format") == "float":
non_default_params.pop("encoding_format")
supported_params = get_supported_openai_params(
diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json
index c60988eccc0..73c69a732fe 100644
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@ -9,7 +9,7 @@
"limit": 827
},
"ANN201": {
- "limit": 2003
+ "limit": 2001
},
"ANN202": {
"limit": 845
@@ -240,13 +240,13 @@
"limit": 96
},
"TRY201": {
- "limit": 405
+ "limit": 403
},
"TRY203": {
- "limit": 113
+ "limit": 111
},
"TRY300": {
- "limit": 857
+ "limit": 855
},
"UP028": {
"limit": 2
diff --git a/test-quality-budget.json b/test-quality-budget.json
index ee33eb581d6..d834c581609 100644
--- a/test-quality-budget.json
+++ b/test-quality-budget.json
@@ -3,7 +3,7 @@
"limit": 733
},
"TQ002": {
- "limit": 742
+ "limit": 741
},
"TQ003": {
"limit": 62
@@ -21,6 +21,6 @@
"limit": 117
},
"TQ008": {
- "limit": 11139
+ "limit": 11135
}
}
diff --git a/tests/llm_translation/test_litellm_proxy_provider.py b/tests/llm_translation/test_litellm_proxy_provider.py
index 1cb805bf9ba..8630259877d 100644
--- a/tests/llm_translation/test_litellm_proxy_provider.py
+++ b/tests/llm_translation/test_litellm_proxy_provider.py
@@ -5,6 +5,7 @@ from io import BytesIO
from unittest.mock import AsyncMock
+import httpx
import litellm
from litellm import completion, embedding
import pytest
@@ -92,44 +93,54 @@ async def test_litellm_gateway_from_sdk_embedding(is_async):
litellm.set_verbose = True
litellm._turn_on_debug()
+ captured_bodies = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured_bodies.append(json.loads(request.content))
+ return httpx.Response(
+ 200,
+ json={
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": [0.1, 0.2, 0.3]}],
+ "model": "my-vllm-model",
+ "usage": {"prompt_tokens": 2, "total_tokens": 2},
+ },
+ )
+
if is_async:
from openai import AsyncOpenAI
- openai_client = AsyncOpenAI(api_key="fake-key")
- mock_method = AsyncMock()
- patch_target = openai_client.embeddings.create
+ openai_client = AsyncOpenAI(
+ api_key="fake-key",
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ )
+ response = await litellm.aembedding(
+ model="litellm_proxy/my-vllm-model",
+ input="Hello world",
+ client=openai_client,
+ api_base="my-custom-api-base",
+ )
else:
from openai import OpenAI
- openai_client = OpenAI(api_key="fake-key")
- mock_method = MagicMock()
- patch_target = openai_client.embeddings.create
-
- with patch.object(patch_target.__self__, patch_target.__name__, new=mock_method):
- try:
- if is_async:
- await litellm.aembedding(
- model="litellm_proxy/my-vllm-model",
- input="Hello world",
- client=openai_client,
- api_base="my-custom-api-base",
- )
- else:
- litellm.embedding(
- model="litellm_proxy/my-vllm-model",
- input="Hello world",
- client=openai_client,
- api_base="my-custom-api-base",
- )
- except Exception as e:
- print(e)
-
- mock_method.assert_called_once()
+ openai_client = OpenAI(
+ api_key="fake-key",
+ http_client=httpx.Client(transport=httpx.MockTransport(handler)),
+ )
+ response = litellm.embedding(
+ model="litellm_proxy/my-vllm-model",
+ input="Hello world",
+ client=openai_client,
+ api_base="my-custom-api-base",
+ )
- print("Call KWARGS - {}".format(mock_method.call_args.kwargs))
+ request_body = captured_bodies[0]
+ print("Request body - {}".format(request_body))
- assert "Hello world" == mock_method.call_args.kwargs["input"]
- assert "my-vllm-model" == mock_method.call_args.kwargs["model"]
+ assert "Hello world" == request_body["input"]
+ assert "my-vllm-model" == request_body["model"]
+ assert "encoding_format" not in request_body
+ assert response.data[0]["embedding"] == [0.1, 0.2, 0.3]
@pytest.mark.parametrize("is_async", [False, True])
diff --git a/tests/llm_translation/test_nvidia_nim.py b/tests/llm_translation/test_nvidia_nim.py
index 7ee4f347f72..d5942e674d0 100644
--- a/tests/llm_translation/test_nvidia_nim.py
+++ b/tests/llm_translation/test_nvidia_nim.py
@@ -63,27 +63,39 @@ def test_embedding_nvidia_nim():
litellm.set_verbose = True
from openai import OpenAI
+ captured_bodies = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured_bodies.append(json.loads(request.content))
+ return httpx.Response(
+ 200,
+ json={
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": [0.1, 0.2, 0.3]}],
+ "model": "nvidia/nv-embedqa-e5-v5",
+ "usage": {"prompt_tokens": 6, "total_tokens": 6},
+ },
+ )
+
client = OpenAI(
api_key="fake-api-key",
+ http_client=httpx.Client(transport=httpx.MockTransport(handler)),
)
- with patch.object(client.embeddings.with_raw_response, "create") as mock_client:
- try:
- litellm.embedding(
- model="nvidia_nim/nvidia/nv-embedqa-e5-v5",
- input="What is the meaning of life?",
- input_type="passage",
- dimensions=1024,
- client=client,
- )
- except Exception as e:
- print(e)
- mock_client.assert_called_once()
- request_body = mock_client.call_args.kwargs
- print("request_body: ", request_body)
- assert request_body["input"] == "What is the meaning of life?"
- assert request_body["model"] == "nvidia/nv-embedqa-e5-v5"
- assert request_body["extra_body"]["input_type"] == "passage"
- assert request_body["dimensions"] == 1024
+ response = litellm.embedding(
+ model="nvidia_nim/nvidia/nv-embedqa-e5-v5",
+ input="What is the meaning of life?",
+ input_type="passage",
+ dimensions=1024,
+ client=client,
+ )
+ request_body = captured_bodies[0]
+ print("request_body: ", request_body)
+ assert request_body["input"] == "What is the meaning of life?"
+ assert request_body["model"] == "nvidia/nv-embedqa-e5-v5"
+ assert request_body["input_type"] == "passage"
+ assert request_body["dimensions"] == 1024
+ assert "encoding_format" not in request_body
+ assert response.data[0]["embedding"] == [0.1, 0.2, 0.3]
def test_chat_completion_nvidia_nim_with_tools():
diff --git a/tests/local_testing/test_exceptions.py b/tests/local_testing/test_exceptions.py
index 8370046446d..e6392cda406 100644
--- a/tests/local_testing/test_exceptions.py
+++ b/tests/local_testing/test_exceptions.py
@@ -5,7 +5,7 @@ import traceback
from typing import Any
import httpx
-from openai import AsyncOpenAI, AuthenticationError, BadRequestError, OpenAIError, RateLimitError
+from openai import AsyncAzureOpenAI, AsyncOpenAI, AuthenticationError, AzureOpenAI, BadRequestError, OpenAIError, RateLimitError
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
@@ -895,7 +895,12 @@ def _pre_call_utils(
):
if call_type == "embedding":
data["input"] = "Hello world!"
- mapped_target: Any = client.embeddings.with_raw_response
+ if isinstance(client, (AzureOpenAI, AsyncAzureOpenAI)):
+ mapped_target: Any = client.embeddings.with_raw_response
+ patched_attr = "create"
+ else:
+ mapped_target = client
+ patched_attr = "post"
if sync_mode:
original_function = litellm.embedding
else:
@@ -905,6 +910,7 @@ def _pre_call_utils(
if streaming is True:
data["stream"] = True
mapped_target = client.chat.completions.with_raw_response # type: ignore
+ patched_attr = "create"
if sync_mode:
original_function = litellm.completion
else:
@@ -914,12 +920,13 @@ def _pre_call_utils(
if streaming is True:
data["stream"] = True
mapped_target = client.completions.with_raw_response # type: ignore
+ patched_attr = "create"
if sync_mode:
original_function = litellm.text_completion
else:
original_function = litellm.atext_completion
- return data, original_function, mapped_target
+ return data, original_function, mapped_target, patched_attr
def _pre_call_utils_httpx(
@@ -1003,7 +1010,7 @@ async def test_exception_with_headers(sync_mode, provider, model, call_type, str
)
data = {"model": model}
- data, original_function, mapped_target = _pre_call_utils(
+ data, original_function, mapped_target, patched_attr = _pre_call_utils(
call_type=call_type,
data=data,
client=openai_client,
@@ -1049,7 +1056,7 @@ async def test_exception_with_headers(sync_mode, provider, model, call_type, str
with patch.object(
mapped_target,
- "create",
+ patched_attr,
side_effect=_return_exception,
):
new_retry_after_mock_client = MagicMock(return_value=-1)
diff --git a/tests/local_testing/test_router.py b/tests/local_testing/test_router.py
index 370c43f8f44..c714bb4f9a7 100644
--- a/tests/local_testing/test_router.py
+++ b/tests/local_testing/test_router.py
@@ -2032,8 +2032,8 @@ def test_router_dynamic_cooldown_correct_retry_after_time():
raise exception
with patch.object(
- openai_client.embeddings.with_raw_response,
- "create",
+ openai_client,
+ "post",
side_effect=_return_exception,
):
new_retry_after_mock_client = MagicMock(return_value=-1)
diff --git a/tests/test_litellm/test_openai_embedding_encoding_format_default.py b/tests/test_litellm/test_openai_embedding_encoding_format_default.py
index 9842bf30585..7a42eaf0f0a 100644
--- a/tests/test_litellm/test_openai_embedding_encoding_format_default.py
+++ b/tests/test_litellm/test_openai_embedding_encoding_format_default.py
@@ -100,3 +100,22 @@ async def test_aembedding_openai_omits_encoding_format_when_client_omits_it(
request_body: Final = json.loads(mock_route.calls.last.request.read())
assert "encoding_format" not in request_body
assert response.data[0]["embedding"] == [0.1, 0.2, 0.3]
+
+
+def test_embedding_openai_omitted_encoding_format_maps_provider_errors(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ respx_mock.post("https://api.openai.com/v1/embeddings").mock(
+ return_value=httpx.Response(
+ 429,
+ headers={"retry-after": "42", "x-should-retry": "false"},
+ json={"error": {"message": "rate limited", "type": "rate_limit_error"}},
+ )
+ )
+
+ with pytest.raises(litellm.RateLimitError) as exc_info:
+ litellm.embedding(
+ model="openai/text-embedding-3-small", input=["hello"], api_key="sk-test", max_retries=0
+ )
+
+ assert int(exc_info.value.litellm_response_headers["retry-after"]) == 42
diff --git a/type-discipline-budget.json b/type-discipline-budget.json
index f3f1a7defe7..67ebb2b3b17 100644
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@ -27,7 +27,7 @@
"limit": 0
},
"LIT010": {
- "limit": 16564
+ "limit": 16562
},
"LIT011": {
"limit": 5577