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(integration): cover embeddings endpoint contracts (#44660)

devin-ai-integration[bot]1c0f722aae53
diff --git a/tests/integration/compatibility/test_embedding_path_aliases.py b/tests/integration/compatibility/test_embedding_path_aliases.py
new file mode 100644
index 00000000000..fbb41e8e534
--- /dev/null
+++ b/tests/integration/compatibility/test_embedding_path_aliases.py
@@ -0,0 +1,216 @@
+import base64
+import json
+import struct
+from typing import Final, Literal
+
+import httpx
+import openai
+import pytest
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+_TEXT: Final = "path alias embedding marker"
+_VECTOR: Final = (0.25, 0.5, 0.75)
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+
+
+class _Embedding(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ object: Literal["embedding"]
+ index: int
+ embedding: list[float]
+
+
+class _Usage(BaseModel):
+ prompt_tokens: int
+ total_tokens: int
+
+
+class _EmbeddingResponse(BaseModel):
+ data: tuple[_Embedding, ...]
+ usage: _Usage
+
+
+def _assert_raw_embedding_response(response: httpx.Response) -> None:
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump() for item in payload.data] == [
+ {"object": "embedding", "index": 0, "embedding": list(_VECTOR)}
+ ], response.text
+ assert (payload.usage.prompt_tokens, payload.usage.total_tokens) == (1, 1), response.text
+
+
+def _reply(encoding_format: str | None) -> Reply:
+ embedding: Final = (
+ base64.b64encode(struct.pack("<3f", *_VECTOR)).decode("ascii") if encoding_format == "base64" else list(_VECTOR)
+ )
+ return Reply(
+ body=json.dumps(
+ {
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": embedding}],
+ "model": "text-embedding-3-small",
+ "usage": {"prompt_tokens": 1, "total_tokens": 1},
+ }
+ ).encode()
+ )
+
+
+_AZURE_SDK_BODY: Final = {
+ "model": "text-embedding-3-small",
+ "input": _TEXT,
+ "encoding_format": "base64",
+}
+
+
+def _drop_bearer_auth(request: httpx.Request) -> None:
+ request.headers.pop("authorization", None)
+ assert "api-key" in request.headers, dict(request.headers)
+
+
+def _azure_sdk_embedding(
+ gateway: Gateway,
+ deployment: str | None,
+ api_key: str,
+ model: str,
+) -> openai.types.CreateEmbeddingResponse:
+ with (
+ httpx.Client(trust_env=False, event_hooks={"request": [_drop_bearer_auth]}) as http_client,
+ openai.AzureOpenAI(
+ azure_endpoint=str(gateway.client.base_url).rstrip("/"),
+ azure_deployment=deployment,
+ api_key=api_key,
+ api_version="2024-10-21",
+ max_retries=0,
+ http_client=http_client,
+ ) as client,
+ ):
+ return client.embeddings.create(model=model, input=_TEXT)
+
+
+ "surface",
+ ("azure_sdk", "azure_sdk_path_over_body", "deployments_raw", "engines_raw", "bare"),
+ ids=("azure-sdk", "azure-sdk-path-over-body", "deployments-path", "engines-path", "bare-model"),
+)
+def test_embedding_model_is_resolved_from_each_endpoint_surface(
+ gateway: Gateway,
+ surface: Literal["azure_sdk", "azure_sdk_path_over_body", "deployments_raw", "engines_raw", "bare"],
+) -> None:
+ expected_key: Final = (
+ "synthetic-key-a"
+ if surface in ("azure_sdk", "azure_sdk_path_over_body", "deployments_raw")
+ else "synthetic-key-b"
+ )
+ # openai-python 2.33.0 defaults omitted encoding_format to base64: https://github.com/openai/openai-python/blob/v2.33.0/src/openai/resources/embeddings.py
+ expected_body: Final = (
+ _AZURE_SDK_BODY
+ if surface in ("azure_sdk", "azure_sdk_path_over_body")
+ else {"model": "text-embedding-3-small", "input": _TEXT}
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/v1/embeddings"
+ assert request.headers["authorization"] == f"Bearer {expected_key}"
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ assert body == expected_body, body
+ return _reply("base64" if surface in ("azure_sdk", "azure_sdk_path_over_body") else None)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ group_a: Final = scenario.model(
+ model="openai/text-embedding-3-small",
+ api_base=f"{wire.url}/v1",
+ api_key="synthetic-key-a",
+ )
+ group_b: Final = scenario.model(
+ model="openai/text-embedding-3-small",
+ api_base=f"{wire.url}/v1",
+ api_key="synthetic-key-b",
+ )
+ virtual_key: Final = scenario.key()
+
+ if surface in ("azure_sdk", "azure_sdk_path_over_body"):
+ deployment: Final = group_a if surface == "azure_sdk_path_over_body" else None
+ request_model: Final = group_b if surface == "azure_sdk_path_over_body" else group_a
+ response: Final = _azure_sdk_embedding(gateway, deployment, virtual_key, request_model)
+ if surface == "azure_sdk":
+ assert response.model == group_a, response.model_dump_json()
+ assert [item.embedding for item in response.data] == [list(_VECTOR)], response.model_dump_json()
+ assert [item.index for item in response.data] == [0], response.model_dump_json()
+ assert (response.usage.prompt_tokens, response.usage.total_tokens) == (1, 1), response.model_dump_json()
+ elif surface == "deployments_raw":
+ raw_response: Final = gateway.client.post(
+ f"/openai/deployments/{group_a}/embeddings?api-version=2024-10-21",
+ json={"input": _TEXT},
+ headers={"api-key": virtual_key},
+ )
+ _assert_raw_embedding_response(raw_response)
+ elif surface == "engines_raw":
+ raw_response = gateway.request(
+ "POST",
+ f"/engines/{group_b}/embeddings",
+ {"input": _TEXT},
+ key=virtual_key,
+ )
+ _assert_raw_embedding_response(raw_response)
+ else:
+ raw_response = gateway.request(
+ "POST",
+ "/embeddings",
+ {"model": group_b, "input": _TEXT},
+ key=virtual_key,
+ )
+ _assert_raw_embedding_response(raw_response)
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/v1/embeddings")]
+
+
+def test_azure_sdk_response_reports_the_path_group_that_served_it(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: AzureOpenAI with azure_deployment=<group_a> and model=<group_b> is served by group_a but the response model reports group_b"
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/v1/embeddings"
+ assert request.headers["authorization"] == "Bearer synthetic-key-a"
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ assert body == _AZURE_SDK_BODY, body
+ return _reply("base64")
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ group_a: Final = scenario.model(
+ model="openai/text-embedding-3-small",
+ api_base=f"{wire.url}/v1",
+ api_key="synthetic-key-a",
+ )
+ group_b: Final = scenario.model(
+ model="openai/text-embedding-3-small",
+ api_base=f"{wire.url}/v1",
+ api_key="synthetic-key-b",
+ )
+ virtual_key: Final = scenario.key()
+ response: Final = _azure_sdk_embedding(gateway, group_a, virtual_key, group_b)
+ assert response.model == group_a, response.model_dump_json()
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/v1/embeddings")]
+
+
+def test_deployments_embedding_rejects_invalid_key_without_upstream_request(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ raise AssertionError(f"Invalid key reached the peer: {request.method} {request.target}")
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="openai/text-embedding-3-small",
+ api_base=f"{wire.url}/v1",
+ api_key="synthetic-key-a",
+ )
+ response: Final = gateway.client.post(
+ f"/openai/deployments/{model}/embeddings?api-version=2024-10-21",
+ json={"input": _TEXT},
+ headers={"api-key": "sk-not-a-real-key"},
+ )
+ assert response.status_code == 401, response.text
+ assert wire.drain() == ()
diff --git a/tests/integration/providers/test_azure_embedding_wire.py b/tests/integration/providers/test_azure_embedding_wire.py
new file mode 100644
index 00000000000..0c5629d1906
--- /dev/null
+++ b/tests/integration/providers/test_azure_embedding_wire.py
@@ -0,0 +1,133 @@
+import base64
+import json
+import struct
+from typing import Final, Literal
+from urllib.parse import parse_qs
+
+import pytest
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+_DEPLOYMENT: Final = "embedding-deployment"
+_INPUTS: Final = ("azure embedding alpha", "azure embedding bravo")
+_VECTORS: Final = ((0.25, 0.5, 0.75), (-1.0, 0.125, 2.0))
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+
+
+class _Embedding(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ object: Literal["embedding"]
+ index: int
+ embedding: list[float]
+
+
+class _Usage(BaseModel):
+ prompt_tokens: int
+ total_tokens: int
+
+
+class _EmbeddingResponse(BaseModel):
+ data: tuple[_Embedding, ...]
+ usage: _Usage
+
+
+def _encoded(vector: tuple[float, ...]) -> str:
+ return base64.b64encode(struct.pack("<3f", *vector)).decode("ascii")
+
+
+def test_azure_embedding_uses_deployment_api_version_and_normalizes_response(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ path, separator, query = request.target.partition("?")
+ assert path == f"/openai/deployments/{_DEPLOYMENT}/embeddings", request.target
+ assert separator == "?", request.target
+ assert parse_qs(query) == {"api-version": ["2024-06-01"]}, request.target
+ assert request.headers["api-key"] == "synthetic-azure-key"
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ sent_fields: Final = {key: value for key, value in body.items() if key != "encoding_format"}
+ assert sent_fields == {"model": _DEPLOYMENT, "input": list(_INPUTS), "dimensions": 256}, body
+ embedding_values: Final = [_encoded(vector) for vector in _VECTORS]
+ return Reply(
+ body=json.dumps(
+ {
+ "object": "list",
+ "data": [
+ {"object": "embedding", "index": index, "embedding": embedding}
+ for index, embedding in enumerate(embedding_values)
+ ],
+ "model": _DEPLOYMENT,
+ "usage": {"prompt_tokens": 4, "total_tokens": 4},
+ }
+ ).encode()
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"azure/{_DEPLOYMENT}",
+ api_base=wire.url,
+ api_key="synthetic-azure-key",
+ api_version="2024-06-01",
+ )
+ virtual_key: Final = scenario.key()
+ response: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": list(_INPUTS), "dimensions": 256},
+ key=virtual_key,
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump() for item in payload.data] == [
+ {"object": "embedding", "index": index, "embedding": list(vector)} for index, vector in enumerate(_VECTORS)
+ ], response.text
+ assert (payload.usage.prompt_tokens, payload.usage.total_tokens) == (4, 4), response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ ("POST", f"/openai/deployments/{_DEPLOYMENT}/embeddings?api-version=2024-06-01")
+ ]
+
+
+def test_azure_embedding_omits_encoding_format_the_client_did_not_send(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: azure embeddings inject encoding_format=base64 into the upstream body when the client omitted it, "
+ "unlike openai which forwards the body as sent"
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == f"/openai/deployments/{_DEPLOYMENT}/embeddings?api-version=2024-06-01"
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ if "encoding_format" in body:
+ return Reply(status=400, body=b'{"error":"encoding_format must be omitted"}')
+ assert body == {"model": _DEPLOYMENT, "input": list(_INPUTS)}, body
+ return Reply(
+ body=json.dumps(
+ {
+ "object": "list",
+ "data": [
+ {"object": "embedding", "index": index, "embedding": list(vector)}
+ for index, vector in enumerate(_VECTORS)
+ ],
+ "model": _DEPLOYMENT,
+ "usage": {"prompt_tokens": 4, "total_tokens": 4},
+ }
+ ).encode()
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"azure/{_DEPLOYMENT}",
+ api_base=wire.url,
+ api_key="synthetic-azure-key",
+ api_version="2024-06-01",
+ )
+ response: Final = gateway.request("POST", "/v1/embeddings", {"model": model, "input": list(_INPUTS)})
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump() for item in payload.data] == [
+ {"object": "embedding", "index": index, "embedding": list(vector)} for index, vector in enumerate(_VECTORS)
+ ], response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ ("POST", f"/openai/deployments/{_DEPLOYMENT}/embeddings?api-version=2024-06-01")
+ ]
diff --git a/tests/integration/providers/test_embedding_cache_partial_hit_wire.py b/tests/integration/providers/test_embedding_cache_partial_hit_wire.py
new file mode 100644
index 00000000000..f7c56631208
--- /dev/null
+++ b/tests/integration/providers/test_embedding_cache_partial_hit_wire.py
@@ -0,0 +1,138 @@
+import json
+from typing import Final, Literal
+
+import httpx
+from integration._support.client import Gateway, eventually
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+_VECTORS: Final = {
+ "alpha": (1.0, 0.0, 0.0),
+ "bravo": (0.0, 1.0, 0.0),
+ "charlie": (0.0, 0.0, 1.0),
+}
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_TEXT_LIST: Final = TypeAdapter(list[str])
+
+
+class _Embedding(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ object: Literal["embedding"]
+ index: int
+ embedding: list[float]
+
+
+class _Usage(BaseModel):
+ prompt_tokens: int
+ total_tokens: int
+
+
+class _EmbeddingResponse(BaseModel):
+ data: tuple[_Embedding, ...]
+ usage: _Usage
+
+
+def _input_values(request: Request) -> tuple[str, ...]:
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ return tuple(_TEXT_LIST.validate_python(body["input"]))
+
+
+def _expected_data(inputs: tuple[str, ...]) -> list[dict[str, JsonValue]]:
+ return [
+ {
+ "object": "embedding",
+ "index": index,
+ "embedding": list(_VECTORS[text]),
+ }
+ for index, text in enumerate(inputs)
+ ]
+
+
+def test_embedding_cache_reuses_cached_items_during_partial_hits(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/v1/embeddings"
+ assert request.headers["authorization"] == "Bearer synthetic-cache-key"
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ inputs: Final = tuple(_TEXT_LIST.validate_python(body["input"]))
+ assert body == {"model": "text-embedding-3-small", "input": list(inputs)}
+ return Reply(
+ body=json.dumps(
+ {
+ "object": "list",
+ "data": [
+ {
+ "object": "embedding",
+ "index": index,
+ "embedding": list(_VECTORS[text]),
+ }
+ for index, text in enumerate(inputs)
+ ],
+ "model": "text-embedding-3-small",
+ "usage": {"prompt_tokens": len(inputs), "total_tokens": len(inputs)},
+ }
+ ).encode()
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="openai/text-embedding-3-small",
+ api_base=f"{wire.url}/v1",
+ api_key="synthetic-cache-key",
+ )
+
+ def attempt_alpha() -> tuple[httpx.Response, tuple[Request, ...]]:
+ response: Final = gateway.request("POST", "/v1/embeddings", {"model": model, "input": ["alpha"]})
+ return response, wire.drain()
+
+ first_warm: Final = attempt_alpha()
+ assert first_warm[0].status_code == 200, first_warm[0].text
+ assert len(first_warm[1]) == 1, "The unique embedding group unexpectedly hit the response cache"
+ assert _input_values(first_warm[1][0]) == ("alpha",)
+ warm_cache_hit: Final = eventually(attempt_alpha, lambda attempt: not attempt[1])
+ assert warm_cache_hit[0].status_code == 200, warm_cache_hit[0].text
+ warm_payload: Final = _EmbeddingResponse.model_validate_json(warm_cache_hit[0].content)
+ assert [item.model_dump() for item in warm_payload.data] == _expected_data(("alpha",)), warm_cache_hit[0].text
+ assert (warm_payload.usage.prompt_tokens, warm_payload.usage.total_tokens) == (
+ 1,
+ 1,
+ ), warm_cache_hit[0].text
+
+ partial: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": ["bravo", "alpha", "charlie"]},
+ )
+ partial_requests: Final = wire.drain()
+ assert partial.status_code == 200, partial.text
+ assert len(partial_requests) == 1, f"Expected one uncached provider call, received {len(partial_requests)}"
+ assert _input_values(partial_requests[0]) == ("bravo", "charlie")
+ partial_payload: Final = _EmbeddingResponse.model_validate_json(partial.content)
+ assert [item.model_dump() for item in partial_payload.data] == _expected_data(("bravo", "alpha", "charlie")), (
+ partial.text
+ )
+ assert (partial_payload.usage.prompt_tokens, partial_payload.usage.total_tokens) == (
+ 3,
+ 3,
+ ), partial.text
+
+ def attempt_partial() -> tuple[httpx.Response, tuple[Request, ...]]:
+ response: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": ["bravo", "alpha", "charlie"]},
+ )
+ return response, wire.drain()
+
+ full_cache_hit: Final = eventually(attempt_partial, lambda attempt: not attempt[1])
+ assert full_cache_hit[0].status_code == 200, full_cache_hit[0].text
+ final_payload: Final = _EmbeddingResponse.model_validate_json(full_cache_hit[0].content)
+ assert [item.model_dump() for item in final_payload.data] == _expected_data(("bravo", "alpha", "charlie")), (
+ full_cache_hit[0].text
+ )
+ assert (final_payload.usage.prompt_tokens, final_payload.usage.total_tokens) == (
+ 3,
+ 3,
+ ), full_cache_hit[0].text
+ assert [(request.method, request.target) for request in wire.drain()] == []
diff --git a/tests/integration/providers/test_embedding_token_array_wire.py b/tests/integration/providers/test_embedding_token_array_wire.py
new file mode 100644
index 00000000000..fe4ce0f1a86
--- /dev/null
+++ b/tests/integration/providers/test_embedding_token_array_wire.py
@@ -0,0 +1,350 @@
+import base64
+import json
+import struct
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from typing import Final, Literal
+from urllib.parse import parse_qs
+
+import pytest
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+_TOKEN_INPUT: Final = [[791, 4062, 14198, 2385], [40, 1093]]
+_FLAT_TOKEN_INPUT: Final = [791, 4062, 14198, 2385]
+_BEDROCK_TEXTS: Final = ["The quick brown base", "I like"]
+_VECTORS: Final = ((0.25, 0.5, 0.75), (-1.0, 0.125, 2.0))
+_AZURE_DEPLOYMENT: Final = "embed-azure-deployment"
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+
+
+class _Embedding(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ object: Literal["embedding"]
+ index: int
+ embedding: list[float]
+ type: str | None = None
+
+
+class _EmbeddingResponse(BaseModel):
+ data: tuple[_Embedding, ...]
+
+
+def _encoded(vector: tuple[float, ...]) -> str:
+ return base64.b64encode(struct.pack("<3f", *vector)).decode("ascii")
+
+
+def _openai_reply(count: int) -> bytes:
+ return json.dumps(
+ {
+ "object": "list",
+ "data": [
+ {"object": "embedding", "index": index, "embedding": list(vector)}
+ for index, vector in enumerate(_VECTORS[:count])
+ ],
+ "model": "text-embedding-3-small",
+ "usage": {"prompt_tokens": 4, "total_tokens": 4},
+ }
+ ).encode()
+
+
+def _azure_reply(count: int) -> bytes:
+ return json.dumps(
+ {
+ "object": "list",
+ "data": [
+ {"object": "embedding", "index": index, "embedding": _encoded(vector)}
+ for index, vector in enumerate(_VECTORS[:count])
+ ],
+ "model": _AZURE_DEPLOYMENT,
+ "usage": {"prompt_tokens": 4, "total_tokens": 4},
+ }
+ ).encode()
+
+
+def _bedrock_reply(texts: tuple[str, ...] = tuple(_BEDROCK_TEXTS)) -> bytes:
+ vectors: Final = _VECTORS[: len(texts)]
+ return json.dumps(
+ {
+ "embeddings": {"float": [list(vector) for vector in vectors]},
+ "id": "synthetic-cohere-embed",
+ "response_type": "embeddings_by_type",
+ "texts": list(texts),
+ }
+ ).encode()
+
+
+@dataclass(frozen=True, slots=True)
+class _TokenArrayCase:
+ model_params: Callable[[str], Mapping[str, JsonValue]]
+ target: str
+ query: Mapping[str, tuple[str, ...]]
+ auth_header: str
+ auth_value: str
+ body: Callable[[JsonValue], Mapping[str, JsonValue]]
+ reply: Callable[[int], bytes]
+ item_type: str | None
+ ignored_body_keys: frozenset[str] = frozenset()
+
+ @property
+ def path(self) -> str:
+ return self.target.partition("?")[0]
+
+
+_CASES: Final = (
+ _TokenArrayCase(
+ model_params=lambda url: {
+ "model": "openai/text-embedding-3-small",
+ "api_base": f"{url}/v1",
+ "api_key": "synthetic-openai-key",
+ },
+ target="/v1/embeddings",
+ query={},
+ auth_header="authorization",
+ auth_value="Bearer synthetic-openai-key",
+ body=lambda tokens: {"model": "text-embedding-3-small", "input": tokens},
+ reply=_openai_reply,
+ item_type=None,
+ ),
+ _TokenArrayCase(
+ model_params=lambda url: {
+ "model": f"azure/{_AZURE_DEPLOYMENT}",
+ "api_base": url,
+ "api_key": "synthetic-azure-key",
+ "api_version": "2024-06-01",
+ },
+ target=f"/openai/deployments/{_AZURE_DEPLOYMENT}/embeddings?api-version=2024-06-01",
+ query={"api-version": ("2024-06-01",)},
+ auth_header="api-key",
+ auth_value="synthetic-azure-key",
+ body=lambda tokens: {"input": tokens, "model": _AZURE_DEPLOYMENT},
+ reply=_azure_reply,
+ item_type=None,
+ ignored_body_keys=frozenset({"encoding_format"}),
+ ),
+ _TokenArrayCase(
+ model_params=lambda url: {
+ "model": "hosted_vllm/vllm-embed-model",
+ "api_base": f"{url}/v1",
+ "api_key": "synthetic-vllm-key",
+ },
+ target="/v1/embeddings",
+ query={},
+ auth_header="authorization",
+ auth_value="Bearer synthetic-vllm-key",
+ body=lambda tokens: {"model": "vllm-embed-model", "input": tokens},
+ reply=_openai_reply,
+ item_type=None,
+ ),
+ _TokenArrayCase(
+ model_params=lambda url: {
+ "model": "nebius/nebius-embed-model",
+ "api_base": f"{url}/v1",
+ "api_key": "synthetic-nebius-key",
+ },
+ target="/v1/embeddings",
+ query={},
+ auth_header="authorization",
+ auth_value="Bearer synthetic-nebius-key",
+ body=lambda tokens: {"model": "nebius-embed-model", "input": tokens},
+ reply=_openai_reply,
+ item_type=None,
+ ),
+ _TokenArrayCase(
+ model_params=lambda url: {
+ "model": "bedrock/cohere.embed-english-v3",
+ "api_base": url,
+ "api_key": "synthetic-bedrock-bearer",
+ "aws_region_name": "us-east-1",
+ },
+ target="/model/cohere.embed-english-v3/invoke",
+ query={},
+ auth_header="authorization",
+ auth_value="Bearer synthetic-bedrock-bearer",
+ body=lambda _tokens: {"texts": _BEDROCK_TEXTS, "input_type": "search_document"},
+ reply=lambda _count: _bedrock_reply(),
+ item_type="float",
+ ),
+)
+
+
+_CASE_IDS: Final = ("openai", "azure", "hosted_vllm", "nebius", "bedrock-cohere")
+_SHAPES: Final = (("nested", _TOKEN_INPUT, 2), ("flat", _FLAT_TOKEN_INPUT, 1))
+_PARAMS: Final = tuple(
+ pytest.param(case, tokens, count, id=f"{case_id}-{shape}")
+ for case, case_id in zip(_CASES, _CASE_IDS, strict=True)
+ for shape, tokens, count in _SHAPES[: 1 if case_id == "bedrock-cohere" else 2]
+)
+
+
[email protected](("case", "tokens", "count"), _PARAMS)
+def test_embedding_token_arrays_are_forwarded_or_decoded_for_provider(
+ gateway: Gateway,
+ case: _TokenArrayCase,
+ tokens: list[int] | list[list[int]],
+ count: int,
+) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ path, separator, query = request.target.partition("?")
+ assert path == case.path, request.target
+ assert {key: tuple(values) for key, values in parse_qs(query).items()} == dict(case.query), request.target
+ assert request.headers[case.auth_header] == case.auth_value, dict(request.headers)
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ sent_fields: Final = {key: value for key, value in body.items() if key not in case.ignored_body_keys}
+ assert sent_fields == case.body(tokens), request.body
+ return Reply(body=case.reply(count))
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(**case.model_params(wire.url))
+ response: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": tokens},
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ type_field: Final = {"type": case.item_type} if case.item_type is not None else {}
+ assert [item.model_dump(exclude_none=True) for item in payload.data] == [
+ {
+ "object": "embedding",
+ "index": index,
+ "embedding": list(vector),
+ **type_field,
+ }
+ for index, vector in enumerate(_VECTORS[:count])
+ ], response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", case.target)]
+
+
+def test_flat_token_array_is_decoded_for_bedrock(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: flat token-array input to a bedrock group is not decoded; cohere gets int texts and the proxy returns 500"
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/model/cohere.embed-english-v3/invoke"
+ assert request.headers["authorization"] == "Bearer synthetic-bedrock-bearer"
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "texts": ["The quick brown base"],
+ "input_type": "search_document",
+ }
+ return Reply(body=_bedrock_reply(("The quick brown base",)))
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="bedrock/cohere.embed-english-v3",
+ api_base=wire.url,
+ api_key="synthetic-bedrock-bearer",
+ aws_region_name="us-east-1",
+ )
+ response: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": _FLAT_TOKEN_INPUT},
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump(exclude_none=True) for item in payload.data] == [
+ {
+ "object": "embedding",
+ "index": 0,
+ "embedding": list(_VECTORS[0]),
+ "type": "float",
+ }
+ ], response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ ("POST", "/model/cohere.embed-english-v3/invoke")
+ ]
+
+
+def test_engines_path_token_arrays_are_decoded_for_bedrock(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: /engines/{model}/embeddings with token-array input and no body model skips decoding for bedrock; upstream gets the int lists in texts and the proxy returns 500"
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/model/cohere.embed-english-v3/invoke"
+ assert request.headers["authorization"] == "Bearer synthetic-bedrock-bearer"
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "texts": _BEDROCK_TEXTS,
+ "input_type": "search_document",
+ }
+ return Reply(body=_bedrock_reply())
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="bedrock/cohere.embed-english-v3",
+ api_base=wire.url,
+ api_key="synthetic-bedrock-bearer",
+ aws_region_name="us-east-1",
+ )
+ virtual_key: Final = scenario.key()
+ response: Final = gateway.request(
+ "POST",
+ f"/engines/{model}/embeddings",
+ {"input": _TOKEN_INPUT},
+ key=virtual_key,
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump(exclude_none=True) for item in payload.data] == [
+ {
+ "object": "embedding",
+ "index": index,
+ "embedding": list(vector),
+ "type": "float",
+ }
+ for index, vector in enumerate(_VECTORS)
+ ], response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ ("POST", "/model/cohere.embed-english-v3/invoke")
+ ]
+
+
+def test_deployments_path_token_arrays_are_decoded_for_bedrock(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: /openai/deployments/{model}/embeddings with token-array input and no body model skips decoding for bedrock; upstream gets the int lists in texts and the proxy returns 500"
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/model/cohere.embed-english-v3/invoke"
+ assert request.headers["authorization"] == "Bearer synthetic-bedrock-bearer"
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "texts": _BEDROCK_TEXTS,
+ "input_type": "search_document",
+ }
+ return Reply(body=_bedrock_reply())
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="bedrock/cohere.embed-english-v3",
+ api_base=wire.url,
+ api_key="synthetic-bedrock-bearer",
+ aws_region_name="us-east-1",
+ )
+ virtual_key: Final = scenario.key()
+ response: Final = gateway.client.post(
+ f"/openai/deployments/{model}/embeddings?api-version=2024-10-21",
+ json={"input": _TOKEN_INPUT},
+ headers={"api-key": virtual_key},
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump(exclude_none=True) for item in payload.data] == [
+ {
+ "object": "embedding",
+ "index": index,
+ "embedding": list(vector),
+ "type": "float",
+ }
+ for index, vector in enumerate(_VECTORS)
+ ], response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ ("POST", "/model/cohere.embed-english-v3/invoke")
+ ]
diff --git a/tests/integration/providers/test_openai_embedding_wire.py b/tests/integration/providers/test_openai_embedding_wire.py
new file mode 100644
index 00000000000..f818a8614dc
--- /dev/null
+++ b/tests/integration/providers/test_openai_embedding_wire.py
@@ -0,0 +1,175 @@
+import base64
+import json
+import struct
+from typing import Final, Literal
+
+import httpx
+import openai
+import pytest
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+_MODEL: Final = "openai/text-embedding-3-small"
+_SDK_KEY: Final = "synthetic-openai-key"
+_INPUTS: Final = ("embedding alpha marker", "embedding bravo marker")
+_RAW_INPUT: Final = "single raw embedding marker"
+_VECTORS: Final = ((0.25, 0.5, 0.75), (-1.0, 0.125, 2.0))
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+
+
+class _Embedding(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ object: Literal["embedding"]
+ index: int
+ embedding: list[float]
+
+
+class _Usage(BaseModel):
+ prompt_tokens: int
+ total_tokens: int
+
+
+class _EmbeddingResponse(BaseModel):
+ data: tuple[_Embedding, ...]
+ usage: _Usage
+
+
+def _encoded(vector: tuple[float, ...]) -> str:
+ return base64.b64encode(struct.pack("<3f", *vector)).decode("ascii")
+
+
+def _embedding_reply(embeddings: list[str | list[float]]) -> Reply:
+ return Reply(
+ body=json.dumps(
+ {
+ "object": "list",
+ "data": [
+ {"object": "embedding", "index": index, "embedding": embedding}
+ for index, embedding in enumerate(embeddings)
+ ],
+ "model": "text-embedding-3-small",
+ "usage": {"prompt_tokens": 4, "total_tokens": 4},
+ }
+ ).encode()
+ )
+
+
+# openai-python 2.33.0 defaults omitted encoding_format to base64: https://github.com/openai/openai-python/blob/v2.33.0/src/openai/resources/embeddings.py
+def test_openai_sdk_embedding_preserves_base64_and_decodes_vectors(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/v1/embeddings"
+ assert request.headers["authorization"] == f"Bearer {_SDK_KEY}"
+ assert request.headers["authorization"] != f"Bearer {virtual_key}"
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "model": "text-embedding-3-small",
+ "input": list(_INPUTS),
+ "encoding_format": "base64",
+ "dimensions": 3,
+ "user": "u1",
+ }
+ return _embedding_reply([_encoded(vector) for vector in _VECTORS])
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=_MODEL,
+ api_base=f"{wire.url}/v1",
+ api_key=_SDK_KEY,
+ )
+ virtual_key: Final = scenario.key()
+ with (
+ httpx.Client(trust_env=False) as http_client,
+ openai.OpenAI(
+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",
+ api_key=virtual_key,
+ max_retries=0,
+ http_client=http_client,
+ ) as client,
+ ):
+ response: Final = client.embeddings.create(
+ model=model,
+ input=list(_INPUTS),
+ dimensions=3,
+ user="u1",
+ )
+ assert [item.embedding for item in response.data] == [list(vector) for vector in _VECTORS], (
+ response.model_dump_json()
+ )
+ assert [item.index for item in response.data] == [0, 1], response.model_dump_json()
+ assert (response.usage.prompt_tokens, response.usage.total_tokens) == (4, 4), response.model_dump_json()
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/v1/embeddings")]
+
+
[email protected]("encoding_format", (None, "float"), ids=("omitted", "float"))
+def test_openai_embedding_forwards_omitted_or_float_encoding_format(
+ gateway: Gateway,
+ encoding_format: str | None,
+) -> None:
+ expected_body: Final = (
+ {"model": "text-embedding-3-small", "input": _RAW_INPUT}
+ if encoding_format is None
+ else {"model": "text-embedding-3-small", "input": _RAW_INPUT, "encoding_format": "float"}
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/v1/embeddings"
+ assert request.headers["authorization"] == f"Bearer {_SDK_KEY}"
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ if encoding_format is None and "encoding_format" in body:
+ return Reply(status=400, body=b'{"error":"encoding_format must be omitted"}')
+ assert body == expected_body, body
+ return _embedding_reply([[0.5, -0.25, 1.0]])
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=_MODEL,
+ api_base=f"{wire.url}/v1",
+ api_key=_SDK_KEY,
+ )
+ virtual_key: Final = scenario.key()
+ request_body: Final = (
+ {"model": model, "input": _RAW_INPUT}
+ if encoding_format is None
+ else {"model": model, "input": _RAW_INPUT, "encoding_format": encoding_format}
+ )
+ response: Final = gateway.request("POST", "/v1/embeddings", request_body, key=virtual_key)
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump() for item in payload.data] == [
+ {"object": "embedding", "index": 0, "embedding": [0.5, -0.25, 1.0]}
+ ], response.text
+ assert (payload.usage.prompt_tokens, payload.usage.total_tokens) == (4, 4), response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/v1/embeddings")]
+
+
+def test_openai_embedding_relays_requested_base64_string_unchanged(gateway: Gateway) -> None:
+ encoded: Final = _encoded(_VECTORS[0])
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/v1/embeddings"
+ assert request.headers["authorization"] == f"Bearer {_SDK_KEY}"
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ assert body == {"model": "text-embedding-3-small", "input": _RAW_INPUT, "encoding_format": "base64"}, body
+ return _embedding_reply([encoded])
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=_MODEL,
+ api_base=f"{wire.url}/v1",
+ api_key=_SDK_KEY,
+ )
+ virtual_key: Final = scenario.key()
+ response: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": _RAW_INPUT, "encoding_format": "base64"},
+ key=virtual_key,
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _JSON_OBJECT.validate_json(response.content)
+ assert payload["data"] == [{"object": "embedding", "index": 0, "embedding": encoded}], response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/v1/embeddings")]
diff --git a/tests/integration/providers/test_vertex_embedding_wire.py b/tests/integration/providers/test_vertex_embedding_wire.py
new file mode 100644
index 00000000000..d30b6e4e3ae
--- /dev/null
+++ b/tests/integration/providers/test_vertex_embedding_wire.py
@@ -0,0 +1,164 @@
+import json
+from typing import Final, Literal
+
+import pytest
+from integration._support.client import Gateway
+from integration._support.vertex import service_account_json
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+_PROJECT: Final = "scripted-embedding-project"
+_LOCATION: Final = "us-central1"
+_VERTEX_MODEL: Final = "text-embedding-005"
+_VERTEX_INPUTS: Final = ("vertex embedding alpha", "vertex embedding bravo")
+_GEMINI_INPUTS: Final = ("gemini embedding alpha", "gemini embedding bravo")
+_VECTOR_A: Final = (1.0,) + (0.0,) * 255
+_VECTOR_B: Final = (0.0, 1.0) + (0.0,) * 254
+_VECTORS: Final = (_VECTOR_A, _VECTOR_B)
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+
+
+class _Embedding(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ object: Literal["embedding"]
+ index: int
+ embedding: list[float]
+
+
+class _Usage(BaseModel):
+ prompt_tokens: int
+ total_tokens: int
+
+
+class _EmbeddingResponse(BaseModel):
+ data: tuple[_Embedding, ...]
+ usage: _Usage
+
+
+ ("embedding_input", "expected_inputs"),
+ ((list(_VERTEX_INPUTS), _VERTEX_INPUTS), (_VERTEX_INPUTS[0], (_VERTEX_INPUTS[0],))),
+ ids=("list", "string"),
+)
+def test_vertex_text_embedding_sends_dimensionality_and_preserves_input_order(
+ gateway: Gateway,
+ embedding_input: str | list[str],
+ expected_inputs: tuple[str, ...],
+) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == (
+ f"/v1/projects/{_PROJECT}/locations/{_LOCATION}/publishers/google/models/{_VERTEX_MODEL}:predict"
+ )
+ assert request.headers["authorization"] == "Bearer scripted-token"
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "instances": [{"content": text} for text in expected_inputs],
+ "parameters": {"outputDimensionality": 256},
+ }
+ return Reply(
+ body=json.dumps(
+ {
+ "predictions": [
+ {
+ "embeddings": {
+ "values": list(_VECTORS[index]),
+ "statistics": {"token_count": index + 2, "truncated": False},
+ }
+ }
+ for index, _ in enumerate(expected_inputs)
+ ]
+ }
+ ).encode()
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"vertex_ai/{_VERTEX_MODEL}",
+ api_base=wire.url,
+ api_key=None,
+ vertex_project=_PROJECT,
+ vertex_location=_LOCATION,
+ vertex_credentials=service_account_json(_PROJECT, gateway.upstream_url.rstrip("/")),
+ )
+ response: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": embedding_input, "dimensions": 256},
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump() for item in payload.data] == [
+ {"object": "embedding", "index": index, "embedding": list(_VECTORS[index])}
+ for index, _ in enumerate(expected_inputs)
+ ], response.text
+ expected_tokens: Final = sum(index + 2 for index in range(len(expected_inputs)))
+ assert (payload.usage.prompt_tokens, payload.usage.total_tokens) == (
+ expected_tokens,
+ expected_tokens,
+ ), response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ (
+ "POST",
+ f"/v1/projects/{_PROJECT}/locations/{_LOCATION}/publishers/google/models/{_VERTEX_MODEL}:predict",
+ )
+ ]
+
+
+ ("embedding_input", "expected_inputs"),
+ ((list(_GEMINI_INPUTS), _GEMINI_INPUTS), (_GEMINI_INPUTS[0], (_GEMINI_INPUTS[0],))),
+ ids=("list", "string"),
+)
+def test_gemini_embedding_sends_batch_contents_and_dimensionality(
+ gateway: Gateway,
+ embedding_input: str | list[str],
+ expected_inputs: tuple[str, ...],
+) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/models/gemini-embedding-001:batchEmbedContents"
+ assert request.headers["x-goog-api-key"] == "synthetic-gemini-key"
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "requests": [
+ {
+ "model": "models/gemini-embedding-001",
+ "content": {"parts": [{"text": text}]},
+ "outputDimensionality": 256,
+ }
+ for text in expected_inputs
+ ]
+ }
+ return Reply(
+ body=json.dumps(
+ {
+ "embeddings": [
+ {"values": list(_VECTORS[index]), "statistics": {"token_count": index + 2}}
+ for index, _ in enumerate(expected_inputs)
+ ]
+ }
+ ).encode()
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="gemini/gemini-embedding-001",
+ api_base=wire.url,
+ api_key="synthetic-gemini-key",
+ )
+ response: Final = gateway.request(
+ "POST",
+ "/v1/embeddings",
+ {"model": model, "input": embedding_input, "dimensions": 256},
+ )
+ assert response.status_code == 200, response.text
+ payload: Final = _EmbeddingResponse.model_validate_json(response.content)
+ assert [item.model_dump() for item in payload.data] == [
+ {"object": "embedding", "index": index, "embedding": list(_VECTORS[index])}
+ for index, _ in enumerate(expected_inputs)
+ ], response.text
+ assert payload.usage.prompt_tokens == payload.usage.total_tokens, response.text
+ assert payload.usage.prompt_tokens > 0, response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ ("POST", "/models/gemini-embedding-001:batchEmbedContents")
+ ]