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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
test(integration): cover vector_stores endpoint contracts (#44739)
devin-ai-integration[bot]903f04dd46b8
diff --git a/tests/integration/authorization/test_rag_query_vector_store_allowlist.py b/tests/integration/authorization/test_rag_query_vector_store_allowlist.pyindex d3f16e46a1e..39f0ad1c7e9 100644--- a/tests/integration/authorization/test_rag_query_vector_store_allowlist.py+++ b/tests/integration/authorization/test_rag_query_vector_store_allowlist.py@@ -5,9 +5,11 @@ import osimport timeimport uuidfrom collections.abc import Iterator, Mapping+from hashlib import sha256from pathlib import Pathfrom types import MappingProxyTypefrom typing import Final, Literal, TypeAlias+from urllib.parse import urlsplitimport httpximport jwt@@ -15,10 +17,12 @@ import pytestimport yamlfrom cryptography.hazmat.primitives.asymmetric import rsafrom integration._support.client import Gateway, Scenario, eventually, gateway_from_environment, object_value+from integration._support.database import read_rowsfrom integration._support.process import owned_proxyfrom integration._support.wire import Reply, Request, wire_serverfrom integration.authorization._guardrail_opt_out import upstream_observations-from pydantic import JsonValue+from openai.types.chat import ChatCompletion+from pydantic import JsonValue, TypeAdapterfrom redis import RedisCONFIG_STORE_ID: Final = "vs_integration_config_store"@@ -27,6 +31,7 @@ REMOVE_OPENAI_API_BASE: Final = ("OPENAI_API_BASE",)JWT_KEY_ID: Final = "integration-vector-store-jwt-key"AUTH_CACHE_INVALIDATION_CHANNEL: Final = "litellm_proxy.auth_cache_invalidation"JsonObject: TypeAlias = dict[str, JsonValue]+JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])def _json_array(*values: JsonValue) -> JsonValue:@@ -45,12 +50,14 @@ def _key_for_scope(scenario: Scenario, model: str, scope: Literal["key", "team"]return scenario.key(team_id=team, models=_json_array(model))-def _rag_query_body(model: str, marker: str, store_id: str) -> JsonObject:+def _rag_query_body(model: str, marker: str, store_id: str, *, stream: bool | None = None) -> JsonObject:body: Final[JsonObject] = {"model": model,"messages": _json_array({"role": "user", "content": marker}),"retrieval_config": {"vector_store_id": store_id, "custom_llm_provider": "openai", "top_k": 1},}+ if stream is not None:+ body["stream"] = streamreturn body@@ -62,8 +69,9 @@ def _rag_query(*,store_id: str = CONFIG_STORE_ID,path: str = "/v1/rag/query",+ stream: bool | None = None,) -> httpx.Response:- return gateway.request("POST", path, _rag_query_body(model, marker, store_id), key=key)+ return gateway.request("POST", path, _rag_query_body(model, marker, store_id, stream=stream), key=key)def _searches_for_marker(@@ -436,6 +444,250 @@ def test_rag_query_alias_denies_store_when_team_allowlist_excludes(gateway: Gateassert _searches_for_marker(gateway, marker) == ()+def _content_delta(chunk: Mapping[str, JsonValue]) -> str:+ choices: Final = chunk["choices"]+ if not isinstance(choices, list) or not choices:+ return ""+ delta: Final = object_value(object_value(choices[0])["delta"])+ return str(delta.get("content", ""))+++def _assert_rag_query_response(+ gateway: Gateway,+ path: str,+ body: Mapping[str, JsonValue],+ key: str,+ stream: bool,+ response_id: str,+) -> None:+ response: Final = gateway.request("POST", path, {**body, "stream": stream}, key=key)+ assert response.status_code == 200, response.text+ if not stream:+ parsed: Final = ChatCompletion.model_validate_json(response.content)+ assert parsed.id == response_id, response.text+ assert parsed.choices[0].message.content == "RAG answer", response.text+ assert parsed.usage is not None and (parsed.usage.prompt_tokens, parsed.usage.completion_tokens) == (10, 5), (+ response.text+ )+ return++ assert response.headers["content-type"].startswith("text/event-stream"), response.text+ frames: Final = tuple(frame for frame in response.text.replace("\r\n", "\n").strip().split("\n\n") if frame)+ assert all(frame.startswith("data: ") for frame in frames), response.text+ assert frames[-1] == "data: [DONE]", response.text+ chunks: Final = tuple(JSON_OBJECT.validate_json(frame[6:]) for frame in frames[:-1])+ assert chunks, response.text+ assert tuple(chunk["id"] for chunk in chunks) == (response_id,) * len(chunks), response.text+ assert "".join(_content_delta(chunk) for chunk in chunks) == "RAG answer", response.text+++def test_rag_query_streaming_injects_search_context_and_records_spend(gateway: Gateway) -> None:+ store_id: Final = f"vs_rag_contract_{uuid.uuid4().hex}"+ search_key: Final = f"rag-search-{uuid.uuid4().hex}"+ chat_key: Final = f"rag-chat-{uuid.uuid4().hex}"+ questions: Final = tuple(f"what is in the note {uuid.uuid4().hex}" for _ in range(4))+ context_texts: Final = tuple(f"retrieved context for {question}" for question in questions)+ response_ids: Final = (+ f"chatcmpl-rag-v1-nonstream-{uuid.uuid4().hex}",+ f"chatcmpl-rag-v1-stream-{uuid.uuid4().hex}",+ f"chatcmpl-rag-alias-nonstream-{uuid.uuid4().hex}",+ f"chatcmpl-rag-alias-stream-{uuid.uuid4().hex}",+ )+ expected_messages_by_case: Final = tuple(+ _json_array(+ {"role": "system", "content": "Answer using the note."},+ {"role": "user", "content": f"Context:\n\n{context_text}\n\n"},+ {"role": "user", "content": question},+ )+ for question, context_text in zip(questions, context_texts)+ )+ search_body: Final[dict[str, JsonValue]] = {+ "filters": None,+ "max_num_results": 1,+ "ranking_options": None,+ "rewrite_query": None,+ }+ expected_search_calls: Final = iter(zip(questions, context_texts))+ expected_chat_calls: Final = iter(+ (+ (False, response_ids[0], expected_messages_by_case[0]),+ (True, response_ids[1], expected_messages_by_case[1]),+ (False, response_ids[2], expected_messages_by_case[2]),+ (True, response_ids[3], expected_messages_by_case[3]),+ )+ )++ def respond(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ if path == f"/v1/vector_stores/{store_id}/search":+ assert request.method == "POST"+ assert request.headers["authorization"] == f"Bearer {search_key}"+ search_question, search_context = next(expected_search_calls)+ assert JSON_OBJECT.validate_json(request.body) == {**search_body, "query": search_question}+ return Reply(+ body=json.dumps(+ {+ "object": "vector_store.search_results.page",+ "search_query": search_question,+ "data": [+ {+ "file_id": "file-rag-context",+ "filename": "context.txt",+ "score": 0.9,+ "attributes": {},+ "content": [{"type": "text", "text": search_context}],+ }+ ],+ "has_more": False,+ "next_page": None,+ }+ ).encode()+ )++ assert path == "/v1/chat/completions", request.target+ assert request.method == "POST"+ assert request.headers["authorization"] == f"Bearer {chat_key}"+ body: Final = JSON_OBJECT.validate_json(request.body)+ expected_stream, response_id, expected_messages = next(expected_chat_calls)+ assert body["messages"] == expected_messages, request.body.decode()+ stream: Final = body.get("stream", False)+ assert stream == expected_stream, request.body.decode()+ model_name: Final = str(body["model"])+ if stream:+ chunks: Final = (+ {+ "id": response_id,+ "object": "chat.completion.chunk",+ "created": 1700000000,+ "model": model_name,+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": "RAG "}, "finish_reason": None}],+ },+ {+ "id": response_id,+ "object": "chat.completion.chunk",+ "created": 1700000000,+ "model": model_name,+ "choices": [{"index": 0, "delta": {"content": "answer"}, "finish_reason": None}],+ },+ {+ "id": response_id,+ "object": "chat.completion.chunk",+ "created": 1700000000,+ "model": model_name,+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ },+ {+ "id": response_id,+ "object": "chat.completion.chunk",+ "created": 1700000000,+ "model": model_name,+ "choices": [],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},+ },+ )+ frames: Final = tuple(f"data: {json.dumps(chunk)}\n\n".encode() for chunk in chunks) + (+ b"data: [DONE]\n\n",+ )+ return Reply(chunks=frames, content_type="text/event-stream")+ return Reply(+ body=json.dumps(+ {+ "id": response_id,+ "object": "chat.completion",+ "created": 1700000000,+ "model": model_name,+ "choices": [+ {"index": 0, "message": {"role": "assistant", "content": "RAG answer"}, "finish_reason": "stop"}+ ],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},+ }+ ).encode()+ )++ with gateway.scenario() as scenario, wire_server(respond) as wire:+ model: Final = scenario.model(+ model="openai/gpt-4o-mini",+ api_base=f"{wire.url}/v1",+ api_key=chat_key,+ input_cost_per_token=0.001,+ output_cost_per_token=0.002,+ )+ registered: Final = gateway.request(+ "POST",+ "/vector_store/new",+ {+ "vector_store_id": store_id,+ "custom_llm_provider": "openai",+ "litellm_params": {"api_base": f"{wire.url}/v1", "api_key": search_key},+ },+ )+ assert registered.status_code == 200, registered.text+ scenario.cleanups.callback(gateway.post, "/vector_store/delete", {"vector_store_id": store_id})+ key: Final = _key_for_scope(scenario, model, "key", store_id)+ body: Final[JsonObject] = {+ "model": model,+ "retrieval_config": {+ "vector_store_id": store_id,+ "custom_llm_provider": "openai",+ "top_k": 1,+ },+ }+ request_bodies: Final = tuple(+ {+ **body,+ "messages": _json_array(+ {"role": "system", "content": "Answer using the note."},+ {"role": "user", "content": question},+ ),+ }+ for question in questions+ )+ query_cases: Final[tuple[tuple[str, bool, str], ...]] = (+ ("/v1/rag/query", False, response_ids[0]),+ ("/v1/rag/query", True, response_ids[1]),+ ("/rag/query", False, response_ids[2]),+ ("/rag/query", True, response_ids[3]),+ )+ for (path, stream, response_id), request_body in zip(query_cases, request_bodies):+ _assert_rag_query_response(gateway, path, request_body, key, stream, response_id)++ observed: Final = wire.drain()+ assert tuple((request.method, urlsplit(request.target).path) for request in observed) == (+ ("POST", f"/v1/vector_stores/{store_id}/search"),+ ("POST", "/v1/chat/completions"),+ ("POST", f"/v1/vector_stores/{store_id}/search"),+ ("POST", "/v1/chat/completions"),+ ("POST", f"/v1/vector_stores/{store_id}/search"),+ ("POST", "/v1/chat/completions"),+ ("POST", f"/v1/vector_stores/{store_id}/search"),+ ("POST", "/v1/chat/completions"),+ ), observed+ assert tuple(JSON_OBJECT.validate_json(request.body) for request in observed[::2]) == tuple(+ {**search_body, "query": question} for question in questions+ ), observed+ chat_bodies: Final = tuple(JSON_OBJECT.validate_json(request.body) for request in observed[1::2])+ assert tuple(body["messages"] for body in chat_bodies) == expected_messages_by_case, observed+ assert tuple(body["model"] for body in chat_bodies) == ("gpt-4o-mini",) * 4, observed+ assert tuple(body.get("stream", False) for body in chat_bodies) == (False, True, False, True), observed+ assert all(request.headers["authorization"] == f"Bearer {search_key}" for request in observed[::2])+ assert all(request.headers["authorization"] == f"Bearer {chat_key}" for request in observed[1::2])++ key_hash: Final = sha256(key.encode()).hexdigest()+ spend_rows: Final = eventually(+ lambda: read_rows(+ "SELECT request_id, api_key, spend, prompt_tokens, completion_tokens "+ 'FROM "LiteLLM_SpendLogs" WHERE request_id IN (%s, %s, %s, %s)',+ response_ids,+ ),+ lambda rows: len(rows) == 4,+ seconds=70,+ )+ assert {+ (row["request_id"], row["api_key"], float(row["spend"]), row["prompt_tokens"], row["completion_tokens"])+ for row in spend_rows+ } == {(response_id, key_hash, 0.02, 10, 5) for response_id in response_ids}++def test_explicit_false_flag_keeps_legacy_vector_store_outcomes(tmp_path: Path) -> None:with gateway_from_environment() as upstream_gateway:with owned_proxy(diff --git a/tests/integration/management/test_managed_vector_store_unified_id.py b/tests/integration/management/test_managed_vector_store_unified_id.pynew file mode 100644index 00000000000..0b0e51c0871--- /dev/null+++ b/tests/integration/management/test_managed_vector_store_unified_id.py@@ -0,0 +1,267 @@+import base64+import json+import uuid+from concurrent.futures import ThreadPoolExecutor+from functools import partial+from typing import Final+from urllib.parse import urlsplit++import httpx+from integration._support.client import Gateway, eventually, string_value+from integration._support.database import read_rows, write_rows+from integration._support.wire import Reply, Request, Wire, wire_server+from openai import OpenAI+from pydantic import BaseModel, JsonValue, TypeAdapter++JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_SEARCH_BODY: Final[dict[str, JsonValue]] = {+ "query": "unified search",+ "filters": None,+ "max_num_results": None,+ "ranking_options": None,+ "rewrite_query": None,+}+_SEARCH_RESPONSE: Final[dict[str, JsonValue]] = {+ "object": "vector_store.search_results.page",+ "search_query": "unified search",+ "data": [+ {+ "file_id": "file-managed-vector-store",+ "filename": "managed-store.txt",+ "score": 0.93,+ "attributes": {"team": "a"},+ "content": [{"type": "text", "text": "managed store content"}],+ }+ ],+ "has_more": False,+ "next_page": None,+}+_MANAGED_STORE_ROW: Final = (+ 'SELECT created_by, team_id FROM "LiteLLM_ManagedVectorStoreTable" WHERE unified_resource_id = %s'+)+++class _Content(BaseModel):+ type: str+ text: str+++class _Result(BaseModel):+ file_id: str+ filename: str+ score: float+ attributes: dict[str, str]+ content: tuple[_Content, ...]+++class _SearchPage(BaseModel):+ object: str+ search_query: str+ data: tuple[_Result, ...]+ has_more: bool+ next_page: str | None+++def _deployment_id(model: str) -> str:+ rows: Final = read_rows(+ 'SELECT model_id FROM "LiteLLM_ProxyModelTable" WHERE model_name = %s '+ "OR model_info->>'team_public_model_name' = %s",+ (model, model),+ )+ assert len(rows) == 1, f"Expected one deployment for {model!r}, found {rows}"+ return string_value(rows[0]["model_id"])+++def _worker_has_deployment(gateway: Gateway, deployment_id: str, _: int) -> bool:+ with httpx.Client(base_url=gateway.client.base_url, timeout=15, trust_env=False) as client:+ response: Final = client.get(+ "/model/info",+ params={"litellm_model_id": deployment_id},+ headers={"Authorization": f"Bearer {gateway.key}"},+ )+ if response.status_code == 200:+ return True+ assert response.status_code == 400, response.text+ assert "not found on litellm proxy" in response.text.lower(), response.text+ return False+++def _wait_until_every_worker_serves(gateway: Gateway, model: str) -> None:+ deployment_id: Final = _deployment_id(model)++ def every_worker_serves() -> bool:+ with ThreadPoolExecutor(max_workers=16) as pool:+ rounds: Final = tuple(+ tuple(pool.map(partial(_worker_has_deployment, gateway, deployment_id), range(16))) for _ in range(2)+ )+ return all(has_deployment for round_ in rounds for has_deployment in round_)++ eventually(every_worker_serves, lambda served: served, seconds=90)+++def _create_reply(provider_id: str, name: str) -> Reply:+ return Reply(+ body=json.dumps(+ {+ "id": provider_id,+ "object": "vector_store",+ "created_at": 1700000000,+ "name": name,+ "file_counts": {+ "in_progress": 0,+ "completed": 0,+ "failed": 0,+ "cancelled": 0,+ "total": 0,+ },+ "status": "completed",+ "usage_bytes": 0,+ "expires_after": None,+ "expires_at": None,+ "last_active_at": None,+ "metadata": {},+ }+ ).encode()+ )+++def _search_reply() -> Reply:+ return Reply(body=json.dumps(_SEARCH_RESPONSE).encode())+++def _models_reply() -> Reply:+ return Reply(body=json.dumps({"object": "list", "data": []}).encode())+++def _store_creation_requests(wire: Wire) -> tuple[Request, ...]:+ requests: Final = wire.drain()+ assert all(+ (request.method, request.target) in {("GET", "/v1/models"), ("POST", "/v1/vector_stores")}+ for request in requests+ ), requests+ return tuple(request for request in requests if request.method == "POST")+++def _create_request_body(name: str) -> dict[str, JsonValue]:+ return {+ "name": name,+ "file_ids": None,+ "expires_after": None,+ "chunking_strategy": None,+ }+++def _assert_create_request(request: Request, name: str) -> None:+ body: Final = JSON_OBJECT.validate_json(request.body)+ assert {key: value for key, value in body.items() if key != "metadata"} == _create_request_body(name)+++def _delete_managed_store_row(unified_id: str) -> None:+ write_rows(+ 'DELETE FROM "LiteLLM_ManagedVectorStoreTable" WHERE unified_resource_id = %s',+ (unified_id,),+ )+++def test_managed_vector_store_id_routes_to_creator_deployment_and_enforces_ownership(gateway: Gateway) -> None:+ store_name: Final = f"managed-store-{uuid.uuid4().hex}"+ provider_id_a: Final = f"vs_provider_a_{uuid.uuid4().hex}"+ provider_id_b: Final = f"vs_provider_b_{uuid.uuid4().hex}"+ provider_key_a: Final = f"provider-a-{uuid.uuid4().hex}"+ provider_key_b: Final = f"provider-b-{uuid.uuid4().hex}"++ def respond_a(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ assert request.headers["authorization"] == f"Bearer {provider_key_a}"+ if request.method == "GET" and path == "/v1/models":+ return _models_reply()+ if request.method == "POST" and path == "/v1/vector_stores":+ _assert_create_request(request, store_name)+ return _create_reply(provider_id_a, store_name)+ assert request.method == "POST"+ assert path == f"/v1/vector_stores/{provider_id_a}/search", request.target+ assert JSON_OBJECT.validate_json(request.body) == _SEARCH_BODY+ return _search_reply()++ def respond_b(request: Request) -> Reply:+ assert request.headers["authorization"] == f"Bearer {provider_key_b}"+ if request.method == "GET" and request.target == "/v1/models":+ return _models_reply()+ assert request.method == "POST"+ assert urlsplit(request.target).path == "/v1/vector_stores", request.target+ _assert_create_request(request, store_name)+ return _create_reply(provider_id_b, store_name)++ with (+ wire_server(respond_a) as wire_a,+ wire_server(respond_b) as wire_b,+ gateway.scenario() as scenario,+ ):+ model_a: Final = scenario.model(api_base=f"{wire_a.url}/v1", api_key=provider_key_a)+ model_b: Final = scenario.model(api_base=f"{wire_b.url}/v1", api_key=provider_key_b)+ _wait_until_every_worker_serves(gateway, model_a)+ _wait_until_every_worker_serves(gateway, model_b)+ creator_team: Final = scenario.team(models=[model_a, model_b])+ creator_user: Final = scenario.member(creator_team)+ creator_key: Final = scenario.key(team_id=creator_team, user_id=creator_user, models=[model_a, model_b])+ other_team: Final = scenario.team(models=[model_a, model_b])+ other_user: Final = scenario.member(other_team)+ other_key: Final = scenario.key(team_id=other_team, user_id=other_user, models=[model_a, model_b])++ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=creator_key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ created: Final = client.vector_stores.create(+ name=store_name,+ extra_body={"target_model_names": f"{model_a},{model_b}"},+ )++ unified_id: Final = created.id+ decoded_id: Final = base64.urlsafe_b64decode(unified_id + "=" * (-len(unified_id) % 4)).decode()+ assert decoded_id.startswith("litellm_proxy:vector_store;"), decoded_id+ assert f"target_model_names,{model_a},{model_b};" in decoded_id, decoded_id+ assert f"resource_id,{provider_id_a};" in decoded_id, decoded_id+ scenario.cleanups.callback(_delete_managed_store_row, unified_id)+ created_rows: Final = read_rows(_MANAGED_STORE_ROW, (unified_id,))+ assert created_rows == [{"created_by": creator_user, "team_id": creator_team}]+ assert [(request.method, request.target) for request in _store_creation_requests(wire_a)] == [+ ("POST", "/v1/vector_stores")+ ]+ assert [(request.method, request.target) for request in _store_creation_requests(wire_b)] == [+ ("POST", "/v1/vector_stores")+ ]++ search_path: Final = f"/v1/vector_stores/{unified_id}/search"+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=creator_key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ searched: Final = client.vector_stores.search(unified_id, query="unified search")+ assert searched.model_dump(exclude_unset=True) == _SEARCH_RESPONSE++ alias_search: Final = gateway.request(+ "POST",+ f"/vector_stores/{unified_id}/search",+ {"query": "unified search"},+ key=creator_key,+ )+ assert alias_search.status_code == 200, alias_search.text+ assert _SearchPage.model_validate_json(alias_search.content).model_dump(mode="json") == _SEARCH_RESPONSE+ assert [(request.method, request.target) for request in wire_a.drain()] == [+ ("POST", f"/v1/vector_stores/{provider_id_a}/search"),+ ("POST", f"/v1/vector_stores/{provider_id_a}/search"),+ ]+ assert wire_b.drain() == ()++ denied: Final = gateway.request("POST", search_path, _SEARCH_BODY, key=other_key)+ assert denied.status_code == 403, denied.text+ assert wire_a.drain() == ()+ assert wire_b.drain() == ()++ db_row_after_denial: Final = read_rows(_MANAGED_STORE_ROW, (unified_id,))+ assert db_row_after_denial == [{"created_by": creator_user, "team_id": creator_team}]diff --git a/tests/integration/management/test_vector_store_config_ownership.py b/tests/integration/management/test_vector_store_config_ownership.pyindex 24bea397ced..fbf21d7af06 100644--- a/tests/integration/management/test_vector_store_config_ownership.py+++ b/tests/integration/management/test_vector_store_config_ownership.py@@ -168,6 +168,158 @@ def test_db_store_lifecycle_is_unchanged_beside_config_store(gateway: Gateway) -assert missing.status_code == 404, missing.text+def test_team_owned_store_rejects_other_team_info_update_and_delete(gateway: Gateway) -> None:+ store_id: Final = f"vs_team_owned_{uuid.uuid4().hex}"+ with gateway.scenario() as scenario:+ owner_team: Final = scenario.team()+ owner_user: Final = scenario.member(owner_team)+ owner_key: Final = scenario.key(team_id=owner_team, user_id=owner_user)+ owner_admin_user: Final = scenario.user(user_role="proxy_admin")+ owner_admin_key: Final = scenario.key(user_id=owner_admin_user, team_id=owner_team)+ other_team: Final = scenario.team()+ other_key: Final = scenario.key(team_id=other_team)+ allowed_vector_store_routes: Final = [+ "/vector_store/info",+ "/vector_store/update",+ "/vector_store/delete",+ ]+ other_route_key: Final = scenario.key(team_id=other_team, allowed_routes=allowed_vector_store_routes)+ owner_route_key: Final = scenario.key(+ team_id=owner_team,+ user_id=owner_user,+ allowed_routes=allowed_vector_store_routes,+ )+ created: Final = gateway.request(+ "POST",+ "/vector_store/new",+ {+ "vector_store_id": store_id,+ "custom_llm_provider": "openai",+ "vector_store_name": "owner name",+ "litellm_params": {"api_base": "https://example.invalid/v1", "api_key": "original synthetic key"},+ },+ key=owner_admin_key,+ )+ assert created.status_code == 200, created.text+ scenario.cleanups.callback(+ gateway.request, "POST", "/vector_store/delete", {"vector_store_id": store_id}, key=gateway.key+ )+ snapshot_query: Final = (+ 'SELECT to_jsonb(store) FROM "LiteLLM_ManagedVectorStoresTable" AS store WHERE vector_store_id = %s'+ )+ before_denial: Final = read_rows(snapshot_query, (store_id,))+ assert len(before_denial) == 1, before_denial+ assert object_value(before_denial[0]["to_jsonb"])["team_id"] == owner_team, before_denial++ granted_info: Final = gateway.request(+ "POST", "/vector_store/info", {"vector_store_id": store_id}, key=other_route_key+ )+ assert granted_info.status_code == 403, granted_info.text+ denied_info: Final = gateway.request("POST", "/vector_store/info", {"vector_store_id": store_id}, key=other_key)+ assert denied_info.status_code == 403, denied_info.text+ assert read_rows(snapshot_query, (store_id,)) == before_denial+ denied_update: Final = gateway.request(+ "POST",+ "/vector_store/update",+ {+ "vector_store_id": store_id,+ "vector_store_name": "unauthorized name",+ "litellm_params": {"api_base": "https://example.invalid/changed", "api_key": "changed synthetic key"},+ },+ key=other_key,+ )+ assert denied_update.status_code == 401, denied_update.text+ assert read_rows(snapshot_query, (store_id,)) == before_denial+ granted_update: Final = gateway.request(+ "POST",+ "/vector_store/update",+ {"vector_store_id": store_id, "vector_store_name": "unauthorized granted update"},+ key=other_route_key,+ )+ assert granted_update.status_code == 403, granted_update.text+ assert read_rows(snapshot_query, (store_id,)) == before_denial+ denied_delete: Final = gateway.request(+ "POST", "/vector_store/delete", {"vector_store_id": store_id}, key=other_key+ )+ assert denied_delete.status_code == 401, denied_delete.text+ assert read_rows(snapshot_query, (store_id,)) == before_denial+ granted_delete: Final = gateway.request(+ "POST", "/vector_store/delete", {"vector_store_id": store_id}, key=other_route_key+ )+ assert granted_delete.status_code == 403, granted_delete.text+ assert read_rows(snapshot_query, (store_id,)) == before_denial++ owner_info: Final = gateway.request("POST", "/vector_store/info", {"vector_store_id": store_id}, key=owner_key)+ assert owner_info.status_code == 200, owner_info.text+ assert object_value(object_value(owner_info.json())["vector_store"])["vector_store_name"] == "owner name"++ updated: Final = gateway.request(+ "POST",+ "/vector_store/update",+ {"vector_store_id": store_id, "vector_store_name": "admin update"},+ key=gateway.key,+ )+ assert updated.status_code == 200, updated.text+ updated_rows: Final = read_rows(snapshot_query, (store_id,))+ assert len(updated_rows) == 1, updated_rows+ updated_store: Final = object_value(updated_rows[0]["to_jsonb"])+ assert updated_store["vector_store_name"] == "admin update", updated_rows+ assert updated_store["team_id"] == owner_team, updated_rows++ admin_info: Final = gateway.request(+ "POST", "/vector_store/info", {"vector_store_id": store_id}, key=gateway.key+ )+ assert admin_info.status_code == 200, admin_info.text+ assert object_value(object_value(admin_info.json())["vector_store"])["vector_store_name"] == "admin update"+ owner_updated: Final = gateway.request(+ "POST",+ "/vector_store/update",+ {"vector_store_id": store_id, "vector_store_name": "owner route grant update"},+ key=owner_route_key,+ )+ assert owner_updated.status_code == 200, owner_updated.text+ owner_info_after_update: Final = gateway.request(+ "POST", "/vector_store/info", {"vector_store_id": store_id}, key=owner_route_key+ )+ assert owner_info_after_update.status_code == 200, owner_info_after_update.text+ assert (+ object_value(object_value(owner_info_after_update.json())["vector_store"])["vector_store_name"]+ == "owner route grant update"+ ), owner_info_after_update.text+ owner_updated_rows: Final = read_rows(snapshot_query, (store_id,))+ assert len(owner_updated_rows) == 1, owner_updated_rows+ owner_updated_store: Final = object_value(owner_updated_rows[0]["to_jsonb"])+ assert owner_updated_store["vector_store_name"] == "owner route grant update", owner_updated_rows+ assert owner_updated_store["team_id"] == owner_team, owner_updated_rows+ owner_deleted: Final = gateway.request(+ "POST", "/vector_store/delete", {"vector_store_id": store_id}, key=owner_route_key+ )+ assert owner_deleted.status_code == 200, owner_deleted.text+ assert read_rows(snapshot_query, (store_id,)) == []+ owner_info_after_delete: Final = gateway.request(+ "POST", "/vector_store/info", {"vector_store_id": store_id}, key=gateway.key+ )+ assert owner_info_after_delete.status_code == 404, owner_info_after_delete.text++ admin_store_id: Final = f"vs_team_owned_admin_{uuid.uuid4().hex}"+ admin_created: Final = gateway.request(+ "POST",+ "/vector_store/new",+ {"vector_store_id": admin_store_id, "custom_llm_provider": "openai", "vector_store_name": "admin target"},+ key=owner_admin_key,+ )+ assert admin_created.status_code == 200, admin_created.text+ scenario.cleanups.callback(+ gateway.request, "POST", "/vector_store/delete", {"vector_store_id": admin_store_id}, key=gateway.key+ )+ assert len(read_rows(snapshot_query, (admin_store_id,))) == 1+ admin_deleted: Final = gateway.request(+ "POST", "/vector_store/delete", {"vector_store_id": admin_store_id}, key=gateway.key+ )+ assert admin_deleted.status_code == 200, admin_deleted.text+ assert read_rows(snapshot_query, (admin_store_id,)) == []++@pytest.mark.covers("other.vector_store.chat.config_store_search_reaches_upstream_after_listing")def test_chat_with_config_store_searches_upstream_and_injects_context_after_listing(gateway: Gateway) -> None:with (diff --git a/tests/integration/management/test_vector_store_file_list_managed_ids.py b/tests/integration/management/test_vector_store_file_list_managed_ids.pyindex 13a485f59d4..fed1b3eaa1f 100644--- a/tests/integration/management/test_vector_store_file_list_managed_ids.py+++ b/tests/integration/management/test_vector_store_file_list_managed_ids.py@@ -12,7 +12,7 @@ from functools import partialfrom pathlib import Pathfrom queue import SimpleQueuefrom types import MappingProxyType-from typing import Final+from typing import Final, TypeVarfrom urllib.parse import parse_qs, urlsplitimport httpx@@ -22,7 +22,7 @@ from integration._support.client import Gateway, Scenario, eventually, object_vafrom integration._support.database import read_rowsfrom integration._support.process import owned_proxy_processfrom integration._support.wire import Reply, Request, Wire, wire_server-from openai import AsyncOpenAI, OpenAI+from openai import APIStatusError, AsyncOpenAI, OpenAIfrom pydantic import JsonValue, TypeAdapterMANAGED_PREFIX: Final = "litellm_proxy:"@@ -34,6 +34,11 @@ JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])MANAGED_FILE_ROW: Final = ('SELECT flat_model_file_ids, created_by, team_id FROM "LiteLLM_ManagedFileTable" WHERE unified_file_id = %s')+T = TypeVar("T")+_FILE_CHUNKING: Final[dict[str, JsonValue]] = {+ "type": "static",+ "static": {"max_chunk_size_tokens": 800, "chunk_overlap_tokens": 400},+}Listing = Callable[[Request], Reply]@@ -46,6 +51,22 @@ def _bearer(request: Request) -> str:return request.headers.get("authorization", "").removeprefix("Bearer ")+def _assert_provider_upload(request: Request, bearer: str, filename: str) -> None:+ assert (request.method, request.target) == ("POST", "/v1/files"), request.target+ assert request.headers["authorization"] == f"Bearer {bearer}", request.headers+ uploaded_filename: Final = UPLOAD_FILENAME.search(request.body)+ assert uploaded_filename is not None and uploaded_filename.group(1) == filename.encode(), request.body[:200]+ assert b'name="purpose"' in request.body and b"user_data" in request.body, request.body[:200]+ assert f"notes in {filename}\n".encode() in request.body, request.body[:200]+++def _sdk_success(call: Callable[[], T]) -> T:+ try:+ return call()+ except APIStatusError as error:+ pytest.fail(str(error))++def _query(request: Request) -> dict[str, list[str]]:return parse_qs(urlsplit(request.target).query, keep_blank_values=True)@@ -84,6 +105,34 @@ def _store_file(store: str, file_id: JsonValue) -> dict[str, JsonValue]:}+def _store_file_response(+ store: str,+ file_id: str,+ attributes: Mapping[str, JsonValue],+ chunking_strategy: Mapping[str, JsonValue] | None = None,+) -> dict[str, JsonValue]:+ return {+ "id": file_id,+ "object": "vector_store.file",+ "usage_bytes": 123,+ "created_at": 1700000001,+ "vector_store_id": store,+ "status": "completed",+ "last_error": None,+ "chunking_strategy": chunking_strategy or {"type": "auto"},+ "attributes": dict(attributes),+ }+++def _file_content_page(content: bytes) -> dict[str, JsonValue]:+ return {+ "object": "vector_store.file_content.page",+ "data": [{"type": "text", "text": content.decode()}],+ "has_more": False,+ "next_page": None,+ }++def _page(store: str, file_ids: tuple[JsonValue, ...], *, has_more: bool = False) -> dict[str, JsonValue]:return {"object": "list",@@ -152,6 +201,78 @@ def _provider(store: str, listing: Listing) -> Callable[[Request], Reply]:return respond+def _managed_file_create_provider(+ store: str,+ bearer: str,+ filename: str,+ attributes: Mapping[str, JsonValue],+ chunking_strategy: Mapping[str, JsonValue],+) -> Callable[[Request], Reply]:+ provider_file_id: Final = _provider_file_id(bearer, filename)++ def respond(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ assert request.headers["authorization"] == f"Bearer {bearer}"+ if request.method == "POST" and path == "/v1/files":+ _assert_provider_upload(request, bearer, filename)+ return _json_reply(_file_object(provider_file_id))+ if request.method == "POST" and path == f"/v1/vector_stores/{store}/files":+ body: Final = JSON_OBJECT.validate_json(request.body)+ if "chunking_strategy" in body:+ return _json_reply(_store_file_response(store, provider_file_id, attributes, chunking_strategy))+ return _json_reply(_store_file(store, provider_file_id))+ if request.method == "GET" and path == f"/v1/vector_stores/{store}/files/{provider_file_id}":+ return _json_reply(_store_file_response(store, provider_file_id, attributes, chunking_strategy))+ return _json_reply({"error": {"message": f"unscripted {request.method} {request.target}"}}, 404)++ return respond+++def _managed_file_lifecycle_provider(+ store: str,+ bearer: str,+ filename: str,+ content: bytes,+) -> Callable[[Request], Reply]:+ provider_file_id: Final = _provider_file_id(bearer, filename)+ update_body: Final[dict[str, JsonValue]] = {"attributes": {"tenant": "b"}}+ chunking_strategy: Final[dict[str, JsonValue]] = {"type": "auto"}+ file_path_prefix: Final = f"/v1/vector_stores/{store}/files/"++ def respond(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ assert request.headers["authorization"] == f"Bearer {bearer}"+ if request.method == "POST" and path == "/v1/files":+ _assert_provider_upload(request, bearer, filename)+ return _json_reply(_file_object(provider_file_id))+ if request.method == "POST" and path == f"/v1/vector_stores/{store}/files":+ body: Final = JSON_OBJECT.validate_json(request.body)+ assert body == {"file_id": provider_file_id}+ return _json_reply(_store_file(store, provider_file_id))+ if path.startswith(file_path_prefix):+ resource_path: Final = path.removeprefix(file_path_prefix)+ is_content_request: Final = resource_path.endswith("/content")+ request_file_id: Final = resource_path.removesuffix("/content")+ assert request_file_id and "/" not in request_file_id, request.target+ if is_content_request and request.method == "GET":+ return Reply(+ body=json.dumps(_file_content_page(content)).encode(),+ headers={"content-disposition": f'attachment; filename="{filename}"'},+ )+ if is_content_request:+ return _json_reply({"error": {"message": f"unscripted {request.method} {request.target}"}}, 404)+ if request.method == "GET":+ return _json_reply(_store_file_response(store, request_file_id, {"tenant": "a"}, chunking_strategy))+ if request.method == "POST":+ assert JSON_OBJECT.validate_json(request.body) == update_body+ return _json_reply(_store_file_response(store, request_file_id, {"tenant": "b"}, chunking_strategy))+ if request.method == "DELETE":+ return _json_reply({"id": request_file_id, "object": "vector_store.file.deleted", "deleted": True})+ return _json_reply({"error": {"message": f"unscripted {request.method} {request.target}"}}, 404)++ return respond++def _decoded(managed_file_id: str) -> str:decoded: Final = base64.urlsafe_b64decode(managed_file_id + "=" * (-len(managed_file_id) % 4)).decode()assert decoded.startswith(MANAGED_PREFIX), decoded@@ -190,25 +311,45 @@ def _sdk_base_url(gateway: Gateway) -> str:return str(gateway.client.base_url).rstrip("/") + "/v1"-def _models_over_a_fresh_connection(gateway: Gateway, _: int) -> frozenset[str]:+def _deployment_id(model: str) -> str:+ rows: Final = read_rows(+ 'SELECT model_id FROM "LiteLLM_ProxyModelTable" WHERE model_name = %s '+ "OR model_info->>'team_public_model_name' = %s",+ (model, model),+ )+ assert len(rows) == 1, f"Expected one deployment for {model!r}, found {rows}"+ return string_value(rows[0]["model_id"])+++def _worker_has_deployment(gateway: Gateway, deployment_id: str, _: int) -> bool:with httpx.Client(base_url=gateway.client.base_url, timeout=15, trust_env=False) as client:- listed: Final = client.get("/v1/models", headers={"Authorization": f"Bearer {gateway.key}"})- assert listed.status_code == 200, listed.text- data: Final = _json(listed)["data"]- assert isinstance(data, list), listed.text- return frozenset(string_value(object_value(entry)["id"]) for entry in data)+ response: Final = client.get(+ "/model/info",+ params={"litellm_model_id": deployment_id},+ headers={"Authorization": f"Bearer {gateway.key}"},+ )+ if response.status_code == 200:+ return True+ assert response.status_code == 400, response.text+ assert "not found on litellm proxy" in response.text.lower(), response.text+ return False-def _every_worker_serves(gateway: Gateway, model: str) -> bool:+def _every_worker_has_deployment(gateway: Gateway, deployment_id: str) -> bool:with ThreadPoolExecutor(max_workers=16) as pool:rounds: Final = tuple(- tuple(pool.map(partial(_models_over_a_fresh_connection, gateway), range(16))) for _ in range(2)+ tuple(pool.map(partial(_worker_has_deployment, gateway, deployment_id), range(16))) for _ in range(2))- return all(model in seen for round_ in rounds for seen in round_)+ return all(has_deployment for round_ in rounds for has_deployment in round_)def _wait_until_every_worker_serves(gateway: Gateway, model: str) -> None:- eventually(lambda: _every_worker_serves(gateway, model), lambda served: served, seconds=90)+ deployment_id: Final = _deployment_id(model)+ eventually(+ lambda: _every_worker_has_deployment(gateway, deployment_id),+ lambda served: served,+ seconds=90,+ )@dataclass(frozen=True, slots=True)@@ -218,10 +359,18 @@ class _Member:key: str-def _member(scenario: Scenario, *models: str) -> _Member:+def _member(scenario: Scenario, *models: str, router_settings: Mapping[str, JsonValue] | None = None) -> _Member:team: Final = scenario.team(models=list(models))user: Final = scenario.member(team)- return _Member(team, user, scenario.key(team_id=team, user_id=user))+ return _Member(+ team,+ user,+ scenario.key(+ team_id=team,+ user_id=user,+ **({"router_settings": dict(router_settings)} if router_settings is not None else {}),+ ),+ )@dataclass(frozen=True, slots=True)@@ -320,6 +469,389 @@ def test_attach_by_managed_id_sends_the_provider_file_id_and_lists_it_back_managassert _ids(rig.listed(member.key)) == (managed_a,)+def test_managed_file_create_forwards_attributes_and_chunking_strategy(gateway: Gateway) -> None:+ store: Final = f"vs_create_managed_{uuid.uuid4().hex}"+ bearer_a: Final = f"provider-create-a-{uuid.uuid4().hex}"+ bearer_b: Final = f"provider-create-b-{uuid.uuid4().hex}"+ filename: Final = "create-managed.txt"+ attributes: Final[dict[str, JsonValue]] = {"tenant": "a"}+ provider_file_id_a: Final = _provider_file_id(bearer_a, filename)+ create_body: Final[dict[str, JsonValue]] = {+ "file_id": provider_file_id_a,+ "attributes": attributes,+ "chunking_strategy": _FILE_CHUNKING,+ }+ with (+ gateway.scenario() as scenario,+ wire_server(_managed_file_create_provider(store, bearer_a, filename, attributes, _FILE_CHUNKING)) as wire_a,+ wire_server(_managed_file_create_provider(store, bearer_b, filename, attributes, _FILE_CHUNKING)) as wire_b,+ ):+ model_a: Final = scenario.model(api_base=f"{wire_a.url}/v1", api_key=bearer_a)+ model_b: Final = scenario.model(api_base=f"{wire_b.url}/v1", api_key=bearer_b)+ member: Final = _member(scenario, model_a, model_b)+ _wait_until_every_worker_serves(gateway, model_a)+ _wait_until_every_worker_serves(gateway, model_b)+ wire_a.drain()+ wire_b.drain()+ managed_file_id: Final = _upload(gateway, member.key, f"{model_a},{model_b}", filename)+ assert _carried_provider_file_id(managed_file_id) == provider_file_id_a, _decoded(managed_file_id)+ assert read_rows(MANAGED_FILE_ROW, (managed_file_id,)) == [+ {+ "flat_model_file_ids": [provider_file_id_a, _provider_file_id(bearer_b, filename)],+ "created_by": member.user,+ "team_id": member.team,+ }+ ]+ upload_requests_a: Final = wire_a.drain()+ upload_requests_b: Final = wire_b.drain()+ assert tuple((request.method, request.target) for request in upload_requests_a) == (("POST", "/v1/files"),)+ assert tuple((request.method, request.target) for request in upload_requests_b) == (("POST", "/v1/files"),)+ _assert_provider_upload(upload_requests_a[0], bearer_a, filename)+ _assert_provider_upload(upload_requests_b[0], bearer_b, filename)+ with OpenAI(+ base_url=_sdk_base_url(gateway),+ api_key=member.key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ created: Final = _sdk_success(+ lambda: client.vector_stores.files.create(+ store,+ file_id=managed_file_id,+ attributes=attributes,+ chunking_strategy=_FILE_CHUNKING,+ )+ )+ polled: Final = _sdk_success(+ lambda: client.vector_stores.files.create_and_poll(+ managed_file_id,+ vector_store_id=store,+ attributes=attributes,+ chunking_strategy=_FILE_CHUNKING,+ poll_interval_ms=0,+ )+ )+ alias_created: Final = gateway.request(+ "POST",+ f"/vector_stores/{store}/files",+ {"file_id": managed_file_id, "attributes": attributes, "chunking_strategy": _FILE_CHUNKING},+ key=member.key,+ )+ assert alias_created.status_code == 200, alias_created.text+ assert _json(alias_created) == _store_file_response(store, managed_file_id, attributes, _FILE_CHUNKING), (+ alias_created.text+ )+ assert created.id == managed_file_id and created.attributes == attributes, str(created)+ assert polled.id == managed_file_id and polled.status == "completed", str(polled)+ requests_a: Final = wire_a.drain()+ assert [(request.method, request.target) for request in requests_a] == [+ ("POST", f"/v1/vector_stores/{store}/files"),+ ("POST", f"/v1/vector_stores/{store}/files"),+ ("GET", f"/v1/vector_stores/{store}/files/{provider_file_id_a}"),+ ("POST", f"/v1/vector_stores/{store}/files"),+ ], requests_a+ assert tuple(+ JSON_OBJECT.validate_json(request.body) for request in (requests_a[0], requests_a[1], requests_a[3])+ ) == (create_body, create_body, create_body), requests_a+ assert requests_a[2].body == b"", requests_a[2]+ assert all(request.headers["authorization"] == f"Bearer {bearer_a}" for request in requests_a)+ assert all(_query(request) == {} for request in requests_a), requests_a+ assert wire_b.drain() == ()+++def test_managed_file_create_preserves_numeric_and_boolean_attributes(gateway: Gateway) -> None:+ pytest.skip("BUG: vector store file attributes drop non-string values (year, flag)")++ store: Final = f"vs_attributes_{uuid.uuid4().hex}"+ bearer: Final = f"provider-attributes-{uuid.uuid4().hex}"+ filename: Final = "attributes-managed.txt"+ attributes: Final[dict[str, JsonValue]] = {"tenant": "a", "year": 2024, "flag": True}+ with gateway.scenario() as scenario:+ with wire_server(_managed_file_create_provider(store, bearer, filename, attributes, _FILE_CHUNKING)) as wire:+ model: Final = scenario.model(api_base=f"{wire.url}/v1", api_key=bearer)+ member: Final = _member(scenario, model)+ _wait_until_every_worker_serves(gateway, model)+ managed_file_id: Final = _upload(gateway, member.key, model, filename)+ with OpenAI(+ base_url=_sdk_base_url(gateway),+ api_key=member.key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ created: Final = client.vector_stores.files.create(+ store,+ file_id=managed_file_id,+ attributes=attributes,+ chunking_strategy=_FILE_CHUNKING,+ extra_query={"model": model},+ )+ assert created.id == managed_file_id, str(created)+ requests: Final = wire.drain()+ assert JSON_OBJECT.validate_json(requests[-1].body) == {+ "file_id": _provider_file_id(bearer, filename),+ "attributes": attributes,+ "chunking_strategy": _FILE_CHUNKING,+ }, f"observed={JSON_OBJECT.validate_json(requests[-1].body)!r}; response={created}"+++def test_managed_file_lifecycle_routes_and_restores_managed_ids(gateway: Gateway) -> None:+ store: Final = f"vs_lifecycle_{uuid.uuid4().hex}"+ bearer_a: Final = f"provider-lifecycle-a-{uuid.uuid4().hex}"+ bearer_b: Final = f"provider-lifecycle-b-{uuid.uuid4().hex}"+ filename: Final = "lifecycle-managed.txt"+ content: Final = b"managed vector store file contents\n"+ provider_file_id_a: Final = _provider_file_id(bearer_a, filename)+ update_body: Final[dict[str, JsonValue]] = {"attributes": {"tenant": "b"}}++ with (+ gateway.scenario() as scenario,+ wire_server(_managed_file_lifecycle_provider(store, bearer_a, filename, content)) as wire_a,+ wire_server(_managed_file_lifecycle_provider(store, bearer_b, filename, content)) as wire_b,+ ):+ model_a: Final = scenario.model(api_base=f"{wire_a.url}/v1", api_key=bearer_a)+ model_b: Final = scenario.model(api_base=f"{wire_b.url}/v1", api_key=bearer_b)+ owner: Final = _member(scenario, model_a, model_b)+ _wait_until_every_worker_serves(gateway, model_a)+ _wait_until_every_worker_serves(gateway, model_b)+ wire_a.drain()+ wire_b.drain()+ managed_file_id: Final = _upload(gateway, owner.key, f"{model_a},{model_b}", filename)+ assert _carried_provider_file_id(managed_file_id) == provider_file_id_a, _decoded(managed_file_id)+ upload_requests_a: Final = wire_a.drain()+ upload_requests_b: Final = wire_b.drain()+ assert tuple((request.method, request.target) for request in upload_requests_a) == (("POST", "/v1/files"),)+ assert tuple((request.method, request.target) for request in upload_requests_b) == (("POST", "/v1/files"),)+ _assert_provider_upload(upload_requests_a[0], bearer_a, filename)+ _assert_provider_upload(upload_requests_b[0], bearer_b, filename)+ attached: Final = gateway.request(+ "POST",+ f"/v1/vector_stores/{store}/files",+ {"file_id": provider_file_id_a},+ key=owner.key,+ params={"model": model_a},+ )+ assert attached.status_code == 200, attached.text+ assert _json(attached) == _store_file(store, provider_file_id_a), attached.text+ setup_requests: Final = wire_a.drain()+ assert [(request.method, request.target) for request in setup_requests] == [+ ("POST", f"/v1/vector_stores/{store}/files"),+ ], setup_requests+ assert JSON_OBJECT.validate_json(setup_requests[0].body) == {"file_id": provider_file_id_a}, setup_requests+ assert setup_requests[0].headers["authorization"] == f"Bearer {bearer_a}", setup_requests[0].headers+ assert _query(setup_requests[0]) == {}, setup_requests[0].target++ with OpenAI(+ base_url=_sdk_base_url(gateway),+ api_key=owner.key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ expected_retrieved_sdk: Final = _store_file_response(store, managed_file_id, {"tenant": "a"})+ expected_updated_sdk: Final = _store_file_response(store, managed_file_id, {"tenant": "b"})+ retrieved: Final = _sdk_success(+ lambda: client.vector_stores.files.retrieve(managed_file_id, vector_store_id=store)+ )+ assert retrieved.model_dump(mode="json", exclude_unset=True) == expected_retrieved_sdk, str(retrieved)+ updated: Final = _sdk_success(+ lambda: client.vector_stores.files.update(+ managed_file_id, vector_store_id=store, attributes={"tenant": "b"}+ )+ )+ assert updated.model_dump(mode="json", exclude_unset=True) == expected_updated_sdk, str(updated)+ content_page: Final = _sdk_success(+ lambda: client.vector_stores.files.content(managed_file_id, vector_store_id=store)+ )+ expected_content_page: Final = _file_content_page(content)+ assert content_page.model_dump(mode="json", exclude_unset=True) == expected_content_page, str(content_page)+ deleted: Final = _sdk_success(+ lambda: client.vector_stores.files.delete(managed_file_id, vector_store_id=store)+ )+ assert deleted.id == managed_file_id, str(deleted)+ assert deleted.deleted is True, str(deleted)++ alias_file_path: Final = f"/vector_stores/{store}/files/{managed_file_id}"+ expected_retrieved_alias: Final = _store_file_response(store, managed_file_id, {"tenant": "a"})+ alias_retrieved: Final = gateway.request("GET", alias_file_path, key=owner.key)+ assert alias_retrieved.status_code == 200, alias_retrieved.text+ assert _json(alias_retrieved) == expected_retrieved_alias, alias_retrieved.text+ alias_updated: Final = gateway.request("POST", alias_file_path, update_body, key=owner.key)+ assert alias_updated.status_code == 200, alias_updated.text+ expected_updated_alias: Final = _store_file_response(store, managed_file_id, {"tenant": "b"})+ assert _json(alias_updated) == expected_updated_alias, alias_updated.text+ raw_content: Final = gateway.request("GET", f"{alias_file_path}/content", key=owner.key)+ assert raw_content.status_code == 200, raw_content.text+ expected_content_page: Final = _file_content_page(content)+ assert raw_content.content == json.dumps(expected_content_page, separators=(",", ":")).encode(), (+ raw_content.text+ )+ assert raw_content.headers["content-disposition"] == f'attachment; filename="{managed_file_id}"', (+ raw_content.text+ )+ assert raw_content.headers["x-content-type-options"] == "nosniff", raw_content.text+ alias_deleted: Final = gateway.request("DELETE", alias_file_path, key=owner.key)+ assert alias_deleted.status_code == 200, alias_deleted.text+ assert _json(alias_deleted) == {+ "id": managed_file_id,+ "object": "vector_store.file.deleted",+ "deleted": True,+ }, alias_deleted.text++ expected_provider_path: Final = f"/v1/vector_stores/{store}/files/{provider_file_id_a}"+ expected_content_path: Final = f"{expected_provider_path}/content"+ lifecycle_requests: Final = wire_a.drain()+ assert [(request.method, request.target) for request in lifecycle_requests] == [+ ("GET", expected_provider_path),+ ("POST", expected_provider_path),+ ("GET", expected_content_path),+ ("DELETE", expected_provider_path),+ ("GET", expected_provider_path),+ ("POST", expected_provider_path),+ ("GET", expected_content_path),+ ("DELETE", expected_provider_path),+ ], lifecycle_requests+ assert JSON_OBJECT.validate_json(lifecycle_requests[1].body) == update_body, lifecycle_requests[1]+ assert JSON_OBJECT.validate_json(lifecycle_requests[5].body) == update_body, lifecycle_requests[5]+ assert tuple(lifecycle_requests[index].body for index in (0, 2, 3, 4, 6, 7)) == (+ b"",+ b"",+ b"",+ b"",+ b"",+ b"",+ ), lifecycle_requests+ assert all(request.headers["authorization"] == f"Bearer {bearer_a}" for request in lifecycle_requests)+ assert all(_query(request) == {} for request in lifecycle_requests), lifecycle_requests+ assert wire_b.drain() == ()+++def test_team_model_managed_file_lifecycle_forwards_the_provider_file_id(gateway: Gateway) -> None:+ store: Final = f"vs_team_lifecycle_{uuid.uuid4().hex}"+ bearer: Final = f"provider-team-lifecycle-{uuid.uuid4().hex}"+ filename: Final = "team-lifecycle-managed.txt"+ content: Final = b"team model vector store file contents\n"+ provider_file_id: Final = _provider_file_id(bearer, filename)+ update_body: Final[dict[str, JsonValue]] = {"attributes": {"tenant": "b"}}++ with (+ gateway.scenario() as scenario,+ wire_server(_managed_file_lifecycle_provider(store, bearer, filename, content)) as wire,+ ):+ team: Final = scenario.team(models=[])+ model: Final = scenario.model(api_base=f"{wire.url}/v1", api_key=bearer, model_info={"team_id": team})+ user: Final = scenario.member(team)+ key: Final = scenario.key(team_id=team, user_id=user)+ _wait_until_every_worker_serves(gateway, model)+ wire.drain()+ entries: Final = gateway.get("/model/info")["data"]+ assert isinstance(entries, list)+ internal: Final = tuple(+ string_value(object_value(entry)["model_name"])+ for entry in entries+ if object_value(object_value(entry)["model_info"]).get("team_public_model_name") == model+ )+ assert len(internal) == 1, entries+ managed_file_id: Final = _upload(gateway, key, internal[0], filename)+ assert _carried_provider_file_id(managed_file_id) == provider_file_id, _decoded(managed_file_id)+ attached: Final = gateway.request(+ "POST", f"/v1/vector_stores/{store}/files", {"file_id": provider_file_id}, key=key+ )+ assert attached.status_code == 200, attached.text+ setup_requests: Final = wire.drain()+ assert [(request.method, request.target) for request in setup_requests] == [+ ("POST", "/v1/files"),+ ("POST", f"/v1/vector_stores/{store}/files"),+ ], setup_requests++ file_path: Final = f"/v1/vector_stores/{store}/files/{managed_file_id}"+ retrieved: Final = gateway.request("GET", file_path, key=key)+ assert retrieved.status_code == 200, retrieved.text+ assert _json(retrieved) == _store_file_response(store, managed_file_id, {"tenant": "a"}), retrieved.text+ updated: Final = gateway.request("POST", file_path, update_body, key=key)+ assert updated.status_code == 200, updated.text+ assert _json(updated) == _store_file_response(store, managed_file_id, {"tenant": "b"}), updated.text+ downloaded: Final = gateway.request("GET", f"{file_path}/content", key=key)+ assert downloaded.status_code == 200, downloaded.text+ assert downloaded.content == json.dumps(_file_content_page(content), separators=(",", ":")).encode(), (+ downloaded.text+ )+ assert downloaded.headers["content-disposition"] == f'attachment; filename="{managed_file_id}"', downloaded.text+ assert downloaded.headers["x-content-type-options"] == "nosniff", downloaded.text+ deleted: Final = gateway.request("DELETE", file_path, key=key)+ assert deleted.status_code == 200, deleted.text+ assert _json(deleted) == {"id": managed_file_id, "object": "vector_store.file.deleted", "deleted": True}, (+ deleted.text+ )++ provider_path: Final = f"/v1/vector_stores/{store}/files/{provider_file_id}"+ lifecycle_requests: Final = wire.drain()+ assert [(request.method, request.target) for request in lifecycle_requests] == [+ ("GET", provider_path),+ ("POST", provider_path),+ ("GET", f"{provider_path}/content"),+ ("DELETE", provider_path),+ ], lifecycle_requests+ assert JSON_OBJECT.validate_json(lifecycle_requests[1].body) == update_body, lifecycle_requests[1]+ assert tuple(lifecycle_requests[index].body for index in (0, 2, 3)) == (b"", b"", b""), lifecycle_requests+ assert all(request.headers["authorization"] == f"Bearer {bearer}" for request in lifecycle_requests)+++def test_stranger_cannot_access_another_teams_managed_file(gateway: Gateway) -> None:+ pytest.skip("BUG: another team can retrieve, update, delete, and read content from a managed vector-store file")++ store: Final = f"vs_stranger_{uuid.uuid4().hex}"+ bearer: Final = f"provider-stranger-{uuid.uuid4().hex}"+ filename: Final = f"stranger-{uuid.uuid4().hex}.txt"+ content: Final = b"managed vector store file contents\n"+ provider: Final = _managed_file_lifecycle_provider(store, bearer, filename, content)++ with gateway.scenario() as scenario, wire_server(provider) as wire:+ model: Final = scenario.model(api_base=f"{wire.url}/v1", api_key=bearer)+ owner: Final = _member(scenario, model)+ stranger: Final = _member(scenario, model)+ _wait_until_every_worker_serves(gateway, model)+ wire.drain()+ managed_file_id: Final = _upload(gateway, owner.key, model, filename)+ attached: Final = gateway.request(+ "POST",+ f"/v1/vector_stores/{store}/files",+ {"file_id": managed_file_id},+ key=owner.key,+ params={"model": model},+ )+ assert attached.status_code == 200, attached.text+ assert _json(attached)["id"] == managed_file_id, attached.text+ setup_requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in setup_requests] == [+ ("POST", "/v1/files"),+ ("POST", f"/v1/vector_stores/{store}/files"),+ ], setup_requests++ file_path: Final = f"/v1/vector_stores/{store}/files/{managed_file_id}"+ responses: Final = (+ gateway.request("GET", file_path, key=stranger.key, params={"model": model}),+ gateway.request(+ "POST",+ file_path,+ {"attributes": {"tenant": "b"}},+ key=stranger.key,+ params={"model": model},+ ),+ gateway.request("DELETE", file_path, key=stranger.key, params={"model": model}),+ gateway.request(+ "GET",+ f"{file_path}/content",+ key=stranger.key,+ params={"model": model},+ ),+ )+ upstream_requests: Final = wire.drain()+ assert tuple(response.status_code for response in responses) == (403, 403, 403, 403), {+ "responses": tuple((response.status_code, response.text) for response in responses),+ "upstream": tuple((request.method, request.target) for request in upstream_requests),+ }+ assert upstream_requests == ()++def test_openai_sdk_sync_auto_pager_walks_pages_with_managed_cursors(gateway: Gateway) -> None:with _rig(gateway, listing=_two_pages) as rig:member: Final = _member(rig.scenario, rig.model)@@ -610,9 +1142,9 @@ def test_provider_errors_reach_the_caller_and_other_models_keep_mapping() -> None:message: Final = f"provider refused listing {uuid.uuid4().hex[:8]}"with _rig(gateway, listing=_error_listing(status, message)) as failing, _rig(gateway, "a.txt") as healthy:- member: Final = _member(failing.scenario, failing.model, healthy.model)+ member: Final = _member(failing.scenario, failing.model, healthy.model, router_settings={"num_retries": 2})managed_a: Final = healthy.upload(member.key, "a.txt")- failed: Final = failing.list(member.key, {"model": failing.model})+ failed: Final = failing.list(member.key, {"model": failing.model}, {"x-litellm-num-retries": "0"})assert failed.status_code == status, failed.texterror: Final = object_value(_json(failed)["error"])assert message in string_value(error["message"]), failed.text@@ -626,9 +1158,9 @@ def test_provider_errors_reach_the_caller_and_other_models_keep_mapping(def test_non_json_provider_body_is_an_error_response_and_other_models_keep_mapping(gateway: Gateway) -> None:with _rig(gateway, listing=_html_listing()) as failing, _rig(gateway, "a.txt") as healthy:- member: Final = _member(failing.scenario, failing.model, healthy.model)+ member: Final = _member(failing.scenario, failing.model, healthy.model, router_settings={"num_retries": 2})managed_a: Final = healthy.upload(member.key, "a.txt")- failed: Final = failing.list(member.key, {"model": failing.model})+ failed: Final = failing.list(member.key, {"model": failing.model}, {"x-litellm-num-retries": "0"})assert failed.status_code == 500, failed.textassert string_value(object_value(_json(failed)["error"])["message"]), failed.textassert _ids(healthy.listed(member.key)) == (managed_a,)@@ -673,6 +1205,7 @@ def test_provider_outage_mid_burst_fails_loudly_and_mapping_resumes_after_recovewith wire_server(respond) as wire:model: Final = scenario.model(api_base=wire.url + "/v1", api_key=bearer)_wait_until_every_worker_serves(gateway, model)+ wire.drain()member: Final = _member(scenario, model)managed_a: Final = _upload(gateway, member.key, model, "a.txt")assert _carried_provider_file_id(managed_a) == provider_adiff --git a/tests/integration/providers/test_rag_ingest_wire.py b/tests/integration/providers/test_rag_ingest_wire.pynew file mode 100644index 00000000000..847e5735d66--- /dev/null+++ b/tests/integration/providers/test_rag_ingest_wire.py@@ -0,0 +1,386 @@+import base64+import json+import re+import uuid+from collections.abc import Callable, Mapping+from email.message import Message+from email.parser import BytesParser+from email.policy import HTTP+from pathlib import Path+from types import MappingProxyType+from typing import Final+from urllib.parse import urlsplit++import httpx+import pytest+import yaml+from integration._support.client import Gateway, gateway_from_environment, object_value+from integration._support.process import owned_proxy+from integration._support.wire import Reply, Request, wire_server+from pydantic import JsonValue, TypeAdapter++PROXY_CONFIG: Final = Path(__file__).resolve().parents[1] / "proxy_config.yaml"+JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_MULTIPART_CONTENT: Final = b"UI multipart content\n"+_JSON_CONTENT: Final = b"JSON base64 content\n"+_REGISTRY_CONTENT: Final = b"registered vector store content\n"+_GENERATED_FILENAME: Final = re.compile(r"^[0-9a-f]{32}\.txt$")+_PROVIDER_CREATE_BODY: Final[dict[str, JsonValue]] = {+ "name": "rag ingest contract",+ "file_ids": None,+ "expires_after": None,+ "chunking_strategy": None,+ "metadata": None,+}+_INGEST_FILE_IDS: Final = MappingProxyType(+ {+ _MULTIPART_CONTENT: "file_ingest_multipart",+ _JSON_CONTENT: "file_ingest_json",+ _REGISTRY_CONTENT: "file_ingest_registry",+ }+)+++def _multipart_parts(request: Request) -> tuple[Message, ...]:+ envelope: Final = f"content-type: {request.headers['content-type']}\r\n\r\n".encode() + request.body+ parsed: Final = BytesParser(policy=HTTP).parsebytes(envelope)+ assert parsed.is_multipart(), request.headers["content-type"]+ return tuple(parsed.iter_parts())+++def _multipart_text(parts: tuple[Message, ...]) -> dict[str, str]:+ return {+ str(part.get_param("name", header="content-disposition")): part.get_payload(decode=True).decode()+ for part in parts+ if part.get_filename() is None+ }+++def _multipart_file(parts: tuple[Message, ...]) -> tuple[str, str, bytes]:+ (part,) = tuple(part for part in parts if part.get_filename() is not None)+ return (+ str(part.get_filename()),+ str(part.get_content_type()),+ part.get_payload(decode=True),+ )+++def _vector_store_reply(identity: str, name: str) -> Reply:+ return Reply(+ body=json.dumps(+ {+ "id": identity,+ "object": "vector_store",+ "created_at": 1700000000,+ "name": name,+ "file_counts": {+ "in_progress": 0,+ "completed": 0,+ "failed": 0,+ "cancelled": 0,+ "total": 0,+ },+ "status": "completed",+ "usage_bytes": 0,+ "expires_after": None,+ "expires_at": None,+ "last_active_at": None,+ "metadata": {},+ }+ ).encode()+ )+++def _file_reply(identity: str, filename: str, content: bytes) -> Reply:+ return Reply(+ body=json.dumps(+ {+ "id": identity,+ "object": "file",+ "bytes": len(content),+ "created_at": 1700000000,+ "filename": filename,+ "purpose": "assistants",+ "status": "processed",+ }+ ).encode()+ )+++def _attached_file_reply(store_id: str, file_id: str) -> Reply:+ return Reply(+ body=json.dumps(+ {+ "id": file_id,+ "object": "vector_store.file",+ "usage_bytes": 12,+ "created_at": 1700000001,+ "vector_store_id": store_id,+ "status": "completed",+ "last_error": None,+ "chunking_strategy": {"type": "auto"},+ "attributes": {},+ }+ ).encode()+ )+++def _assert_upload(request: Request, expected_content: bytes) -> tuple[str, str]:+ assert request.method == "POST"+ assert urlsplit(request.target).path == "/v1/files", request.target+ parts: Final = _multipart_parts(request)+ assert _multipart_text(parts) == {"purpose": "assistants"}+ filename, content_type, content = _multipart_file(parts)+ assert _GENERATED_FILENAME.fullmatch(filename), filename+ assert content_type == "text/plain", request.headers["content-type"]+ assert content == expected_content+ return filename, content_type+++def _no_registry_config(directory: Path) -> Path:+ config: Final = object_value(yaml.safe_load(PROXY_CONFIG.read_text()))+ without_registry: Final[Mapping[str, JsonValue]] = {+ key: value for key, value in config.items() if key != "vector_store_registry"+ }+ path: Final = directory / "proxy_no_vector_store_registry.yaml"+ path.write_text(yaml.safe_dump({**without_registry, "model_list": []}))+ return path+++def _new_store_provider(+ provider_key: str, store_id: str, store_name: str = "rag ingest contract"+) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ assert request.headers["authorization"] == f"Bearer {provider_key}"+ if request.method == "POST" and path == "/v1/vector_stores":+ assert JSON_OBJECT.validate_json(request.body) == {+ **_PROVIDER_CREATE_BODY,+ "name": store_name,+ }+ return _vector_store_reply(store_id, store_name)+ if request.method == "POST" and path == "/v1/files":+ parts: Final = _multipart_parts(request)+ assert _multipart_text(parts) == {"purpose": "assistants"}+ filename, content_type, content = _multipart_file(parts)+ assert _GENERATED_FILENAME.fullmatch(filename), filename+ assert content_type == "text/plain", request.headers["content-type"]+ file_id: Final = _INGEST_FILE_IDS.get(content)+ assert file_id is not None, content+ return _file_reply(file_id, filename, content)+ if request.method == "POST" and path == f"/v1/vector_stores/{store_id}/files":+ body: Final = JSON_OBJECT.validate_json(request.body)+ file_id: Final = str(body["file_id"])+ assert body == {"file_id": file_id, "chunking_strategy": {"type": "auto"}}+ assert file_id in {"file_ingest_multipart", "file_ingest_json"}+ return _attached_file_reply(store_id, file_id)+ return Reply(status=404, body=json.dumps({"error": request.target}).encode())++ return respond+++def _registered_store_provider(provider_key: str, store_id: str) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ assert request.headers["authorization"] == f"Bearer {provider_key}"+ if request.method == "POST" and path == "/v1/files":+ filename, _ = _assert_upload(request, _REGISTRY_CONTENT)+ return _file_reply("file_ingest_registry", filename, _REGISTRY_CONTENT)+ assert request.method == "POST"+ assert path == f"/v1/vector_stores/{store_id}/files", request.target+ body: Final = JSON_OBJECT.validate_json(request.body)+ assert body == {"file_id": "file_ingest_registry", "chunking_strategy": {"type": "auto"}}+ return _attached_file_reply(store_id, "file_ingest_registry")++ return respond+++def _ingest_options(name: str) -> dict[str, JsonValue]:+ return {"name": name, "vector_store": {"custom_llm_provider": "openai"}}+++def _ingest_response(response: httpx.Response, vector_store_id: str, file_id: str) -> None:+ assert response.status_code == 200, response.text+ body: Final = JSON_OBJECT.validate_json(response.content)+ assert body["vector_store_id"] == vector_store_id, response.text+ assert body["file_id"] == file_id, response.text+++def test_rag_ingest_request_multipart_json_and_registered_credentials(gateway: Gateway, tmp_path: Path) -> None:+ default_key: Final = f"ingest-default-{uuid.uuid4().hex}"+ registered_key: Final = f"ingest-registered-{uuid.uuid4().hex}"+ new_store_id: Final = f"vs_ingest_wire_{uuid.uuid4().hex}"+ registered_store_id: Final = f"vs_ingest_registry_{uuid.uuid4().hex}"+ config: Final = _no_registry_config(tmp_path)+ with (+ gateway_from_environment() as upstream_gateway,+ wire_server(_new_store_provider(default_key, new_store_id)) as default_wire,+ wire_server(_registered_store_provider(registered_key, registered_store_id)) as registered_wire,+ ):+ with owned_proxy(+ upstream_gateway,+ tmp_path,+ {+ "OPENAI_BASE_URL": f"{default_wire.url}/v1",+ "OPENAI_API_KEY": default_key,+ },+ config=config,+ remove_environment=("OPENAI_API_BASE",),+ workers=2,+ ) as owned:+ with owned.scenario() as scenario:+ multipart: Final = owned.request_multipart(+ "/v1/rag/ingest",+ {"request": json.dumps({"ingest_options": _ingest_options("rag ingest contract")})},+ {"file": ("ui-upload.txt", _MULTIPART_CONTENT, "text/plain")},+ )+ _ingest_response(multipart, new_store_id, "file_ingest_multipart")+ scenario.cleanups.callback(+ owned.post, "/vector_store/delete", {"vector_store_id": new_store_id}+ )++ json_upload: Final = owned.request(+ "POST",+ "/rag/ingest",+ {+ "ingest_options": _ingest_options("rag ingest contract"),+ "file": {+ "filename": "json-upload.txt",+ "content": base64.b64encode(_JSON_CONTENT).decode(),+ "content_type": "text/plain",+ },+ },+ )+ _ingest_response(json_upload, new_store_id, "file_ingest_json")++ default_requests: Final = default_wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in default_requests] == [+ ("POST", "/v1/vector_stores"),+ ("POST", "/v1/files"),+ ("POST", f"/v1/vector_stores/{new_store_id}/files"),+ ("POST", "/v1/vector_stores"),+ ("POST", "/v1/files"),+ ("POST", f"/v1/vector_stores/{new_store_id}/files"),+ ], default_requests+ assert JSON_OBJECT.validate_json(default_requests[0].body) == _PROVIDER_CREATE_BODY+ assert JSON_OBJECT.validate_json(default_requests[2].body) == {+ "file_id": "file_ingest_multipart",+ "chunking_strategy": {"type": "auto"},+ }+ assert JSON_OBJECT.validate_json(default_requests[3].body) == _PROVIDER_CREATE_BODY+ assert JSON_OBJECT.validate_json(default_requests[5].body) == {+ "file_id": "file_ingest_json",+ "chunking_strategy": {"type": "auto"},+ }+ assert all(+ request.headers["authorization"] == f"Bearer {default_key}" for request in default_requests+ )+ _assert_upload(default_requests[1], _MULTIPART_CONTENT)+ _assert_upload(default_requests[4], _JSON_CONTENT)++ registered: Final = owned.request(+ "POST",+ "/vector_store/new",+ {+ "vector_store_id": registered_store_id,+ "custom_llm_provider": "openai",+ "litellm_params": {+ "api_base": f"{registered_wire.url}/v1",+ "api_key": registered_key,+ },+ },+ )+ assert registered.status_code == 200, registered.text+ scenario.cleanups.callback(+ owned.post, "/vector_store/delete", {"vector_store_id": registered_store_id}+ )+ rejected_credentials: Final = owned.request_multipart(+ "/v1/rag/ingest",+ {+ "request": json.dumps(+ {+ "ingest_options": {+ "vector_store": {+ "vector_store_id": registered_store_id,+ "custom_llm_provider": "openai",+ "api_key": "caller-synthetic-key",+ },+ }+ }+ )+ },+ {"file": ("registered.txt", _REGISTRY_CONTENT, "text/plain")},+ )+ assert rejected_credentials.status_code == 400, rejected_credentials.text+ assert "api_key" in rejected_credentials.text, rejected_credentials.text+ assert default_wire.drain() == ()+ assert registered_wire.drain() == ()+ registered_ingest: Final = owned.request_multipart(+ "/v1/rag/ingest",+ {+ "request": json.dumps(+ {+ "ingest_options": {+ "vector_store": {+ "vector_store_id": registered_store_id,+ "custom_llm_provider": "openai",+ }+ }+ }+ )+ },+ {"file": ("registered.txt", _REGISTRY_CONTENT, "text/plain")},+ )+ _ingest_response(registered_ingest, registered_store_id, "file_ingest_registry")+ assert default_wire.drain() == ()+ registered_requests: Final = registered_wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in registered_requests] == [+ ("POST", "/v1/files"),+ ("POST", f"/v1/vector_stores/{registered_store_id}/files"),+ ], registered_requests+ assert all(+ request.headers["authorization"] == f"Bearer {registered_key}" for request in registered_requests+ )+ _assert_upload(registered_requests[0], _REGISTRY_CONTENT)+++def test_documented_multipart_ingest_options_is_honored(gateway: Gateway, tmp_path: Path) -> None:+ pytest.skip(+ "BUG: multipart -F ingest_options documented on /v1/rag/ingest is rejected with 400 saying vector_store configuration is missing"+ )++ provider_key: Final = f"ingest-docs-{uuid.uuid4().hex}"+ store_id: Final = f"vs_ingest_docs_{uuid.uuid4().hex}"++ with (+ gateway_from_environment() as upstream_gateway,+ wire_server(_new_store_provider(provider_key, store_id, "docs ingest contract")) as wire,+ ):+ with owned_proxy(+ upstream_gateway,+ tmp_path,+ {"OPENAI_BASE_URL": f"{wire.url}/v1", "OPENAI_API_KEY": provider_key},+ config=_no_registry_config(tmp_path),+ remove_environment=("OPENAI_API_BASE",),+ ) as owned:+ with owned.scenario() as scenario:+ response: Final = owned.request_multipart(+ "/v1/rag/ingest",+ {"ingest_options": json.dumps(_ingest_options("docs ingest contract"))},+ {"file": ("docs.txt", _MULTIPART_CONTENT, "text/plain")},+ )+ _ingest_response(response, store_id, "file_ingest_multipart")+ scenario.cleanups.callback(+ owned.post, "/vector_store/delete", {"vector_store_id": store_id}+ )++ requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in requests] == [+ ("POST", "/v1/vector_stores"),+ ("POST", "/v1/files"),+ ("POST", f"/v1/vector_stores/{store_id}/files"),+ ], requests+ assert all(+ request.headers["authorization"] == f"Bearer {provider_key}" for request in requests+ )+ _assert_upload(requests[1], _MULTIPART_CONTENT)diff --git a/tests/integration/providers/test_vector_store_create_wire.py b/tests/integration/providers/test_vector_store_create_wire.pynew file mode 100644index 00000000000..fd166da1763--- /dev/null+++ b/tests/integration/providers/test_vector_store_create_wire.py@@ -0,0 +1,465 @@+import json+import uuid+from concurrent.futures import ThreadPoolExecutor+from functools import partial+from pathlib import Path+from typing import Final+from urllib.parse import parse_qs, urlsplit++import httpx+import pytest+from integration._support.client import (+ Gateway,+ Scenario,+ eventually,+ gateway_from_environment,+ object_value,+ 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 openai import OpenAI+from pydantic import BaseModel, JsonValue, TypeAdapter++JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_CHUNKING: Final[dict[str, JsonValue]] = {+ "type": "static",+ "static": {"max_chunk_size_tokens": 800, "chunk_overlap_tokens": 400},+}+_CREATE_FIELDS: Final[dict[str, JsonValue]] = {+ "name": "integration vector store",+ "file_ids": ["file-wire-create"],+ "expires_after": {"anchor": "last_active_at", "days": 7},+ "chunking_strategy": _CHUNKING,+ "metadata": {"team": "blue"},+}+++class _FileCounts(BaseModel):+ in_progress: int+ completed: int+ failed: int+ cancelled: int+ total: int+++class _VectorStoreResponse(BaseModel):+ id: str+ object: str+ created_at: int+ name: str+ file_counts: _FileCounts+ status: str+ usage_bytes: int+ expires_after: dict[str, JsonValue] | None+ expires_at: int | None+ last_active_at: int | None+ metadata: dict[str, str]+++def _vector_store_reply(identity: str) -> Reply:+ return Reply(+ body=json.dumps(+ {+ "id": identity,+ "object": "vector_store",+ "created_at": 1700000000,+ "name": _CREATE_FIELDS["name"],+ "file_counts": {+ "in_progress": 0,+ "completed": 1,+ "failed": 0,+ "cancelled": 0,+ "total": 1,+ },+ "status": "completed",+ "usage_bytes": 12,+ "expires_after": _CREATE_FIELDS["expires_after"],+ "expires_at": None,+ "last_active_at": None,+ "metadata": _CREATE_FIELDS["metadata"],+ }+ ).encode()+ )+++def _assert_create_request(+ request: Request,+ expected_file_ids: list[str],+ provider_key: str,+) -> None:+ assert request.method == "POST"+ assert urlsplit(request.target).path == "/v1/vector_stores", request.target+ assert parse_qs(urlsplit(request.target).query) == {}, request.target+ assert request.headers["authorization"] == f"Bearer {provider_key}"+ body: Final = JSON_OBJECT.validate_json(request.body)+ assert {key: value for key, value in body.items() if key != "metadata"} == {+ "name": _CREATE_FIELDS["name"],+ "file_ids": expected_file_ids,+ "expires_after": _CREATE_FIELDS["expires_after"],+ "chunking_strategy": _CHUNKING,+ }, request.body.decode()+++def _upload_managed_file(+ gateway: Gateway,+ key: str,+ model: str,+ filename: str,+ content: bytes,+) -> str:+ uploaded: Final = gateway.request_multipart(+ "/v1/files",+ {"purpose": "user_data", "target_model_names": model},+ {"file": (filename, content, "text/plain")},+ key=key,+ )+ assert uploaded.status_code == 200, uploaded.text+ return string_value(JSON_OBJECT.validate_json(uploaded.content)["id"])+++def _deployment(scenario: Scenario, wire_url: str, provider_key: str) -> str:+ return scenario.model(api_base=f"{wire_url}/v1", api_key=provider_key)+++def _deployment_id(model: str) -> str:+ rows: Final = read_rows(+ 'SELECT model_id FROM "LiteLLM_ProxyModelTable" WHERE model_name = %s '+ "OR model_info->>'team_public_model_name' = %s",+ (model, model),+ )+ assert len(rows) == 1, f"Expected one deployment for {model!r}, found {rows}"+ return string_value(rows[0]["model_id"])+++def _worker_has_deployment(gateway: Gateway, deployment_id: str, _: int) -> bool:+ with httpx.Client(base_url=gateway.client.base_url, timeout=15, trust_env=False) as client:+ response: Final = client.get(+ "/model/info",+ params={"litellm_model_id": deployment_id},+ headers={"Authorization": f"Bearer {gateway.key}"},+ )+ if response.status_code == 200:+ return True+ assert response.status_code == 400, response.text+ assert "not found on litellm proxy" in response.text.lower(), response.text+ return False+++def _wait_until_every_worker_serves(gateway: Gateway, model: str) -> None:+ deployment_id: Final = _deployment_id(model)++ def every_worker_serves() -> bool:+ with ThreadPoolExecutor(max_workers=16) as pool:+ rounds: Final = tuple(+ tuple(pool.map(partial(_worker_has_deployment, gateway, deployment_id), range(16))) for _ in range(2)+ )+ return all(has_deployment for round_ in rounds for has_deployment in round_)++ eventually(every_worker_serves, lambda served: served, seconds=90)+++def test_vector_store_create_forwards_chunking_strategy_on_sdk_and_alias_routes(gateway: Gateway) -> None:+ provider_key: Final = f"provider-create-{uuid.uuid4().hex}"+ expected_sdk_response: Final = {+ "id": "vs_created",+ "object": "vector_store",+ "created_at": 1700000000,+ "name": _CREATE_FIELDS["name"],+ "file_counts": {+ "in_progress": 0,+ "completed": 1,+ "failed": 0,+ "cancelled": 0,+ "total": 1,+ },+ "status": "completed",+ "usage_bytes": 12,+ "expires_after": _CREATE_FIELDS["expires_after"],+ "expires_at": None,+ "last_active_at": None,+ "metadata": _CREATE_FIELDS["metadata"],+ }++ def respond(_: Request) -> Reply:+ return _vector_store_reply("vs_created")++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ model: Final = _deployment(scenario, wire.url, provider_key)+ _wait_until_every_worker_serves(gateway, model)+ wire.drain()+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=gateway.key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ sdk_response: Final = client.vector_stores.create(+ name=str(_CREATE_FIELDS["name"]),+ file_ids=["file-wire-create"],+ expires_after={"anchor": "last_active_at", "days": 7},+ chunking_strategy=_CHUNKING,+ metadata={"team": "blue"},+ extra_body={"model": model},+ )+ assert sdk_response.model_dump(exclude_unset=True) == expected_sdk_response++ alias_response: Final = gateway.request(+ "POST",+ "/vector_stores",+ {"model": model, **_CREATE_FIELDS},+ )+ assert alias_response.status_code == 200, alias_response.text+ assert _VectorStoreResponse.model_validate_json(alias_response.content).model_dump() == {+ **expected_sdk_response,+ }+ requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in requests] == [+ ("POST", "/v1/vector_stores"),+ ("POST", "/v1/vector_stores"),+ ]+ for request in requests:+ _assert_create_request(request, ["file-wire-create"], provider_key)+ body: Final = JSON_OBJECT.validate_json(request.body)+ metadata_value: Final = body.get("metadata")+ assert metadata_value is not None, request.body.decode()+ metadata: Final = object_value(metadata_value)+ assert metadata.get("team") == "blue", request.body.decode()+++def test_vector_store_create_routes_by_the_model_query_parameter(gateway: Gateway) -> None:+ pytest.skip(+ "BUG: vector store create ignores the ?model= query parameter and falls through to the default openai provider"+ )++ provider_key: Final = f"provider-query-{uuid.uuid4().hex}"+ expected_sdk_response: Final = {+ "id": "vs_query_model",+ "object": "vector_store",+ "created_at": 1700000000,+ "name": _CREATE_FIELDS["name"],+ "file_counts": {+ "in_progress": 0,+ "completed": 1,+ "failed": 0,+ "cancelled": 0,+ "total": 1,+ },+ "status": "completed",+ "usage_bytes": 12,+ "expires_after": _CREATE_FIELDS["expires_after"],+ "expires_at": None,+ "last_active_at": None,+ "metadata": _CREATE_FIELDS["metadata"],+ }++ def respond(_: Request) -> Reply:+ return _vector_store_reply("vs_query_model")++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ model: Final = _deployment(scenario, wire.url, provider_key)+ _wait_until_every_worker_serves(gateway, model)+ wire.drain()+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=gateway.key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ sdk_response: Final = client.vector_stores.create(+ name=str(_CREATE_FIELDS["name"]),+ file_ids=["file-wire-create"],+ expires_after={"anchor": "last_active_at", "days": 7},+ chunking_strategy=_CHUNKING,+ metadata={"team": "blue"},+ extra_query={"model": model},+ )+ assert sdk_response.model_dump(exclude_unset=True) == expected_sdk_response+ requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in requests] == [+ ("POST", "/v1/vector_stores")+ ]+ (request,) = requests+ _assert_create_request(request, ["file-wire-create"], provider_key)+ body: Final = JSON_OBJECT.validate_json(request.body)+ metadata_value: Final = body.get("metadata")+ assert metadata_value is not None, request.body.decode()+ metadata: Final = object_value(metadata_value)+ assert metadata.get("team") == "blue", request.body.decode()+++def test_vector_store_create_without_model_uses_the_default_openai_credentials(+ gateway: Gateway, tmp_path: Path+) -> None:+ provider_key: Final = f"provider-default-{uuid.uuid4().hex}"+ expected_sdk_response: Final = {+ "id": "vs_default_openai",+ "object": "vector_store",+ "created_at": 1700000000,+ "name": _CREATE_FIELDS["name"],+ "file_counts": {+ "in_progress": 0,+ "completed": 1,+ "failed": 0,+ "cancelled": 0,+ "total": 1,+ },+ "status": "completed",+ "usage_bytes": 12,+ "expires_after": _CREATE_FIELDS["expires_after"],+ "expires_at": None,+ "last_active_at": None,+ "metadata": _CREATE_FIELDS["metadata"],+ }++ def respond(_: Request) -> Reply:+ return _vector_store_reply("vs_default_openai")++ with (+ gateway_from_environment() as upstream_gateway,+ wire_server(respond) as wire,+ ):+ with owned_proxy(+ upstream_gateway,+ tmp_path,+ {"OPENAI_BASE_URL": f"{wire.url}/v1", "OPENAI_API_KEY": provider_key},+ remove_environment=("OPENAI_API_BASE",),+ ) as owned:+ with OpenAI(+ base_url=f"{str(owned.client.base_url).rstrip('/')}/v1",+ api_key=owned.key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ sdk_response: Final = client.vector_stores.create(+ name=str(_CREATE_FIELDS["name"]),+ file_ids=["file-wire-create"],+ expires_after={"anchor": "last_active_at", "days": 7},+ chunking_strategy=_CHUNKING,+ metadata={"team": "blue"},+ )+ assert sdk_response.model_dump(exclude_unset=True) == expected_sdk_response+ requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in requests] == [+ ("POST", "/v1/vector_stores")+ ]+ (request,) = requests+ _assert_create_request(request, ["file-wire-create"], provider_key)+ body: Final = JSON_OBJECT.validate_json(request.body)+ metadata_value: Final = body.get("metadata")+ assert metadata_value is not None, request.body.decode()+ metadata: Final = object_value(metadata_value)+ assert metadata.get("team") == "blue", request.body.decode()+++def test_vector_store_create_translates_managed_file_ids(gateway: Gateway) -> None:+ pytest.skip("BUG: vector store create forwards managed file IDs to the provider without translating them")++ provider_key: Final = f"provider-create-managed-{uuid.uuid4().hex}"+ provider_file_id: Final = f"file-create-managed-{uuid.uuid4().hex}"+ raw_file_id: Final = f"file-create-raw-{uuid.uuid4().hex}"+ filename: Final = f"create-{uuid.uuid4().hex}.txt"+ file_content: Final = b"managed vector store create\n"+ provider_store_id: Final = f"vs-created-{uuid.uuid4().hex}"++ def respond(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ assert request.headers["authorization"] == f"Bearer {provider_key}"+ if request.method == "POST" and path == "/v1/files":+ assert f'filename="{filename}"'.encode() in request.body, request.body[:200]+ assert file_content in request.body, request.body[:200]+ assert b'name="purpose"' in request.body, request.body[:200]+ assert b"user_data" in request.body, request.body[:200]+ return Reply(+ body=json.dumps(+ {+ "id": provider_file_id,+ "object": "file",+ "bytes": len(file_content),+ "created_at": 1700000000,+ "filename": filename,+ "purpose": "user_data",+ "status": "processed",+ }+ ).encode()+ )+ _assert_create_request(request, [raw_file_id, provider_file_id], provider_key)+ return _vector_store_reply(provider_store_id)++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ model: Final = _deployment(scenario, wire.url, provider_key)+ _wait_until_every_worker_serves(gateway, model)+ wire.drain()+ team: Final = scenario.team(models=[model])+ user: Final = scenario.member(team)+ key: Final = scenario.key(team_id=team, user_id=user, models=[model])+ managed_file_id: Final = _upload_managed_file(gateway, key, model, filename, file_content)+ file_ids: Final = [raw_file_id, managed_file_id]+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ response: Final = client.vector_stores.create(+ name=str(_CREATE_FIELDS["name"]),+ file_ids=file_ids,+ expires_after={"anchor": "last_active_at", "days": 7},+ chunking_strategy=_CHUNKING,+ metadata={"team": "blue"},+ extra_body={"model": model},+ )+ assert response.id == provider_store_id, str(response)+ requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in requests] == [+ ("POST", "/v1/files"),+ ("POST", "/v1/vector_stores"),+ ], requests+++def test_vector_store_create_forwards_only_caller_metadata(gateway: Gateway) -> None:+ pytest.skip(+ "BUG: vector store create forwards proxy-internal metadata (user_api_key_hash, endpoint, api_base, ...) to the provider"+ )++ provider_key: Final = f"provider-create-metadata-{uuid.uuid4().hex}"+ provider_id: Final = f"vs-metadata-{uuid.uuid4().hex}"++ def respond(request: Request) -> Reply:+ assert request.method == "POST"+ assert urlsplit(request.target).path == "/v1/vector_stores", request.target+ assert request.headers["authorization"] == f"Bearer {provider_key}"+ assert JSON_OBJECT.validate_json(request.body) == {+ "name": _CREATE_FIELDS["name"],+ "file_ids": _CREATE_FIELDS["file_ids"],+ "expires_after": _CREATE_FIELDS["expires_after"],+ "chunking_strategy": _CHUNKING,+ "metadata": {"team": "blue"},+ }, request.body.decode()+ return _vector_store_reply(provider_id)++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ model: Final = _deployment(scenario, wire.url, provider_key)+ _wait_until_every_worker_serves(gateway, model)+ wire.drain()+ key: Final = scenario.key(models=[model])+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ response: Final = client.vector_stores.create(+ name=str(_CREATE_FIELDS["name"]),+ file_ids=["file-wire-create"],+ expires_after={"anchor": "last_active_at", "days": 7},+ chunking_strategy=_CHUNKING,+ metadata={"team": "blue"},+ extra_body={"model": model},+ )+ assert response.id == provider_id, str(response)+ requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in requests] == [+ ("POST", "/v1/vector_stores")+ ], requestsdiff --git a/tests/integration/providers/test_vector_store_search_wire.py b/tests/integration/providers/test_vector_store_search_wire.pynew file mode 100644index 00000000000..accefe1bcf8--- /dev/null+++ b/tests/integration/providers/test_vector_store_search_wire.py@@ -0,0 +1,141 @@+import json+import uuid+from typing import Final+from urllib.parse import urlsplit++import httpx+from integration._support.client import Gateway+from integration._support.wire import Reply, Request, wire_server+from openai import OpenAI+from pydantic import BaseModel, JsonValue, TypeAdapter++JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_SEARCH_PATH_SUFFIX: Final = "/vector_stores/{vector_store_id}/search"+_FILTERS: Final[dict[str, JsonValue]] = {+ "type": "and",+ "filters": [{"type": "eq", "key": "tenant", "value": "a"}],+}+_SEARCH_BODY: Final[dict[str, JsonValue]] = {+ "query": ["a", "b"],+ "filters": _FILTERS,+ "max_num_results": 3,+ "ranking_options": {"ranker": "auto", "score_threshold": 0.2},+ "rewrite_query": True,+}+_ALIAS_BODY: Final[dict[str, JsonValue]] = {+ "query": "c",+ "filters": None,+ "max_num_results": None,+ "ranking_options": None,+ "rewrite_query": None,+}+_ALIAS_REQUEST_BODY: Final[dict[str, JsonValue]] = {"query": "c"}+_SEARCH_RESULT: Final[dict[str, JsonValue]] = {+ "file_id": "file-search-wire",+ "filename": "search.txt",+ "score": 0.91,+ "attributes": {"tenant": "a"},+ "content": [{"type": "text", "text": "matching content"}],+}+++class _SearchContent(BaseModel):+ type: str+ text: str+++class _SearchResult(BaseModel):+ file_id: str+ filename: str+ score: float+ attributes: dict[str, str]+ content: tuple[_SearchContent, ...]+++class _SearchPage(BaseModel):+ object: str+ search_query: str+ data: tuple[_SearchResult, ...]+ has_more: bool+ next_page: str | None+++def _search_reply(query: str) -> Reply:+ return Reply(+ body=json.dumps(+ {+ "object": "vector_store.search_results.page",+ "search_query": query,+ "data": [_SEARCH_RESULT],+ "has_more": False,+ "next_page": None,+ }+ ).encode()+ )+++def test_vector_store_search_forwards_all_search_fields_on_both_routes(gateway: Gateway) -> None:+ store_id: Final = f"vs_search_{uuid.uuid4().hex}"+ registry_key: Final = f"registry-search-{uuid.uuid4().hex}"+ search_path: Final = _SEARCH_PATH_SUFFIX.format(vector_store_id=store_id)+ expected_sdk_response: Final = {+ "object": "vector_store.search_results.page",+ "search_query": "a b",+ "data": [_SEARCH_RESULT],+ "has_more": False,+ "next_page": None,+ }+ expected_alias_response: Final = {+ **expected_sdk_response,+ "search_query": "c",+ }++ def respond(request: Request) -> Reply:+ assert request.method == "POST"+ assert urlsplit(request.target).path == f"/v1{search_path}", request.target+ assert request.headers["authorization"] == f"Bearer {registry_key}"+ body: Final = JSON_OBJECT.validate_json(request.body)+ if body.get("query") == ["a", "b"]:+ assert body == _SEARCH_BODY+ return _search_reply("a b")+ assert body == _ALIAS_BODY+ return _search_reply("c")++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ registered: Final = gateway.request(+ "POST",+ "/vector_store/new",+ {+ "vector_store_id": store_id,+ "custom_llm_provider": "openai",+ "litellm_params": {"api_base": f"{wire.url}/v1", "api_key": registry_key},+ },+ )+ assert registered.status_code == 200, registered.text+ scenario.cleanups.callback(gateway.post, "/vector_store/delete", {"vector_store_id": store_id})++ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=gateway.key,+ http_client=httpx.Client(trust_env=False),+ max_retries=0,+ ) as client:+ sdk_response: Final = client.vector_stores.search(+ store_id,+ query=["a", "b"],+ filters=_FILTERS,+ max_num_results=3,+ ranking_options={"ranker": "auto", "score_threshold": 0.2},+ rewrite_query=True,+ )+ assert sdk_response.model_dump(exclude_unset=True) == expected_sdk_response++ alias_response: Final = gateway.request("POST", f"{search_path}", _ALIAS_REQUEST_BODY)+ assert alias_response.status_code == 200, alias_response.text+ assert _SearchPage.model_validate_json(alias_response.content).model_dump(mode="json") == expected_alias_response++ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", f"/v1{search_path}"),+ ("POST", f"/v1{search_path}"),+ ]