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 small_inference endpoint contracts (#44654)

devin-ai-integration[bot]c9a1d9b0268a
diff --git a/tests/integration/authorization/test_search_tool_allowlist.py b/tests/integration/authorization/test_search_tool_allowlist.py
new file mode 100644
index 00000000000..3715669a892
--- /dev/null
+++ b/tests/integration/authorization/test_search_tool_allowlist.py
@@ -0,0 +1,238 @@
+import json
+import uuid
+from collections.abc import Callable
+from typing import Final
+
+import pytest
+from integration._support.client import Gateway, Scenario, string_value
+from integration._support.database import read_rows
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import JsonValue
+
+_EXA_KEY: Final = "synthetic-exa-allowlist-key"
+_SEARCH_BODY: Final = {"query": "allowlisted search tools only"}
+_EXA_BODY: Final = {"query": "allowlisted search tools only", "contents": {"text": True}}
+
+
+def _exa_peer(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", "/allowed/search"), request.target
+ assert request.headers["x-api-key"] == _EXA_KEY, request.headers
+ assert json.loads(request.body) == _EXA_BODY, request.body
+ return Reply(body=json.dumps({"results": []}).encode())
+
+
+def _create_tool(gateway: Gateway, scenario: Scenario, name: str, api_base: str) -> str:
+ created: Final = gateway.post(
+ "/search_tools",
+ {
+ "search_tool": {
+ "search_tool_name": name,
+ "litellm_params": {"search_provider": "exa_ai", "api_key": _EXA_KEY, "api_base": api_base},
+ "search_tool_info": {"description": f"integration tool {name}"},
+ }
+ },
+ )
+ identity: Final = string_value(created["search_tool_id"])
+ scenario.cleanups.callback(gateway.request, "DELETE", f"/search_tools/{identity}")
+ return identity
+
+
+def _key_scoped_to(scenario: Scenario, allowed: str) -> str:
+ user: Final = scenario.user(user_role="internal_user")
+ return scenario.key(user_id=user, object_permission={"search_tools": [allowed]})
+
+
+def _team_key_scoped_to(scenario: Scenario, allowed: str) -> str:
+ team: Final = scenario.team(object_permission={"search_tools": [allowed]})
+ return scenario.key(team_id=team, user_id=scenario.member(team))
+
+
+def _listed_names(gateway: Gateway, key: str, path: str, field: str) -> list[str]:
+ response: Final = gateway.request("GET", path, key=key)
+ assert response.status_code == 200, response.text
+ entries: Final = response.json()[field]
+ return sorted(entry["search_tool_name"] for entry in entries)
+
+
+def _two_tools(gateway: Gateway, scenario: Scenario, wire: Wire) -> tuple[str, str]:
+ allowed: Final = f"tool-a-{uuid.uuid4().hex}"
+ denied: Final = f"tool-b-{uuid.uuid4().hex}"
+ _create_tool(gateway, scenario, allowed, f"{wire.url}/allowed")
+ _create_tool(gateway, scenario, denied, f"{wire.url}/denied")
+ return allowed, denied
+
+
+def _refusal(scope: str, denied: str, allowed: str) -> dict[str, dict[str, str]]:
+ return {
+ "error": {
+ "message": f"{scope} not allowed to access search tool: {denied}. Allowed search tools: ['{allowed}']",
+ "type": "key_model_access_denied",
+ "param": "search_tool_name",
+ "code": "403",
+ }
+ }
+
+
+ ("scope", "make_key"),
+ [pytest.param("Key", _key_scoped_to, id="key"), pytest.param("Team", _team_key_scoped_to, id="team")],
+)
+def test_search_tool_allowlist_refuses_other_tools_before_any_upstream_call(
+ gateway: Gateway, scope: str, make_key: Callable[[Scenario, str], str]
+) -> None:
+ with wire_server(_exa_peer) as wire, gateway.scenario() as scenario:
+ allowed, denied = _two_tools(gateway, scenario, wire)
+ key: Final = make_key(scenario, allowed)
+ refusal: Final = _refusal(scope, denied, allowed)
+ for path, body in (
+ (f"/v1/search/{denied}", _SEARCH_BODY),
+ ("/v1/search", {"search_tool_name": denied, **_SEARCH_BODY}),
+ ):
+ refused = gateway.request("POST", path, body, key=key)
+ assert (refused.status_code, refused.json()) == (403, refusal), refused.text
+ assert wire.drain() == ()
+ served: Final = gateway.request("POST", f"/v1/search/{allowed}", _SEARCH_BODY, key=key)
+ assert (served.status_code, served.json()) == (200, {"object": "search", "results": []}), served.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/allowed/search")]
+
+
+_SCOPES: Final = (
+ pytest.param("Key", _key_scoped_to, id="key"),
+ pytest.param("Team", _team_key_scoped_to, id="team"),
+)
+
+
[email protected](("scope", "make_key"), _SCOPES)
+def test_search_tool_allowlist_refuses_the_model_spelling_before_any_upstream_call(
+ gateway: Gateway, scope: str, make_key: Callable[[Scenario, str], str]
+) -> None:
+ pytest.skip("BUG: POST /v1/search with model=<tool> bypasses the key and team search_tools allowlist")
+ with wire_server(_exa_peer) as wire, gateway.scenario() as scenario:
+ allowed, denied = _two_tools(gateway, scenario, wire)
+ key: Final = make_key(scenario, allowed)
+ refused: Final = gateway.request("POST", "/v1/search", {"model": denied, **_SEARCH_BODY}, key=key)
+ assert (refused.status_code, refused.json()) == (403, _refusal(scope, denied, allowed)), refused.text
+ assert wire.drain() == ()
+
+
[email protected](("scope", "make_key"), _SCOPES)
+def test_search_tools_list_shows_a_scoped_key_only_its_allowlisted_tools(
+ gateway: Gateway, scope: str, make_key: Callable[[Scenario, str], str]
+) -> None:
+ with wire_server(_exa_peer) as wire, gateway.scenario() as scenario:
+ allowed, denied = _two_tools(gateway, scenario, wire)
+ key: Final = make_key(scenario, allowed)
+ listed: Final = gateway.request("GET", "/search_tools/list", key=key)
+ assert listed.status_code == 200, listed.text
+ names: Final = sorted(entry["search_tool_name"] for entry in listed.json()["search_tools"])
+ assert names == [allowed], f"{scope} scoped to {allowed} listed {names}, {denied} must be hidden: {listed.text}"
+ assert wire.drain() == ()
+
+
+def test_search_tools_listing_route_hides_tools_outside_the_key_allowlist(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: GET /v1/search/tools lists every router search tool to a key whose search_tools allowlist excludes them"
+ )
+ with wire_server(_exa_peer) as wire, gateway.scenario() as scenario:
+ allowed, denied = _two_tools(gateway, scenario, wire)
+ key: Final = _key_scoped_to(scenario, allowed)
+ for path in ("/v1/search/tools", "/search/tools"):
+ assert _listed_names(gateway, key, path, "data") == [allowed]
+ assert wire.drain() == ()
+
+
+def _search_tool_row(identity: str) -> list[dict[str, JsonValue]]:
+ return read_rows(
+ 'SELECT search_tool_name, litellm_params, search_tool_info, updated_at::text AS updated_at FROM "LiteLLM_SearchToolsTable" '
+ "WHERE search_tool_id = %s",
+ (identity,),
+ )
+
+
+def _non_admin_attempts(
+ existing: str, existing_name: str, attempted_name: str, api_base: str
+) -> tuple[tuple[str, str, dict[str, JsonValue] | None], ...]:
+ attacker_params: Final = {"search_provider": "exa_ai", "api_key": "attacker", "api_base": api_base}
+ return (
+ (
+ "POST",
+ "/search_tools",
+ {"search_tool": {"search_tool_name": attempted_name, "litellm_params": attacker_params}},
+ ),
+ (
+ "PUT",
+ f"/search_tools/{existing}",
+ {"search_tool": {"search_tool_name": existing_name, "litellm_params": attacker_params}},
+ ),
+ ("DELETE", f"/search_tools/{existing}", None),
+ ("POST", "/search_tools/test_connection", {"litellm_params": attacker_params}),
+ )
+
+
+def _delete_tools_named(gateway: Gateway, name: str) -> None:
+ for row in read_rows('SELECT search_tool_id FROM "LiteLLM_SearchToolsTable" WHERE search_tool_name = %s', (name,)):
+ gateway.request("DELETE", f"/search_tools/{string_value(row['search_tool_id'])}")
+
+
+def _refuse_all(request: Request) -> Reply:
+ raise AssertionError(f"non-admin search tool management reached the provider: {request.target}")
+
+
[email protected]("role", ["internal_user", "internal_user_viewer"])
+def test_non_admin_keys_cannot_create_update_delete_or_probe_search_tools(gateway: Gateway, role: str) -> None:
+ with wire_server(_refuse_all) as wire, gateway.scenario() as scenario:
+ existing_name: Final = f"admin-owned-{uuid.uuid4().hex}"
+ existing: Final = _create_tool(gateway, scenario, existing_name, f"{wire.url}/admin")
+ before: Final = _search_tool_row(existing)
+ key: Final = scenario.key(user_id=scenario.user(user_role=role))
+ attempted_name: Final = f"non-admin-{uuid.uuid4().hex}"
+ scenario.cleanups.callback(_delete_tools_named, gateway, attempted_name)
+ for method, path, body in _non_admin_attempts(existing, existing_name, attempted_name, f"{wire.url}/attacker"):
+ response = gateway.request(method, path, body, key=key)
+ error = response.json().get("error", {}) if response.status_code in (401, 403) else {}
+ refusal = (error.get("type"), f"Route={path}. Your role={role}." in str(error.get("message")))
+ assert refusal == ("auth_error", True), f"{method} {path}: {response.status_code} {response.text}"
+ assert _search_tool_row(existing) == before
+ assert (
+ read_rows(
+ 'SELECT search_tool_id FROM "LiteLLM_SearchToolsTable" WHERE search_tool_name = %s', (attempted_name,)
+ )
+ == []
+ )
+ assert wire.drain() == ()
+
+
+def test_internal_user_keeps_listing_search_tools(gateway: Gateway) -> None:
+ with wire_server(_refuse_all) as wire, gateway.scenario() as scenario:
+ name: Final = f"admin-owned-{uuid.uuid4().hex}"
+ _create_tool(gateway, scenario, name, f"{wire.url}/admin")
+ key: Final = scenario.key(user_id=scenario.user(user_role="internal_user"))
+ assert name in _listed_names(gateway, key, "/search_tools/list", "search_tools")
+ assert wire.drain() == ()
+
+
[email protected]("role", ["internal_user", "internal_user_viewer"])
+def test_non_admin_search_tool_writes_are_forbidden_with_403(gateway: Gateway, role: str) -> None:
+ pytest.skip("BUG: non-admin POST/PUT/DELETE /search_tools and test_connection return 401 auth_error instead of 403")
+ with wire_server(_refuse_all) as wire, gateway.scenario() as scenario:
+ existing_name: Final = f"admin-owned-{uuid.uuid4().hex}"
+ existing: Final = _create_tool(gateway, scenario, existing_name, f"{wire.url}/admin")
+ key: Final = scenario.key(user_id=scenario.user(user_role=role))
+ attempted_name: Final = f"non-admin-{uuid.uuid4().hex}"
+ scenario.cleanups.callback(_delete_tools_named, gateway, attempted_name)
+ for method, path, body in _non_admin_attempts(existing, existing_name, attempted_name, f"{wire.url}/attacker"):
+ response = gateway.request(method, path, body, key=key)
+ assert (response.status_code, response.json()["error"]["code"]) == (403, "403"), (
+ f"{method} {path}: {response.text}"
+ )
+ assert wire.drain() == ()
+
+
+def test_internal_user_viewer_can_list_search_tools(gateway: Gateway) -> None:
+ pytest.skip("BUG: GET /search_tools/list returns 401 to an internal_user_viewer key")
+ with wire_server(_refuse_all) as wire, gateway.scenario() as scenario:
+ name: Final = f"admin-owned-{uuid.uuid4().hex}"
+ _create_tool(gateway, scenario, name, f"{wire.url}/admin")
+ key: Final = scenario.key(user_id=scenario.user(user_role="internal_user_viewer"))
+ assert name in _listed_names(gateway, key, "/search_tools/list", "search_tools")
+ assert wire.drain() == ()
diff --git a/tests/integration/management/test_search_tool_crud.py b/tests/integration/management/test_search_tool_crud.py
new file mode 100644
index 00000000000..d7f161431c6
--- /dev/null
+++ b/tests/integration/management/test_search_tool_crud.py
@@ -0,0 +1,143 @@
+import json
+import uuid
+from pathlib import Path
+from types import MappingProxyType
+from typing import Final
+
+import yaml
+from integration._support.client import Gateway, string_value
+from integration._support.database import read_rows
+from integration._support.process import owned_proxy
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue
+
+_PROXY_CONFIG: Final = Path(__file__).resolve().parents[1] / "proxy_config.yaml"
+_ORIGINAL_KEY: Final = "exa-original-provider-key"
+_ROTATED_KEY: Final = "exa-rotated-provider-key"
+_TOOL_INFO: Final = {"description": "integration search tool crud"}
+_QUERY: Final = "search tool crud query"
+_KEY_BY_TARGET: Final = MappingProxyType({"/original/search": _ORIGINAL_KEY, "/rotated/search": _ROTATED_KEY})
+
+
+def _config_without_periodic_reload(directory: Path) -> Path:
+ base: Final = yaml.safe_load(_PROXY_CONFIG.read_text())
+ config: Final = {
+ **base,
+ "general_settings": {**base["general_settings"], "proxy_config_reload_interval_seconds": 3600},
+ }
+ path: Final = directory / "search-tool-crud.yaml"
+ path.write_text(yaml.safe_dump(config))
+ return path
+
+
+def _stored_row(identity: str) -> dict[str, JsonValue]:
+ rows: Final = read_rows(
+ 'SELECT search_tool_name, litellm_params, search_tool_info FROM "LiteLLM_SearchToolsTable" '
+ "WHERE search_tool_id = %s",
+ (identity,),
+ )
+ assert len(rows) == 1, rows
+ return rows[0]
+
+
+def _assert_stored_encrypted(identity: str, name: str, plaintext: dict[str, str]) -> None:
+ row: Final = _stored_row(identity)
+ assert (row["search_tool_name"], row["search_tool_info"]) == (name, _TOOL_INFO), row
+ stored: Final = row["litellm_params"]
+ assert isinstance(stored, dict) and sorted(stored) == sorted(plaintext), row
+ leaked: Final = {key: value for key, value in plaintext.items() if stored[key] == value or value in json.dumps(row)}
+ assert leaked == {}, f"search tool litellm_params stored in plaintext: {sorted(leaked)}"
+
+
+def _masked(key: str) -> str:
+ return f"{key[:2]}****{key[-2:]}"
+
+
+def test_search_tool_create_update_delete_is_read_back_and_applied_without_restart(
+ gateway: Gateway, tmp_path: Path
+) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target in _KEY_BY_TARGET, request.target
+ target: Final = request.target
+ key: Final = _KEY_BY_TARGET[target]
+ assert request.headers["x-api-key"] == key, request.headers
+ assert json.loads(request.body) == {"query": _QUERY, "contents": {"text": True}}, request.body
+ return Reply(
+ body=json.dumps({"results": [{"title": target, "url": "https://crud.invalid", "text": key}]}).encode()
+ )
+
+ name: Final = f"crud-tool-{uuid.uuid4().hex}"
+ with (
+ wire_server(respond) as wire,
+ owned_proxy(gateway, tmp_path, {}, config=_config_without_periodic_reload(tmp_path)) as candidate,
+ candidate.scenario() as scenario,
+ ):
+ original: Final = {"search_provider": "exa_ai", "api_key": _ORIGINAL_KEY, "api_base": f"{wire.url}/original"}
+ created: Final = candidate.post(
+ "/search_tools",
+ {"search_tool": {"search_tool_name": name, "litellm_params": original, "search_tool_info": _TOOL_INFO}},
+ )
+ identity: Final = string_value(created["search_tool_id"])
+ scenario.cleanups.callback(candidate.request, "DELETE", f"/search_tools/{identity}")
+ _assert_stored_encrypted(identity, name, original)
+
+ def read_back(params: dict[str, str]) -> None:
+ expected: Final = {
+ "search_tool_id": identity,
+ "search_tool_name": name,
+ "litellm_params": {**params, "api_key": _masked(params["api_key"])},
+ "search_tool_info": _TOOL_INFO,
+ "is_from_config": False,
+ }
+ response: Final = candidate.request("GET", f"/search_tools/{identity}")
+ assert response.status_code == 200, response.text
+ single: Final = {
+ field: value for field, value in response.json().items() if field not in ("created_at", "updated_at")
+ }
+ assert single == expected, response.text
+ listed: Final = [
+ {field: value for field, value in tool.items() if field not in ("created_at", "updated_at")}
+ for tool in candidate.get("/search_tools/list")["search_tools"]
+ if isinstance(tool, dict) and tool["search_tool_id"] == identity
+ ]
+ assert listed == [expected], listed
+
+ def search_reaches(target: str, key: str) -> None:
+ response: Final = candidate.request("POST", f"/v1/search/{name}", {"query": _QUERY})
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "object": "search",
+ "results": [
+ {"title": target, "url": "https://crud.invalid", "snippet": key, "date": None, "last_updated": None}
+ ],
+ }, response.text
+
+ read_back(original)
+ search_reaches("/original/search", _ORIGINAL_KEY)
+
+ rotated: Final = {"search_provider": "exa_ai", "api_key": _ROTATED_KEY, "api_base": f"{wire.url}/rotated"}
+ updated: Final = candidate.request(
+ "PUT",
+ f"/search_tools/{identity}",
+ {"search_tool": {"search_tool_name": name, "litellm_params": rotated, "search_tool_info": _TOOL_INFO}},
+ )
+ assert updated.status_code == 200, updated.text
+ _assert_stored_encrypted(identity, name, rotated)
+ read_back(rotated)
+ search_reaches("/rotated/search", _ROTATED_KEY)
+
+ deleted: Final = candidate.request("DELETE", f"/search_tools/{identity}")
+ assert deleted.status_code == 200, deleted.text
+ assert (
+ read_rows('SELECT search_tool_id FROM "LiteLLM_SearchToolsTable" WHERE search_tool_id = %s', (identity,))
+ == []
+ )
+ missing: Final = candidate.request("GET", f"/search_tools/{identity}")
+ assert missing.status_code == 404, missing.text
+ refused: Final = candidate.request("POST", f"/v1/search/{name}", {"query": _QUERY})
+ refusal: Final = (refused.status_code >= 400, refused.json().get("error", {}).get("message"))
+ assert refusal == (True, f"Search tool '{name}' not found in router.search_tools"), refused.text
+ assert [(request.method, request.target) for request in wire.drain()] == [
+ ("POST", "/original/search"),
+ ("POST", "/rotated/search"),
+ ]
diff --git a/tests/integration/providers/test_moderations_wire.py b/tests/integration/providers/test_moderations_wire.py
new file mode 100644
index 00000000000..1e0b62b4d0e
--- /dev/null
+++ b/tests/integration/providers/test_moderations_wire.py
@@ -0,0 +1,132 @@
+import json
+from collections.abc import Callable
+from pathlib import Path
+from typing import Final
+
+import openai
+import yaml
+from integration._support.client import Gateway
+from integration._support.process import owned_proxy
+from integration._support.wire import Reply, Request, Wire, wire_server
+from openai.types import Moderation
+from pydantic import BaseModel
+
+_OPENAI_KEY: Final = "synthetic-openai-moderation-key"
+_UPSTREAM_MODEL: Final = "omni-moderation-latest"
+_PROXY_CONFIG: Final = Path(__file__).resolve().parents[1] / "proxy_config.yaml"
+_CATEGORIES: Final = (
+ "harassment",
+ "harassment/threatening",
+ "hate",
+ "hate/threatening",
+ "illicit",
+ "illicit/violent",
+ "self-harm",
+ "self-harm/instructions",
+ "self-harm/intent",
+ "sexual",
+ "sexual/minors",
+ "violence",
+ "violence/graphic",
+)
+_RESULT: Final = {
+ "flagged": True,
+ "categories": {category: category == "violence" for category in _CATEGORIES},
+ "category_scores": {category: 0.93 if category == "violence" else 0.01 for category in _CATEGORIES},
+ "category_applied_input_types": {
+ category: ["text", "image"] if category == "violence" else ["text"] for category in _CATEGORIES
+ },
+}
+_INPUTS: Final = (
+ "a single moderation string",
+ ["first moderation string", "second moderation string"],
+ [
+ {"type": "text", "text": "describe this picture"},
+ {"type": "image_url", "image_url": {"url": "https://image.invalid/picture.png"}},
+ ],
+)
+
+
+def _openai_peer() -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ if (request.method, request.target) == ("GET", "/v1/models"):
+ return Reply(
+ body=json.dumps({"object": "list", "data": [{"id": _UPSTREAM_MODEL, "object": "model"}]}).encode()
+ )
+ assert (request.method, request.target) == ("POST", "/v1/moderations"), request.target
+ assert request.headers["authorization"] == f"Bearer {_OPENAI_KEY}", request.headers
+ return Reply(
+ body=json.dumps({"id": "modr-integration", "model": _UPSTREAM_MODEL, "results": [_RESULT]}).encode()
+ )
+
+ return respond
+
+
+def _spec_view(result: Moderation) -> dict[str, object]:
+ def by_alias(section: BaseModel) -> dict[str, object]:
+ return {field.alias or name: getattr(section, name) for name, field in type(section).model_fields.items()}
+
+ return {
+ "flagged": result.flagged,
+ "categories": by_alias(result.categories),
+ "category_scores": by_alias(result.category_scores),
+ "category_applied_input_types": by_alias(result.category_applied_input_types),
+ }
+
+
+def _moderation_bodies(wire: Wire) -> list[object]:
+ received: Final = wire.drain()
+ calls: Final = [(request.method, request.target) for request in received]
+ assert set(calls) <= {("GET", "/v1/models"), ("POST", "/v1/moderations")}, calls
+ return [json.loads(request.body) for request in received if request.method == "POST"]
+
+
+def _sdk(gateway: Gateway) -> openai.OpenAI:
+ return openai.OpenAI(base_url=str(gateway.client.base_url) + "/v1", api_key=gateway.key, max_retries=0)
+
+
+def test_openai_sdk_moderation_inputs_reach_upstream_as_exact_model_and_input(gateway: Gateway) -> None:
+ with wire_server(_openai_peer()) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(model=f"openai/{_UPSTREAM_MODEL}", api_base=f"{wire.url}/v1", api_key=_OPENAI_KEY)
+ client: Final = _sdk(gateway)
+ for moderation_input in _INPUTS:
+ response = client.moderations.create(model=model, input=moderation_input)
+ assert [_spec_view(result) for result in response.results] == [_RESULT], response
+ alias: Final = gateway.request("POST", "/moderations", {"model": model, "input": _INPUTS[0]})
+ assert alias.status_code == 200, alias.text
+ assert [_spec_view(Moderation.model_validate(result)) for result in alias.json()["results"]] == [_RESULT], (
+ alias.text
+ )
+ assert _moderation_bodies(wire) == [
+ {"model": _UPSTREAM_MODEL, "input": moderation_input} for moderation_input in (*_INPUTS, _INPUTS[0])
+ ]
+
+
+def test_model_less_moderation_resolves_to_configured_moderation_model(gateway: Gateway, tmp_path: Path) -> None:
+ with wire_server(_openai_peer()) as wire:
+ base: Final = yaml.safe_load(_PROXY_CONFIG.read_text())
+ config: Final = {
+ **base,
+ "model_list": [
+ {
+ "model_name": "default-moderation",
+ "litellm_params": {
+ "model": f"openai/{_UPSTREAM_MODEL}",
+ "api_base": f"{wire.url}/v1",
+ "api_key": _OPENAI_KEY,
+ },
+ }
+ ],
+ "general_settings": {**base["general_settings"], "moderation_model": "default-moderation"},
+ }
+ path: Final = tmp_path / "moderation-default.yaml"
+ path.write_text(yaml.safe_dump(config))
+ with owned_proxy(gateway, tmp_path, {}, config=path) as candidate:
+ for moderation_input in (_INPUTS[0], _INPUTS[2]):
+ response = candidate.request("POST", "/v1/moderations", {"input": moderation_input})
+ assert response.status_code == 200, response.text
+ results = [_spec_view(Moderation.model_validate(result)) for result in response.json()["results"]]
+ assert results == [_RESULT], response.text
+ assert _moderation_bodies(wire) == [
+ {"model": _UPSTREAM_MODEL, "input": moderation_input} for moderation_input in (_INPUTS[0], _INPUTS[2])
+ ]
diff --git a/tests/integration/providers/test_ocr_multipart_wire.py b/tests/integration/providers/test_ocr_multipart_wire.py
new file mode 100644
index 00000000000..494db25c62b
--- /dev/null
+++ b/tests/integration/providers/test_ocr_multipart_wire.py
@@ -0,0 +1,138 @@
+import base64
+import json
+from typing import Final
+
+import pytest
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel
+
+_PDF_BYTES: Final = b"%PDF-1.4\n%integration\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n"
+_PNG_BYTES: Final = (
+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00"
+ b"\x1f\x15\xc4\x89\x00\x00\x00\rIDAT\x08\xd7c\xf8\xcf\xc0\xf0\x1f\x00\x05\x00\x01\xff"
+ b"\x89\x99=\x1d\x00\x00\x00\x00IEND\xaeB`\x82"
+)
+_MISTRAL_KEY: Final = "synthetic-mistral-key"
+_MISTRAL_PAGES: Final = (
+ {"index": 0, "markdown": "# page zero", "images": [], "dimensions": {"dpi": 200, "height": 1100, "width": 850}},
+ {"index": 1, "markdown": "page one", "images": [], "dimensions": {"dpi": 200, "height": 1100, "width": 850}},
+)
+
+
+class _Dimensions(BaseModel):
+ dpi: int
+ height: int
+ width: int
+
+
+class _Page(BaseModel):
+ index: int
+ markdown: str
+ images: tuple[object, ...]
+ dimensions: _Dimensions
+
+
+class _OCRResponse(BaseModel):
+ object: str
+ pages: tuple[_Page, ...]
+
+
+def _data_url(media_type: str, content: bytes) -> str:
+ return f"data:{media_type};base64,{base64.b64encode(content).decode()}"
+
+
+def _expected_body(
+ upstream_model: str, document: dict[str, str], include_image_base64: bool = True
+) -> dict[str, object]:
+ return {"model": upstream_model, "document": document, "pages": [0, 1], "include_image_base64": include_image_base64}
+
+
+def _mistral_reply(request: Request) -> Reply:
+ return Reply(
+ body=json.dumps(
+ {
+ "pages": list(_MISTRAL_PAGES),
+ "model": "mistral-ocr-latest",
+ "usage_info": {"pages_processed": 2, "doc_size_bytes": len(request.body)},
+ "document_annotation": None,
+ }
+ ).encode()
+ )
+
+
+def _expected_bodies(upstream_model: str) -> tuple[dict[str, object], ...]:
+ pdf: Final = _expected_body(
+ upstream_model, {"type": "document_url", "document_url": _data_url("application/pdf", _PDF_BYTES)}
+ )
+ png: Final = _expected_body(upstream_model, {"type": "image_url", "image_url": _data_url("image/png", _PNG_BYTES)})
+ return (pdf, png, pdf, pdf, pdf, png)
+
+
+def test_multipart_uploads_reach_mistral_as_data_urls_typed_by_the_client_content_type(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", "/v1/ocr"), request.target
+ assert request.headers["authorization"] == f"Bearer {_MISTRAL_KEY}", request.headers
+ assert request.headers["content-type"] == "application/json", request.headers
+ body: Final = json.loads(request.body)
+ assert body in _expected_bodies("mistral-ocr-latest"), body
+ return _mistral_reply(request)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="mistral/mistral-ocr-latest",
+ api_base=f"{wire.url}/v1",
+ api_key=_MISTRAL_KEY,
+ model_info={"mode": "ocr"},
+ )
+ fields: Final = {"model": model, "pages": "[0,1]", "include_image_base64": "true"}
+ uploads: Final = (
+ ("doc.pdf", _PDF_BYTES, "application/pdf"),
+ ("scan.png", _PNG_BYTES, "image/png"),
+ ("blob", _PDF_BYTES, "application/pdf"),
+ ("upload.bin", _PDF_BYTES, "application/pdf"),
+ ("doc.pdf", _PDF_BYTES, "application/octet-stream"),
+ ("scan.png", _PNG_BYTES, "application/octet-stream"),
+ )
+ for path, upload in ((path, upload) for path in ("/v1/ocr", "/ocr") for upload in uploads):
+ response = gateway.request_multipart(path, fields, {"file": upload})
+ assert response.status_code == 200, f"{path}: {response.text}"
+ payload = _OCRResponse.model_validate_json(response.content)
+ assert payload == _OCRResponse(object="ocr", pages=tuple(_Page(**page) for page in _MISTRAL_PAGES)), (
+ response.text
+ )
+ received: Final = wire.drain()
+ assert [(request.method, request.target) for request in received] == [("POST", "/v1/ocr")] * (2 * len(uploads))
+ assert tuple(json.loads(request.body) for request in received) == _expected_bodies("mistral-ocr-latest") * 2
+
+
+def test_python_requests_boolean_spelling_reaches_mistral_as_a_boolean(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: multipart include_image_base64='True' or 'False' (Python requests' str(bool)) reaches Mistral "
+ "as the string 'True' or 'False' instead of a JSON boolean"
+ )
+
+ def respond(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", "/v1/ocr"), request.target
+ return _mistral_reply(request)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="mistral/mistral-ocr-latest",
+ api_base=f"{wire.url}/v1",
+ api_key=_MISTRAL_KEY,
+ model_info={"mode": "ocr"},
+ )
+ for spelling in ("True", "False"):
+ response = gateway.request_multipart(
+ "/v1/ocr",
+ {"model": model, "pages": "[0,1]", "include_image_base64": spelling},
+ {"file": ("doc.pdf", _PDF_BYTES, "application/pdf")},
+ )
+ assert response.status_code == 200, f"{spelling}: {response.text}"
+ received: Final = wire.drain()
+ pdf: Final = {"type": "document_url", "document_url": _data_url("application/pdf", _PDF_BYTES)}
+ assert tuple(json.loads(request.body) for request in received) == (
+ _expected_body("mistral-ocr-latest", pdf, include_image_base64=True),
+ _expected_body("mistral-ocr-latest", pdf, include_image_base64=False),
+ ), [request.body for request in received]
diff --git a/tests/integration/providers/test_rerank_latency_headers_wire.py b/tests/integration/providers/test_rerank_latency_headers_wire.py
index 62624e0480a..d391fadfe0b 100644
--- a/tests/integration/providers/test_rerank_latency_headers_wire.py
+++ b/tests/integration/providers/test_rerank_latency_headers_wire.py
@@ -1,10 +1,12 @@
import json
import uuid
+from collections.abc import Callable
from typing import Final
import pytest
from integration._support.client import Gateway
from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel
MODEL: Final = "cohere/synthetic-rerank-model-without-pricing"
QUERY: Final = "which document mentions the gateway"
@@ -48,3 +50,101 @@ def test_rerank_response_carries_call_id_latency_and_cost_headers_like_chat_comp
assert float(response.headers["x-litellm-response-cost"]) == 0.0, response.headers
assert float(response.headers["x-litellm-response-duration-ms"]) > 0, response.headers
assert float(response.headers["x-litellm-overhead-duration-ms"]) >= 0, response.headers
+
+
+COHERE_KEY: Final = "synthetic-cohere-key"
+COHERE_V2_BODY: Final = {"model": "rerank-v3.5", "query": QUERY, "top_n": 1, "documents": list(DOCUMENTS)}
+COHERE_V1_BODY: Final = {**COHERE_V2_BODY, "return_documents": False, "max_chunks_per_doc": 3}
+COHERE_V2_SDK_BODY: Final = {**COHERE_V2_BODY, "max_tokens_per_doc": 512}
+
+
+class _RerankResult(BaseModel):
+ index: int
+ relevance_score: float
+
+
+class _RerankResponse(BaseModel):
+ results: tuple[_RerankResult, ...]
+
+
+def _cohere_peer(expected: dict[str, object], route: str) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", route), request.target
+ assert request.headers["authorization"] == f"Bearer {COHERE_KEY}", request.headers
+ assert json.loads(request.body) == expected, request.body
+ return Reply(body=RESPONSE)
+
+ return respond
+
+
[email protected]("path", ["/v1/rerank", "/v2/rerank", "/rerank"])
+ ("client_fields", "api_base_suffix", "expected_body", "expected_route"),
+ [
+ pytest.param({}, "", COHERE_V2_BODY, "/v2/rerank", id="default-v2"),
+ pytest.param(
+ {"max_chunks_per_doc": 3, "return_documents": False}, "", COHERE_V1_BODY, "/v1/rerank", id="v1-sdk-fields"
+ ),
+ pytest.param({}, "/v1/rerank", COHERE_V2_BODY, "/v1/rerank", id="v1-api-base"),
+ pytest.param({"max_tokens_per_doc": 512}, "", COHERE_V2_SDK_BODY, "/v2/rerank", id="v2-sdk-fields"),
+ ],
+)
+def test_cohere_rerank_selects_v1_or_v2_from_client_fields_and_sends_exact_body(
+ gateway: Gateway,
+ path: str,
+ client_fields: dict[str, object],
+ api_base_suffix: str,
+ expected_body: dict[str, object],
+ expected_route: str,
+) -> None:
+ with wire_server(_cohere_peer(expected_body, expected_route)) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="cohere/rerank-v3.5",
+ api_key=COHERE_KEY,
+ api_base=wire.url + api_base_suffix,
+ model_info={"mode": "rerank"},
+ )
+ response: Final = gateway.request(
+ "POST", path, {"model": model, "query": QUERY, "documents": list(DOCUMENTS), "top_n": 1, **client_fields}
+ )
+ assert response.status_code == 200, response.text
+ assert _RerankResponse.model_validate_json(response.content) == _RerankResponse(
+ results=(_RerankResult(index=0, relevance_score=0.91), _RerankResult(index=1, relevance_score=0.03))
+ ), response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", expected_route)]
+
+
+OBJECT_DOCUMENTS: Final = ({"text": DOCUMENTS[0]}, {"text": DOCUMENTS[1]})
+
+
+ ("client_fields", "expected_route"),
+ [
+ pytest.param({}, "/v2/rerank", id="v2"),
+ pytest.param({"max_chunks_per_doc": 3, "return_documents": False}, "/v1/rerank", id="v1-sdk-fields"),
+ ],
+)
+def test_cohere_v1_sdk_object_documents_reach_cohere_unchanged_on_both_api_versions(
+ gateway: Gateway, client_fields: dict[str, object], expected_route: str
+) -> None:
+ expected_body: Final = {
+ "model": "rerank-v3.5",
+ "query": QUERY,
+ "top_n": 1,
+ "documents": list(OBJECT_DOCUMENTS),
+ **client_fields,
+ }
+ with wire_server(_cohere_peer(expected_body, expected_route)) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="cohere/rerank-v3.5", api_key=COHERE_KEY, api_base=wire.url, model_info={"mode": "rerank"}
+ )
+ response: Final = gateway.request(
+ "POST",
+ "/v1/rerank",
+ {"model": model, "query": QUERY, "documents": list(OBJECT_DOCUMENTS), "top_n": 1, **client_fields},
+ )
+ assert response.status_code == 200, response.text
+ assert _RerankResponse.model_validate_json(response.content) == _RerankResponse(
+ results=(_RerankResult(index=0, relevance_score=0.91), _RerankResult(index=1, relevance_score=0.03))
+ ), response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", expected_route)]
diff --git a/tests/integration/providers/test_search_wire.py b/tests/integration/providers/test_search_wire.py
new file mode 100644
index 00000000000..b60d92cb6a6
--- /dev/null
+++ b/tests/integration/providers/test_search_wire.py
@@ -0,0 +1,191 @@
+import json
+import uuid
+from typing import Final
+
+import pytest
+from integration._support.client import Gateway, Scenario
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import BaseModel
+
+_EXA_KEY: Final = "synthetic-exa-key"
+_QUERY: Final = "latest AI developments 2024"
+_DOMAINS: Final = ("arxiv.org", "nature.com")
+_PERPLEXITY_BODY: Final = {"query": _QUERY, "max_results": 5, "search_domain_filter": list(_DOMAINS), "country": "US"}
+_EXA_BODY: Final = {
+ "query": _QUERY,
+ "numResults": 5,
+ "includeDomains": list(_DOMAINS),
+ "userLocation": "US",
+ "contents": {"text": True},
+}
+_EXA_RESULTS: Final = {
+ "results": [
+ {
+ "title": "Gateway result",
+ "url": "https://result.invalid/a",
+ "text": "result snippet",
+ "publishedDate": "2024-01-01T00:00:00.000Z",
+ }
+ ]
+}
+
+
+class _SearchResult(BaseModel):
+ title: str
+ url: str
+ snippet: str
+ date: str | None
+ last_updated: str | None
+
+
+class _SearchResponse(BaseModel):
+ object: str
+ results: tuple[_SearchResult, ...]
+
+
+_EXPECTED_RESPONSE: Final = _SearchResponse(
+ object="search",
+ results=(
+ _SearchResult(
+ title="Gateway result",
+ url="https://result.invalid/a",
+ snippet="result snippet",
+ date="2024-01-01T00:00:00.000Z",
+ last_updated=None,
+ ),
+ ),
+)
+
+
+def _create_exa_tool(gateway: Gateway, scenario: Scenario, name: str, api_base: str) -> None:
+ created: Final = gateway.post(
+ "/search_tools",
+ {
+ "search_tool": {
+ "search_tool_name": name,
+ "litellm_params": {"search_provider": "exa_ai", "api_key": _EXA_KEY, "api_base": api_base},
+ }
+ },
+ )
+ scenario.cleanups.callback(gateway.request, "DELETE", f"/search_tools/{created['search_tool_id']}")
+
+
+def test_perplexity_spec_search_reaches_exa_with_only_mapped_fields_on_every_route_spelling(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", "/exa/search"), request.target
+ assert request.headers["x-api-key"] == _EXA_KEY, request.headers
+ assert "authorization" not in request.headers, request.headers
+ assert json.loads(request.body) == _EXA_BODY, request.body
+ return Reply(body=json.dumps(_EXA_RESULTS).encode())
+
+ tool: Final = f"exa-tool-{uuid.uuid4().hex}"
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ _create_exa_tool(gateway, scenario, tool, f"{wire.url}/exa")
+ spellings: Final = (
+ (f"/v1/search/{tool}", _PERPLEXITY_BODY),
+ (f"/search/{tool}", _PERPLEXITY_BODY),
+ ("/v1/search", {"search_tool_name": tool, **_PERPLEXITY_BODY}),
+ ("/search", {"search_tool_name": tool, **_PERPLEXITY_BODY}),
+ ("/v1/search", {"model": tool, **_PERPLEXITY_BODY}),
+ ("/search", {"model": tool, **_PERPLEXITY_BODY}),
+ (f"/v1/search/{tool}", {"search_tool_name": f"unknown-{uuid.uuid4().hex}", **_PERPLEXITY_BODY}),
+ )
+ for path, body in spellings:
+ response = gateway.request("POST", path, body)
+ assert response.status_code == 200, f"{path} {sorted(body)}: {response.text}"
+ assert _SearchResponse.model_validate_json(response.content) == _EXPECTED_RESPONSE, response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/exa/search")] * len(
+ spellings
+ )
+
+
+def test_exa_native_fields_and_caller_contents_pass_through_while_unmapped_perplexity_fields_are_dropped(
+ gateway: Gateway,
+) -> None:
+ def respond(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", "/exa/search"), request.target
+ assert request.headers["x-api-key"] == _EXA_KEY, request.headers
+ assert json.loads(request.body) == {
+ "query": _QUERY,
+ "numResults": 5,
+ "includeDomains": list(_DOMAINS),
+ "userLocation": "US",
+ "category": "research paper",
+ "startPublishedDate": "2024-01-01T00:00:00.000Z",
+ "contents": {"highlights": {"numSentences": 2}},
+ }, request.body
+ return Reply(body=json.dumps(_EXA_RESULTS).encode())
+
+ tool: Final = f"exa-tool-{uuid.uuid4().hex}"
+ body: Final = {
+ **_PERPLEXITY_BODY,
+ "max_tokens_per_page": 512,
+ "category": "research paper",
+ "startPublishedDate": "2024-01-01T00:00:00.000Z",
+ "contents": {"highlights": {"numSentences": 2}},
+ }
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ _create_exa_tool(gateway, scenario, tool, f"{wire.url}/exa")
+ response: Final = gateway.request("POST", f"/v1/search/{tool}", body)
+ assert response.status_code == 200, response.text
+ assert _SearchResponse.model_validate_json(response.content) == _EXPECTED_RESPONSE, response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/exa/search")]
+
+
+def test_list_query_reaches_exa_as_one_space_joined_query(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", "/exa/search"), request.target
+ assert request.headers["x-api-key"] == _EXA_KEY, request.headers
+ assert json.loads(request.body) == {
+ "query": "first q second q",
+ "numResults": 2,
+ "contents": {"text": True},
+ }, request.body
+ return Reply(body=json.dumps(_EXA_RESULTS).encode())
+
+ tool: Final = f"exa-tool-{uuid.uuid4().hex}"
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ _create_exa_tool(gateway, scenario, tool, f"{wire.url}/exa")
+ response: Final = gateway.request(
+ "POST", f"/v1/search/{tool}", {"query": ["first q", "second q"], "max_results": 2}
+ )
+ assert response.status_code == 200, response.text
+ assert _SearchResponse.model_validate_json(response.content) == _EXPECTED_RESPONSE, response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/exa/search")]
+
+
+def _not_found(name: str) -> str:
+ return f"Search tool '{name}' not found in router.search_tools"
+
+
+def test_unknown_search_tool_is_refused_without_reaching_any_configured_tool(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ raise AssertionError(f"unknown search tool reached a configured tool: {request.target} {request.body!r}")
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ _create_exa_tool(gateway, scenario, f"exa-tool-{uuid.uuid4().hex}", f"{wire.url}/exa")
+ name: Final = f"unknown-tool-{uuid.uuid4().hex}"
+ spellings: Final = (
+ (f"/v1/search/{name}", _PERPLEXITY_BODY),
+ ("/v1/search", {"search_tool_name": name, **_PERPLEXITY_BODY}),
+ )
+ for path, body in spellings:
+ response = gateway.request("POST", path, body)
+ refusal = (response.status_code >= 400, response.json().get("error", {}).get("message"))
+ assert refusal == (True, _not_found(name)), f"{path}: {response.text}"
+ assert wire.drain() == ()
+
+
+def test_unknown_search_tool_is_a_client_error_without_any_upstream_call(gateway: Gateway) -> None:
+ pytest.skip("BUG: POST /v1/search/<unknown or deleted tool> returns 500 internal_server_error instead of a 4xx")
+
+ def respond(request: Request) -> Reply:
+ raise AssertionError(f"unknown search tool reached a provider: {request.target}")
+
+ with wire_server(respond) as wire:
+ name: Final = f"unknown-tool-{uuid.uuid4().hex}"
+ response: Final = gateway.request("POST", f"/v1/search/{name}", _PERPLEXITY_BODY)
+ assert (response.status_code in (400, 404), response.json()["error"]["message"]) == (True, _not_found(name)), (
+ response.text
+ )
+ assert wire.drain() == ()