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): pin assistants and evals endpoint contracts (#44734)
devin-ai-integration[bot]1047a450bfe6
diff --git a/tests/integration/compatibility/test_missing_body_param_status.py b/tests/integration/compatibility/test_missing_body_param_status.pyindex f809a67c0ce..a452110f138 100644--- a/tests/integration/compatibility/test_missing_body_param_status.py+++ b/tests/integration/compatibility/test_missing_body_param_status.py@@ -24,8 +24,10 @@ from integration._support.database import read_rowsfrom integration._support.process import owned_proxy_process, paused, stop_childfrom integration._support.upstream import ScenarioHandle, delete_scenario, register_scenariofrom integration._support.wire import Reply, Request, Wire, wire_server-from openai import AsyncOpenAI, BadRequestError, OpenAI+from openai import APIStatusError, AsyncOpenAI, BadRequestError, OpenAIfrom openai.types import Video+from openai.types.eval_create_response import EvalCreateResponse as _Eval+from openai.types.evals.run_create_response import RunCreateResponse as _EvalRunfrom pydantic import JsonValuefrom litellm.responses.utils import ResponsesAPIRequestUtils@@ -42,6 +44,64 @@ from tests.integration.cost_calculation.cost_tracking_case import ()_Route = tuple[str, str, tuple[str, ...], dict[str, JsonValue], str]+_EVAL_DATA_SOURCE_CONFIG: Final[dict[str, JsonValue]] = {+ "type": "custom",+ "item_schema": {"type": "object", "properties": {"a": {"type": "string"}}},+}+_EVAL_DATA_SOURCE_CONFIG_RESPONSE: Final[dict[str, JsonValue]] = {+ "type": "custom",+ "schema": {"type": "object", "properties": {"a": {"type": "string"}}},+}+_EVAL_TESTING_CRITERIA: Final[list[JsonValue]] = [+ {"type": "string_check", "name": "exact", "input": "{{item.a}}", "reference": "{{item.a}}", "operation": "eq"}+]+_EVAL_RUN_DATA_SOURCE: Final[dict[str, JsonValue]] = {+ "type": "jsonl",+ "source": {"type": "file_id", "id": "file-abc"},+}+_EVAL_CREATE_REQUEST: Final[dict[str, JsonValue]] = {+ "data_source_config": _EVAL_DATA_SOURCE_CONFIG,+ "testing_criteria": _EVAL_TESTING_CRITERIA,+ "name": "nightly",+ "metadata": {"suite": "nightly"},+}+_EVAL_RUN_REQUEST: Final[dict[str, JsonValue]] = {+ "data_source": _EVAL_RUN_DATA_SOURCE,+ "name": "run-1",+ "metadata": {"suite": "nightly"},+}+_EVAL_CREATE_UPSTREAM_RESPONSE: Final[dict[str, JsonValue]] = {+ "id": "eval_abc",+ "object": "eval",+ "created_at": 1700000000,+ "name": "nightly",+ "data_source_config": _EVAL_DATA_SOURCE_CONFIG_RESPONSE,+ "testing_criteria": _EVAL_TESTING_CRITERIA,+ "metadata": {"suite": "nightly"},+}+_EVAL_CREATE_RESPONSE: Final[dict[str, JsonValue]] = {+ **_EVAL_CREATE_UPSTREAM_RESPONSE,+ "updated_at": None,+}+_EVAL_RUN_RESPONSE: Final[dict[str, JsonValue]] = {+ "id": "run_abc",+ "object": "eval.run",+ "created_at": 1700000001,+ "eval_id": "eval_abc",+ "started_at": None,+ "completed_at": None,+ "data_source": _EVAL_RUN_DATA_SOURCE,+ "error": None,+ "per_model_usage": [],+ "per_testing_criteria_results": [],+ "report_url": "https://example.invalid/evals/run_abc",+ "result_counts": {"errored": 0, "failed": 0, "passed": 0, "total": 0},+ "shared_with_openai": None,+ "name": "run-1",+ "model": "gpt-4o-mini",+ "metadata": {"suite": "nightly"},+ "status": "queued",+}_ROUTES: Final[dict[str, _Route]] = {"acompletion": ("/v1/chat/completions",@@ -1648,6 +1708,94 @@ def test_upstream_pause_and_worker_kill_preserve_required_body_status(assert recovered.status_code == 200, recovered.text+def test_eval_create_and_run_forward_client_metadata(gateway: Gateway) -> None:+ pytest.skip(+ "BUG: evals.create and evals.runs.create drop the client metadata upstream, "+ "and the run response model is overwritten with the routing alias"+ )++ def respond(request: Request) -> Reply:+ if request.method == "POST" and request.target == "/v1/evals":+ return Reply(body=json.dumps(_EVAL_CREATE_UPSTREAM_RESPONSE).encode())+ if request.method == "POST" and request.target == "/v1/evals/eval_abc/runs":+ return Reply(body=json.dumps(_EVAL_RUN_RESPONSE).encode())+ return Reply(status=404, body=b'{"error":"unexpected upstream request"}')++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ alias: Final = scenario.model(model="openai/gpt-4o-mini", api_base=wire.url, api_key="synthetic-openai-key")+ eventually(+ lambda: gateway.request(+ "POST",+ "/v1/chat/completions",+ {"model": alias, "messages": [{"role": "user", "content": "model readiness"}]},+ ),+ lambda response: not (response.status_code == 400 and "Invalid model name" in response.text),+ seconds=30,+ )+ wire.drain()+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1", api_key=gateway.key, max_retries=0+ ) as client:+ try:+ create_raw: Final = client.evals.with_raw_response.create(+ name="nightly",+ data_source_config=_EVAL_DATA_SOURCE_CONFIG,+ testing_criteria=_EVAL_TESTING_CRITERIA,+ metadata={"suite": "nightly"},+ extra_body={"model": alias},+ )+ except APIStatusError as error:+ create_error_text: Final = error.response.text+ create_failed_requests: Final = wire.drain()+ assert [(request.method, request.target) for request in create_failed_requests] == [+ ("POST", "/v1/evals")+ ], create_error_text+ assert create_failed_requests[0].headers["authorization"] == "Bearer synthetic-openai-key", (+ create_error_text+ )+ assert json.loads(create_failed_requests[0].body) == _EVAL_CREATE_REQUEST, create_error_text+ pytest.fail(f"SDK Eval creation failed with HTTP {error.response.status_code}: {create_error_text}")+ try:+ run_raw: Final = client.evals.runs.with_raw_response.create(+ "eval_abc",+ data_source=_EVAL_RUN_DATA_SOURCE,+ name="run-1",+ metadata={"suite": "nightly"},+ extra_body={"model": alias},+ )+ except APIStatusError as error:+ run_error_text: Final = error.response.text+ run_failed_requests: Final = wire.drain()+ assert [(request.method, request.target) for request in run_failed_requests] == [+ ("POST", "/v1/evals"),+ ("POST", "/v1/evals/eval_abc/runs"),+ ], run_error_text+ assert tuple(request.headers["authorization"] for request in run_failed_requests) == (+ "Bearer synthetic-openai-key",+ "Bearer synthetic-openai-key",+ ), run_error_text+ assert json.loads(run_failed_requests[0].body) == _EVAL_CREATE_REQUEST, run_error_text+ assert json.loads(run_failed_requests[1].body) == _EVAL_RUN_REQUEST, run_error_text+ pytest.fail(f"SDK Eval run creation failed with HTTP {error.response.status_code}: {run_error_text}")+ response_text: Final = "\n".join((create_raw.http_response.text, run_raw.http_response.text))+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/evals"),+ ("POST", "/v1/evals/eval_abc/runs"),+ ], response_text+ assert tuple(request.headers["authorization"] for request in requests) == (+ "Bearer synthetic-openai-key",+ "Bearer synthetic-openai-key",+ ), response_text+ assert json.loads(requests[0].body) == _EVAL_CREATE_REQUEST, response_text+ assert json.loads(requests[1].body) == _EVAL_RUN_REQUEST, response_text+ assert (create_raw.status_code, run_raw.status_code) == (200, 200), response_text+ assert isinstance(create_raw.parse(), _Eval), response_text+ assert json.loads(create_raw.http_response.text) == _EVAL_CREATE_RESPONSE, response_text+ assert isinstance(run_raw.parse(), _EvalRun), response_text+ assert json.loads(run_raw.http_response.text) == _EVAL_RUN_RESPONSE, response_text++_VIDEO_UPSTREAM_ID: Final = "video_upstream"_VIDEO_PROVIDER_KEY: Final = "video-provider-key"_VIDEO_BODY: Final = {diff --git a/tests/integration/providers/test_assistants_evals_wire.py b/tests/integration/providers/test_assistants_evals_wire.pynew file mode 100644index 00000000000..02f7307e725--- /dev/null+++ b/tests/integration/providers/test_assistants_evals_wire.py@@ -0,0 +1,343 @@+from __future__ import annotations++import json+from pathlib import Path+from typing import Final+from urllib.parse import parse_qs, urlsplit++import pytest+import yaml+from integration._support.client import Gateway+from integration._support.process import owned_proxy+from integration._support.wire import Reply, Request, wire_server+from openai import APIStatusError, OpenAI+from openai.types.beta.thread import Thread as _Thread+from openai.types.beta.threads.message import Message as _Message+from openai.types.beta.threads.run import Run as _Run+from pydantic import JsonValue++_THREAD: Final[dict[str, JsonValue]] = {+ "id": "thread_abc",+ "object": "thread",+ "created_at": 1700000000,+ "metadata": {"project": "alpha"},+ "tool_resources": {"code_interpreter": {"file_ids": ["file-abc"]}, "file_search": None},+}+_MESSAGE: Final[dict[str, JsonValue]] = {+ "id": "msg_abc",+ "assistant_id": None,+ "attachments": [{"file_id": "file-abc", "tools": [{"type": "file_search"}]}],+ "completed_at": None,+ "object": "thread.message",+ "content": [{"type": "text", "text": {"value": "Summarize the attachment", "annotations": []}}],+ "created_at": 1700000001,+ "incomplete_at": None,+ "incomplete_details": None,+ "metadata": {"turn": "2"},+ "role": "user",+ "run_id": None,+ "status": "completed",+ "thread_id": "thread_abc",+}+_IMAGE_PARTS: Final[list[JsonValue]] = [+ {"type": "text", "text": "Compare these"},+ {"type": "image_file", "image_file": {"file_id": "file-img", "detail": "low"}},+ {"type": "image_url", "image_url": {"url": "https://example.invalid/chart.png", "detail": "high"}},+]+_ATTACHMENTS: Final[list[JsonValue]] = [{"file_id": "file-abc", "tools": [{"type": "file_search"}]}]+_THREAD_MESSAGES: Final[tuple[dict[str, JsonValue], ...]] = (+ {"role": "user", "content": "What is in the report?", "metadata": {"turn": "1"}},+ {+ "role": "user",+ "content": [{"type": "text", "text": "What is in the report?"}],+ "attachments": _ATTACHMENTS,+ "metadata": {"turn": "1"},+ },+ {"role": "user", "content": _IMAGE_PARTS, "attachments": _ATTACHMENTS, "metadata": {"turn": "1"}},+)+_RUN_TOOL_FUNCTION: Final[dict[str, JsonValue]] = {+ "name": "lookup",+ "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]},+}+_RAW_RUN_REQUEST: Final[dict[str, JsonValue]] = {+ "assistant_id": "asst_abc",+ "tools": [{"type": "function", "function": _RUN_TOOL_FUNCTION}],+ "tool_choice": {"type": "function", "function": {"name": "lookup"}},+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "answer",+ "schema": {"type": "object", "properties": {"answer": {"type": "string"}}, "required": ["answer"]},+ "strict": True,+ },+ },+}+_RUN: Final[dict[str, JsonValue]] = {+ "id": "run_abc",+ "assistant_id": "asst_abc",+ "cancelled_at": None,+ "completed_at": None,+ "created_at": 1700000002,+ "expires_at": None,+ "failed_at": None,+ "incomplete_details": None,+ "instructions": "Be terse",+ "last_error": None,+ "max_completion_tokens": 50,+ "max_prompt_tokens": 500,+ "metadata": {"run": "r1"},+ "model": "gpt-4o",+ "object": "thread.run",+ "parallel_tool_calls": False,+ "required_action": None,+ "response_format": {"type": "json_object"},+ "started_at": None,+ "status": "queued",+ "thread_id": "thread_abc",+ "tool_choice": "auto",+ "tools": [{"type": "code_interpreter"}],+ "truncation_strategy": {"type": "last_messages", "last_messages": 4},+ "usage": None,+ "temperature": 0.3,+ "top_p": 0.9,+}+_RUN_REQUEST: Final[dict[str, JsonValue]] = {+ "assistant_id": "asst_abc",+ "instructions": "Be terse",+ "additional_instructions": "Cite sources",+ "additional_messages": [{"role": "user", "content": "Also check page 2"}],+ "metadata": {"run": "r1"},+ "model": "gpt-4o",+ "tools": [{"type": "code_interpreter"}],+ "temperature": 0.3,+ "top_p": 0.9,+ "max_prompt_tokens": 500,+ "max_completion_tokens": 50,+ "truncation_strategy": {"type": "last_messages", "last_messages": 4},+ "tool_choice": "auto",+ "response_format": {"type": "json_object"},+ "parallel_tool_calls": False,+ "reasoning_effort": "low",+}+++def _assistant_config(tmp_path: Path, api_base: str) -> Path:+ config: Final[dict[str, JsonValue]] = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())+ config["assistant_settings"] = {+ "custom_llm_provider": "openai",+ "litellm_params": {"api_base": api_base, "api_key": "synthetic-openai-key"},+ }+ config_path: Final = tmp_path / "assistants_evals.yaml"+ config_path.write_text(yaml.safe_dump(config), encoding="utf-8")+ return config_path+++def _respond(request: Request) -> Reply:+ path: Final = request.target.partition("?")[0]+ responses: Final = {+ "/v1/threads": _THREAD,+ "/v1/threads/thread_abc/messages": _MESSAGE,+ "/v1/threads/thread_abc/runs": _RUN,+ }+ if request.method != "POST" or path not in responses:+ return Reply(status=404, body=b'{"error":"unexpected upstream request"}')+ return Reply(body=json.dumps(responses[path]).encode())++[email protected]("message", _THREAD_MESSAGES, ids=("string", "parts-attachments", "image-parts-attachments"))[email protected]("prefix", ("", "/v1"), ids=("root-alias", "v1-alias"))+def test_create_thread_forwards_sdk_body(+ gateway: Gateway, tmp_path: Path, prefix: str, message: dict[str, JsonValue]+) -> None:+ pytest.skip("BUG: POST /threads reaches the upstream with body {} and drops messages, metadata and tool_resources")+ thread_request: Final[dict[str, JsonValue]] = {+ "messages": [message],+ "metadata": {"project": "alpha"},+ "tool_resources": {"code_interpreter": {"file_ids": ["file-abc"]}},+ }+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ base_url: Final = f"{str(candidate.client.base_url).rstrip('/')}{prefix}"+ with OpenAI(base_url=base_url, api_key=candidate.key, max_retries=0) as client:+ try:+ raw: Final = client.beta.threads.with_raw_response.create(+ messages=[message],+ metadata={"project": "alpha"},+ tool_resources={"code_interpreter": {"file_ids": ["file-abc"]}},+ )+ except APIStatusError as error:+ failure_text: Final = error.response.text+ failed_requests: Final = wire.drain()+ assert [(request.method, request.target) for request in failed_requests] == [+ ("POST", "/v1/threads")+ ], failure_text+ assert json.loads(failed_requests[0].body) == thread_request, failure_text+ pytest.fail(f"SDK thread creation failed with HTTP {error.response.status_code}: {failure_text}")+ assert raw.status_code == 200, raw.http_response.text+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [("POST", "/v1/threads")], (+ raw.http_response.text+ )+ assert json.loads(requests[0].body) == thread_request, raw.http_response.text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", raw.http_response.text+ assert isinstance(raw.parse(), _Thread), raw.http_response.text+ assert json.loads(raw.http_response.text) == _THREAD, raw.http_response.text+++ ("content", "prefix"),+ (+ ("Summarize the attachment", ""),+ ("Summarize the attachment", "/v1"),+ ([{"type": "text", "text": "Summarize the attachment"}], ""),+ ([{"type": "text", "text": "Summarize the attachment"}], "/v1"),+ (_IMAGE_PARTS, ""),+ (_IMAGE_PARTS, "/v1"),+ ),+ ids=(+ "string-root-alias",+ "string-v1-alias",+ "parts-root-alias",+ "parts-v1-alias",+ "image-parts-root-alias",+ "image-parts-v1-alias",+ ),+)+def test_add_message_forwards_content_parts_attachments_metadata(+ gateway: Gateway, tmp_path: Path, content: JsonValue, prefix: str+) -> None:+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ base_url: Final = f"{str(candidate.client.base_url).rstrip('/')}{prefix}"+ with OpenAI(base_url=base_url, api_key=candidate.key, max_retries=0) as client:+ raw: Final = client.beta.threads.messages.with_raw_response.create(+ "thread_abc",+ role="user",+ content=content,+ attachments=[{"file_id": "file-abc", "tools": [{"type": "file_search"}]}],+ metadata={"turn": "2"},+ )+ assert raw.status_code == 200, raw.http_response.text+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/messages")+ ], raw.http_response.text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", raw.http_response.text+ assert json.loads(requests[0].body) == {+ "role": "user",+ "content": content,+ "attachments": [{"file_id": "file-abc", "tools": [{"type": "file_search"}]}],+ "metadata": {"turn": "2"},+ }, raw.http_response.text+ assert isinstance(raw.parse(), _Message), raw.http_response.text+ assert json.loads(raw.http_response.text) == _MESSAGE, raw.http_response.text++[email protected]("prefix", ("", "/v1"), ids=("root-alias", "v1-alias"))+def test_run_forwards_every_sdk_field(gateway: Gateway, tmp_path: Path, prefix: str) -> None:+ pytest.skip(+ "BUG: runs.create drops additional_messages, temperature, top_p, max_prompt_tokens, max_completion_tokens, "+ "truncation_strategy, tool_choice, response_format, parallel_tool_calls and reasoning_effort, sends nulls, "+ "then polls "+ "GET /runs/{id}"+ )+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ base_url: Final = f"{str(candidate.client.base_url).rstrip('/')}{prefix}"+ with OpenAI(base_url=base_url, api_key=candidate.key, max_retries=0) as client:+ try:+ raw: Final = client.beta.threads.runs.with_raw_response.create(+ "thread_abc",+ assistant_id="asst_abc",+ instructions="Be terse",+ additional_instructions="Cite sources",+ additional_messages=[{"role": "user", "content": "Also check page 2"}],+ metadata={"run": "r1"},+ model="gpt-4o",+ tools=[{"type": "code_interpreter"}],+ temperature=0.3,+ top_p=0.9,+ max_prompt_tokens=500,+ max_completion_tokens=50,+ truncation_strategy={"type": "last_messages", "last_messages": 4},+ tool_choice="auto",+ response_format={"type": "json_object"},+ parallel_tool_calls=False,+ reasoning_effort="low",+ )+ except APIStatusError as error:+ failure_text: Final = error.response.text+ failed_requests: Final = wire.drain()+ assert [(request.method, request.target) for request in failed_requests] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], failure_text+ assert json.loads(failed_requests[0].body) == _RUN_REQUEST, failure_text+ pytest.fail(f"SDK run creation failed with HTTP {error.response.status_code}: {failure_text}")+ assert raw.status_code == 200, raw.http_response.text+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], raw.http_response.text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", raw.http_response.text+ assert json.loads(requests[0].body) == _RUN_REQUEST, raw.http_response.text+ run: Final[_Run] = raw.parse()+ assert json.loads(raw.http_response.text) == _RUN, raw.http_response.text+ assert run.status == "queued", raw.http_response.text++[email protected]("prefix", ("", "/v1"), ids=("root-alias", "v1-alias"))+def test_run_raw_body_forwards_stream_false_and_typed_options(gateway: Gateway, tmp_path: Path, prefix: str) -> None:+ pytest.skip(+ "BUG: runs.create with a raw stream false body drops tool_choice and response_format, then polls GET /runs/{id}"+ )+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ response: Final = candidate.client.post(+ f"{prefix}/threads/thread_abc/runs",+ json={**_RAW_RUN_REQUEST, "stream": False},+ headers={"Authorization": f"Bearer {candidate.key}"},+ )+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], response.text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", response.text+ upstream_body: Final = json.loads(requests[0].body)+ assert upstream_body.pop("stream", False) is False, response.text+ assert upstream_body == _RAW_RUN_REQUEST, response.text+ assert response.status_code == 200, response.text+ assert response.headers["content-type"].startswith("application/json"), response.text+ assert response.json() == _RUN, response.text+ assert _Run.model_validate(response.json()).status == "queued", response.text++[email protected]("prefix", ("", "/v1"), ids=("root-alias", "v1-alias"))+def test_run_include_query_reaches_upstream(gateway: Gateway, tmp_path: Path, prefix: str) -> None:+ pytest.skip("BUG: runs.create include[] query param never reaches the upstream")+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ base_url: Final = f"{str(candidate.client.base_url).rstrip('/')}{prefix}"+ with OpenAI(base_url=base_url, api_key=candidate.key, max_retries=0) as client:+ raw: Final = client.beta.threads.runs.with_raw_response.create(+ "thread_abc",+ assistant_id="asst_abc",+ include=["step_details.tool_calls[*].file_search.results[*].content"],+ )+ assert raw.status_code == 200, raw.http_response.text+ requests: Final = wire.drain()+ assert [(request.method, urlsplit(request.target).path) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], raw.http_response.text+ assert parse_qs(urlsplit(requests[0].target).query) == {+ "include[]": ["step_details.tool_calls[*].file_search.results[*].content"]+ }, raw.http_response.text+ assert json.loads(requests[0].body) == {"assistant_id": "asst_abc"}, raw.http_response.text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", raw.http_response.text+ run: Final[_Run] = raw.parse()+ assert isinstance(run, _Run), raw.http_response.text+ assert json.loads(raw.http_response.text) == _RUN, raw.http_response.textdiff --git a/tests/integration/providers/test_provider_lookup_status.py b/tests/integration/providers/test_provider_lookup_status.pyindex 2bc28d2b648..a231e7df9e4 100644--- a/tests/integration/providers/test_provider_lookup_status.py+++ b/tests/integration/providers/test_provider_lookup_status.py@@ -3,21 +3,137 @@ from __future__ import annotationsimport asyncioimport jsonimport uuid+from collections.abc import Callable+from dataclasses import dataclassfrom pathlib import Path-from typing import Final, Literal+from typing import Final, Literal, Protocol+from urllib.parse import parse_qs, urlsplitimport httpximport pytestfrom integration._support.client import JSON_OBJECT, Gateway, Scenario, eventually, object_valuefrom integration._support.process import owned_proxy_processfrom integration._support.upstream import ScenarioHandle, delete_scenario, register_scenario+from integration._support.wire import Reply, Request, wire_serverfrom openai import APIStatusError, AsyncOpenAI, OpenAI-from pydantic import JsonValue+from openai.pagination import SyncCursorPage+from openai.types.eval_create_response import EvalCreateResponse as _Eval+from openai.types.eval_delete_response import EvalDeleteResponse as _EvalDelete+from openai.types.eval_list_response import EvalListResponse as _EvalList+from openai.types.eval_retrieve_response import EvalRetrieveResponse as _EvalRetrieve+from openai.types.eval_update_response import EvalUpdateResponse as _EvalUpdate+from openai.types.evals.run_cancel_response import RunCancelResponse as _EvalRunCancel+from openai.types.evals.run_create_response import RunCreateResponse as _EvalRunCreate+from openai.types.evals.run_delete_response import RunDeleteResponse as _EvalRunDelete+from openai.types.evals.run_list_response import RunListResponse as _EvalRunList+from openai.types.evals.run_retrieve_response import RunRetrieveResponse as _EvalRunRetrieve+from pydantic import BaseModel, JsonValuefrom litellm.proxy.openai_files_endpoints.common_utils import encode_file_id_with_modelfrom litellm.types.videos.utils import encode_video_id_with_providerfrom tests.integration.cost_calculation.cost_tracking_case import JsonResponse, RoutedResponse+_EVAL_DATA_SOURCE_CONFIG: Final[dict[str, JsonValue]] = {+ "type": "custom",+ "item_schema": {"type": "object", "properties": {"a": {"type": "string"}}},+}+_EVAL_DATA_SOURCE_CONFIG_RESPONSE: Final[dict[str, JsonValue]] = {+ "type": "custom",+ "schema": {"type": "object", "properties": {"a": {"type": "string"}}},+}+_EVAL_TESTING_CRITERIA: Final[list[JsonValue]] = [+ {"type": "string_check", "name": "exact", "input": "{{item.a}}", "reference": "{{item.a}}", "operation": "eq"}+]+_EVAL_CREATE_UPSTREAM_RESPONSE: Final[dict[str, JsonValue]] = {+ "id": "eval_abc",+ "object": "eval",+ "created_at": 1700000000,+ "name": "nightly",+ "data_source_config": _EVAL_DATA_SOURCE_CONFIG_RESPONSE,+ "testing_criteria": _EVAL_TESTING_CRITERIA,+ "metadata": {"suite": "nightly"},+}+_EVAL_CREATE_RESPONSE: Final[dict[str, JsonValue]] = {+ **_EVAL_CREATE_UPSTREAM_RESPONSE,+ "updated_at": None,+}+_EVAL_UPDATE_UPSTREAM_RESPONSE: Final[dict[str, JsonValue]] = {+ **_EVAL_CREATE_UPSTREAM_RESPONSE,+ "name": "renamed",+ "metadata": {"team": "search"},+}+_EVAL_UPDATE_RESPONSE: Final[dict[str, JsonValue]] = {+ **_EVAL_UPDATE_UPSTREAM_RESPONSE,+ "updated_at": None,+}+_EVAL_RUN_DATA_SOURCE: Final[dict[str, JsonValue]] = {+ "type": "jsonl",+ "source": {"type": "file_id", "id": "file-abc"},+}+_EVAL_RUN_RESPONSE: Final[dict[str, JsonValue]] = {+ "id": "run_abc",+ "object": "eval.run",+ "created_at": 1700000001,+ "eval_id": "eval_abc",+ "started_at": None,+ "completed_at": None,+ "data_source": _EVAL_RUN_DATA_SOURCE,+ "error": None,+ "per_model_usage": [],+ "per_testing_criteria_results": [],+ "report_url": "https://example.invalid/evals/run_abc",+ "result_counts": {"errored": 0, "failed": 0, "passed": 0, "total": 0},+ "shared_with_openai": None,+ "name": "run-1",+ "model": "gpt-4o-mini",+ "metadata": {"suite": "nightly"},+ "status": "queued",+}+_EVAL_RUN_CANCEL_RESPONSE: Final[dict[str, JsonValue]] = {+ **_EVAL_RUN_RESPONSE,+ "status": "cancelled",+}+_EVAL_DELETE_RESPONSE: Final[dict[str, JsonValue]] = {"object": "eval.deleted", "deleted": True, "eval_id": "eval_abc"}+_EVAL_RUN_DELETE_RESPONSE: Final[dict[str, JsonValue]] = {+ "object": "eval.run.deleted",+ "deleted": True,+ "run_id": "run_abc",+}+_EVAL_LIST_UPSTREAM_RESPONSE: Final[dict[str, JsonValue]] = {+ "object": "list",+ "data": [_EVAL_CREATE_UPSTREAM_RESPONSE],+ "first_id": "eval_abc",+ "last_id": "eval_abc",+ "has_more": False,+}+_EVAL_LIST_RESPONSE: Final[dict[str, JsonValue]] = {**_EVAL_LIST_UPSTREAM_RESPONSE, "data": [_EVAL_CREATE_RESPONSE]}+_EVAL_RUN_LIST_RESPONSE: Final[dict[str, JsonValue]] = {+ "object": "list",+ "data": [_EVAL_RUN_RESPONSE],+ "first_id": "run_abc",+ "last_id": "run_abc",+ "has_more": False,+}+_EVAL_UPSTREAM_RESPONSES: Final[dict[tuple[str, str], dict[str, JsonValue]]] = {+ ("POST", "/v1/evals"): _EVAL_CREATE_UPSTREAM_RESPONSE,+ ("GET", "/v1/evals"): _EVAL_LIST_UPSTREAM_RESPONSE,+ ("GET", "/v1/evals/eval_abc"): _EVAL_CREATE_UPSTREAM_RESPONSE,+ ("POST", "/v1/evals/eval_abc"): _EVAL_UPDATE_UPSTREAM_RESPONSE,+ ("DELETE", "/v1/evals/eval_abc"): _EVAL_DELETE_RESPONSE,+ ("POST", "/v1/evals/eval_abc/runs"): _EVAL_RUN_RESPONSE,+ ("GET", "/v1/evals/eval_abc/runs"): _EVAL_RUN_LIST_RESPONSE,+ ("GET", "/v1/evals/eval_abc/runs/run_abc"): _EVAL_RUN_RESPONSE,+ ("POST", "/v1/evals/eval_abc/runs/run_abc/cancel"): _EVAL_RUN_CANCEL_RESPONSE,+ ("DELETE", "/v1/evals/eval_abc/runs/run_abc"): _EVAL_RUN_DELETE_RESPONSE,+}+++def _evals_respond(request: Request) -> Reply:+ body: Final = _EVAL_UPSTREAM_RESPONSES.get((request.method, urlsplit(request.target).path))+ if body is None:+ return Reply(status=404, body=b'{"error":"unexpected upstream request"}')+ return Reply(body=json.dumps(body).encode())+def _provider_error(status: int) -> dict[str, JsonValue]:return {@@ -106,6 +222,309 @@ def _assert_provider_error(response: httpx.Response, status: int) -> None:assert "scripted provider status" in str(error.get("message")), response.text+def _assert_no_gateway_headers(gateway: Gateway, requests: tuple[Request, ...], context: str) -> None:+ leaked: Final = [+ {name: value for name, value in request.headers.items() if name == "x-litellm-model" or gateway.key in value}+ for request in requests+ ]+ assert leaked == [{} for _ in requests], context+++def test_eval_update_forwards_only_client_fields(gateway: Gateway) -> None:+ pytest.skip(+ "BUG: evals.update returns 500 Object of type datetime is not JSON serializable and never reaches the upstream"+ )+ with wire_server(_evals_respond) as wire, gateway.scenario() as scenario:+ alias: Final = scenario.model(model="openai/gpt-4o-mini", api_base=wire.url, api_key="synthetic-openai-key")+ _ready(gateway, alias)+ wire.drain()+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1", api_key=gateway.key, max_retries=0+ ) as client:+ try:+ raw: Final = client.evals.with_raw_response.update(+ "eval_abc", name="renamed", metadata={"team": "search"}, extra_body={"model": alias}+ )+ except APIStatusError as error:+ failure_text: Final = error.response.text+ failed_requests: Final = wire.drain()+ assert [(request.method, request.target) for request in failed_requests] == [+ ("POST", "/v1/evals/eval_abc")+ ], failure_text+ assert failed_requests[0].headers["authorization"] == "Bearer synthetic-openai-key", failure_text+ assert json.loads(failed_requests[0].body) == {"name": "renamed", "metadata": {"team": "search"}}, (+ failure_text+ )+ pytest.fail(f"SDK Eval update failed with HTTP {error.response.status_code}: {failure_text}")+ assert raw.status_code == 200, raw.http_response.text+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [("POST", "/v1/evals/eval_abc")], (+ raw.http_response.text+ )+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", raw.http_response.text+ _assert_no_gateway_headers(gateway, requests, raw.http_response.text)+ assert json.loads(requests[0].body) == {"name": "renamed", "metadata": {"team": "search"}}, (+ raw.http_response.text+ )+ evaluation: Final[_EvalUpdate] = raw.parse()+ assert json.loads(raw.http_response.text) == _EVAL_UPDATE_RESPONSE, raw.http_response.text+ assert evaluation.name == "renamed", raw.http_response.text+++class _RawResponse(Protocol):+ @property+ def http_response(self) -> httpx.Response: ...++ def parse(self) -> object: ...+++@dataclass(frozen=True, slots=True)+class _ModelRouting:+ body: dict[str, object] | None+ query: dict[str, object] | None+ headers: dict[str, str] | None+++@dataclass(frozen=True, slots=True)+class _EvalCall:+ send: Callable[[OpenAI, _ModelRouting], _RawResponse]+ parsed: type[BaseModel]+ upstream: tuple[str, str, dict[str, list[str]], JsonValue]+ response: dict[str, JsonValue]+++_EVAL_CREATE_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.with_raw_response.create(+ name="nightly",+ data_source_config=_EVAL_DATA_SOURCE_CONFIG,+ testing_criteria=_EVAL_TESTING_CRITERIA,+ extra_body=routing.body,+ ),+ parsed=_Eval,+ upstream=(+ "POST",+ "/v1/evals",+ {},+ {"name": "nightly", "data_source_config": _EVAL_DATA_SOURCE_CONFIG, "testing_criteria": _EVAL_TESTING_CRITERIA},+ ),+ response=_EVAL_CREATE_RESPONSE,+)+_EVAL_CREATE_WITH_METADATA_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.with_raw_response.create(+ name="nightly",+ data_source_config=_EVAL_DATA_SOURCE_CONFIG,+ testing_criteria=_EVAL_TESTING_CRITERIA,+ metadata={"suite": "nightly"},+ extra_body=routing.body,+ ),+ parsed=_Eval,+ upstream=(+ "POST",+ "/v1/evals",+ {},+ {+ "name": "nightly",+ "data_source_config": _EVAL_DATA_SOURCE_CONFIG,+ "testing_criteria": _EVAL_TESTING_CRITERIA,+ "metadata": {"suite": "nightly"},+ },+ ),+ response=_EVAL_CREATE_RESPONSE,+)+_EVAL_LIST_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.with_raw_response.list(+ limit=2, after="eval_000", order="asc", order_by="updated_at", extra_query=routing.query+ ),+ parsed=_EvalList,+ upstream=(+ "GET",+ "/v1/evals",+ {"limit": ["2"], "after": ["eval_000"], "order": ["asc"], "order_by": ["updated_at"]},+ None,+ ),+ response=_EVAL_LIST_RESPONSE,+)+_EVAL_RETRIEVE_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.with_raw_response.retrieve("eval_abc", extra_query=routing.query),+ parsed=_EvalRetrieve,+ upstream=("GET", "/v1/evals/eval_abc", {}, None),+ response=_EVAL_CREATE_RESPONSE,+)+_EVAL_UPDATE_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.with_raw_response.update(+ "eval_abc", name="renamed", metadata={"team": "search"}, extra_body=routing.body+ ),+ parsed=_EvalUpdate,+ upstream=("POST", "/v1/evals/eval_abc", {}, {"name": "renamed", "metadata": {"team": "search"}}),+ response=_EVAL_UPDATE_RESPONSE,+)+_EVAL_DELETE_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.with_raw_response.delete("eval_abc", extra_query=routing.query),+ parsed=_EvalDelete,+ upstream=("DELETE", "/v1/evals/eval_abc", {}, None),+ response=_EVAL_DELETE_RESPONSE,+)+_EVAL_RUN_CREATE_WITH_METADATA_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.runs.with_raw_response.create(+ "eval_abc",+ data_source=_EVAL_RUN_DATA_SOURCE,+ name="run-1",+ metadata={"suite": "nightly"},+ extra_body=routing.body,+ ),+ parsed=_EvalRunCreate,+ upstream=(+ "POST",+ "/v1/evals/eval_abc/runs",+ {},+ {"data_source": _EVAL_RUN_DATA_SOURCE, "name": "run-1", "metadata": {"suite": "nightly"}},+ ),+ response=_EVAL_RUN_RESPONSE,+)+_EVAL_RUN_LIST_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.runs.with_raw_response.list(+ "eval_abc", limit=3, after="run_000", order="desc", extra_query=routing.query+ ),+ parsed=_EvalRunList,+ upstream=("GET", "/v1/evals/eval_abc/runs", {"limit": ["3"], "after": ["run_000"], "order": ["desc"]}, None),+ response=_EVAL_RUN_LIST_RESPONSE,+)+_EVAL_RUN_LIST_BY_STATUS_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.runs.with_raw_response.list(+ "eval_abc", limit=3, after="run_000", order="desc", status="completed", extra_query=routing.query+ ),+ parsed=_EvalRunList,+ upstream=(+ "GET",+ "/v1/evals/eval_abc/runs",+ {"limit": ["3"], "after": ["run_000"], "order": ["desc"], "status": ["completed"]},+ None,+ ),+ response=_EVAL_RUN_LIST_RESPONSE,+)+_EVAL_RUN_RETRIEVE_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.runs.with_raw_response.retrieve(+ "run_abc", eval_id="eval_abc", extra_query=routing.query+ ),+ parsed=_EvalRunRetrieve,+ upstream=("GET", "/v1/evals/eval_abc/runs/run_abc", {}, None),+ response=_EVAL_RUN_RESPONSE,+)+_EVAL_RUN_CANCEL_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.runs.with_raw_response.cancel(+ "run_abc", eval_id="eval_abc", extra_query=routing.query+ ),+ parsed=_EvalRunCancel,+ # OpenAI cancel path per openai-python 3.30.0 evals.runs.cancel, checked 2026-10-14+ upstream=("POST", "/v1/evals/eval_abc/runs/run_abc/cancel", {}, {}),+ response=_EVAL_RUN_CANCEL_RESPONSE,+)+_EVAL_RUN_DELETE_CALL: Final = _EvalCall(+ send=lambda client, routing: client.evals.runs.with_raw_response.delete(+ "run_abc", eval_id="eval_abc", extra_query=routing.query+ ),+ parsed=_EvalRunDelete,+ upstream=("DELETE", "/v1/evals/eval_abc/runs/run_abc", {}, None),+ response=_EVAL_RUN_DELETE_RESPONSE,+)+_EVAL_ROUTES_WITHOUT_KNOWN_BUGS: Final = (+ _EVAL_CREATE_CALL,+ _EVAL_LIST_CALL,+ _EVAL_RETRIEVE_CALL,+ _EVAL_DELETE_CALL,+ _EVAL_RUN_LIST_CALL,+ _EVAL_RUN_DELETE_CALL,+)+_EVERY_EVAL_ROUTE: Final = (+ _EVAL_CREATE_WITH_METADATA_CALL,+ _EVAL_LIST_CALL,+ _EVAL_RETRIEVE_CALL,+ _EVAL_UPDATE_CALL,+ _EVAL_DELETE_CALL,+ _EVAL_RUN_CREATE_WITH_METADATA_CALL,+ _EVAL_RUN_LIST_BY_STATUS_CALL,+ _EVAL_RUN_RETRIEVE_CALL,+ _EVAL_RUN_CANCEL_CALL,+ _EVAL_RUN_DELETE_CALL,+)+++def _model_routing(alias: str, spelling: str) -> _ModelRouting:+ if spelling == "x-litellm-model":+ return _ModelRouting(body=None, query=None, headers={"x-litellm-model": alias})+ return _ModelRouting(body={"model": alias}, query={"model": alias}, headers=None)+++def _parsed_types(parsed: object) -> tuple[type, ...]:+ if isinstance(parsed, SyncCursorPage):+ return tuple(type(item) for item in parsed.data)+ return (type(parsed),)+++def _observed(request: Request) -> tuple[str, str, dict[str, list[str]], JsonValue]:+ target: Final = urlsplit(request.target)+ body: Final[JsonValue] = json.loads(request.body) if request.body else None+ return request.method, target.path, parse_qs(target.query), body+++def _assert_eval_sdk_paths(gateway: Gateway, suffix: str, spelling: str, calls: tuple[_EvalCall, ...]) -> None:+ with wire_server(_evals_respond) as wire, gateway.scenario() as scenario:+ alias: Final = scenario.model(+ model="openai/gpt-4o-mini", api_base=f"{wire.url}{suffix}", api_key="synthetic-openai-key"+ )+ _ready(gateway, alias)+ wire.drain()+ routing: Final = _model_routing(alias, spelling)+ with OpenAI(+ base_url=f"{str(gateway.client.base_url).rstrip('/')}/v1",+ api_key=gateway.key,+ max_retries=0,+ default_headers=routing.headers,+ ) as client:+ try:+ raws: Final = tuple(call.send(client, routing) for call in calls)+ except APIStatusError as error:+ failure_text: Final = error.response.text+ observed: Final = [_observed(request) for request in wire.drain()]+ pytest.fail(f"SDK eval call failed with HTTP {error.response.status_code}: {failure_text}\n{observed}")+ response_text: Final = "\n".join(raw.http_response.text for raw in raws)+ requests: Final = wire.drain()+ assert [_observed(request) for request in requests] == [call.upstream for call in calls], response_text+ assert {request.headers["authorization"] for request in requests} == {"Bearer synthetic-openai-key"}, (+ response_text+ )+ _assert_no_gateway_headers(gateway, requests, response_text)+ assert [json.loads(raw.http_response.text) for raw in raws] == [call.response for call in calls], response_text+ assert [_parsed_types(raw.parse()) for raw in raws] == [(call.parsed,) for call in calls], response_text++[email protected]("spelling", ("model-param", "x-litellm-model"))+def test_eval_routes_reach_sdk_paths_with_bare_api_base(gateway: Gateway, spelling: str) -> None:+ _assert_eval_sdk_paths(gateway, "", spelling, _EVAL_ROUTES_WITHOUT_KNOWN_BUGS)++[email protected]("spelling", ("model-param", "x-litellm-model"))[email protected]("suffix", ("/v1", "/v1/"), ids=("v1", "v1-trailing-slash"))+def test_eval_routes_reach_sdk_paths_with_v1_api_base(gateway: Gateway, suffix: str, spelling: str) -> None:+ pytest.skip("BUG: an api_base ending in /v1 sends every eval request to /v1/v1/evals")+ _assert_eval_sdk_paths(gateway, suffix, spelling, _EVAL_ROUTES_WITHOUT_KNOWN_BUGS)++[email protected]("spelling", ("model-param", "x-litellm-model"))[email protected]("suffix", ("", "/v1", "/v1/"), ids=("bare", "v1", "v1-trailing-slash"))+def test_every_eval_route_reaches_sdk_path_and_relays_upstream_body(+ gateway: Gateway, suffix: str, spelling: str+) -> None:+ pytest.skip(+ "BUG: evals.runs.cancel returns only {id, object, status} "+ "instead of relaying the full upstream eval run (the route's response_model=CancelRunResponse strips it), "+ "evals.update returns 500, create and run create drop metadata, runs.list drops status, "+ "run create and retrieve overwrite the run's model with the routing alias, "+ "and an api_base ending in /v1 sends every eval request to /v1/v1/evals"+ )+ _assert_eval_sdk_paths(gateway, suffix, spelling, _EVERY_EVAL_ROUTE)++@pytest.mark.parametrize("status", (400, 401, 404, 429, 500), ids=("bad-request", "unauthorized", "not-found", "rate-limit", "server-error"))diff --git a/tests/integration/streaming/test_assistants_evals_stream.py b/tests/integration/streaming/test_assistants_evals_stream.pynew file mode 100644index 00000000000..9f9e0275154--- /dev/null+++ b/tests/integration/streaming/test_assistants_evals_stream.py@@ -0,0 +1,403 @@+from __future__ import annotations++import json+import threading+from collections.abc import Callable, Iterator+from pathlib import Path+from typing import Final++import httpx+import pytest+import yaml+from integration._support.client import Gateway+from integration._support.process import owned_proxy+from integration._support.wire import Reply, Request, wire_server+from openai import APITimeoutError, OpenAI+from pydantic import JsonValue++_QUEUED_RUN: Final[dict[str, JsonValue]] = {+ "id": "run_abc",+ "assistant_id": "asst_abc",+ "cancelled_at": None,+ "completed_at": None,+ "created_at": 1700000002,+ "expires_at": None,+ "failed_at": None,+ "incomplete_details": None,+ "instructions": "Be terse",+ "last_error": None,+ "max_completion_tokens": 50,+ "max_prompt_tokens": 500,+ "metadata": {"run": "r1"},+ "model": "gpt-4o",+ "object": "thread.run",+ "parallel_tool_calls": False,+ "required_action": None,+ "response_format": {"type": "json_object"},+ "started_at": None,+ "status": "queued",+ "thread_id": "thread_abc",+ "tool_choice": "auto",+ "tools": [{"type": "code_interpreter"}],+ "truncation_strategy": {"type": "last_messages", "last_messages": 4},+ "usage": None,+ "temperature": 0.3,+ "top_p": 0.9,+}+_MESSAGE_CREATED: Final[dict[str, JsonValue]] = {+ "id": "msg_abc",+ "assistant_id": "asst_abc",+ "attachments": None,+ "completed_at": None,+ "content": [],+ "created_at": 1700000003,+ "incomplete_at": None,+ "incomplete_details": None,+ "metadata": {},+ "object": "thread.message",+ "role": "assistant",+ "run_id": "run_abc",+ "status": "in_progress",+ "thread_id": "thread_abc",+}+_MESSAGE_DELTA: Final[dict[str, JsonValue]] = {+ "id": "msg_abc",+ "object": "thread.message.delta",+ "delta": {"content": [{"index": 0, "type": "text", "text": {"value": "Hi"}}]},+}+_COMPLETED_RUN: Final[dict[str, JsonValue]] = {+ **_QUEUED_RUN,+ "completed_at": 1700000004,+ "status": "completed",+ "usage": {"completion_tokens": 1, "prompt_tokens": 1, "total_tokens": 2},+}+_RUN_REQUEST: Final[dict[str, JsonValue]] = {+ "assistant_id": "asst_abc",+ "instructions": "Be terse",+ "additional_instructions": "Cite sources",+ "additional_messages": [{"role": "user", "content": "Also check page 2"}],+ "metadata": {"run": "r1"},+ "model": "gpt-4o",+ "tools": [{"type": "code_interpreter"}],+ "temperature": 0.3,+ "top_p": 0.9,+ "max_prompt_tokens": 500,+ "max_completion_tokens": 50,+ "truncation_strategy": {"type": "last_messages", "last_messages": 4},+ "tool_choice": "auto",+ "response_format": {"type": "json_object"},+ "parallel_tool_calls": False,+ "reasoning_effort": "low",+}+++def _assistant_config(tmp_path: Path, api_base: str) -> Path:+ config: Final[dict[str, JsonValue]] = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())+ config["assistant_settings"] = {+ "custom_llm_provider": "openai",+ "litellm_params": {"api_base": api_base, "api_key": "synthetic-openai-key"},+ }+ config_path: Final = tmp_path / "assistants_evals_stream.yaml"+ config_path.write_text(yaml.safe_dump(config), encoding="utf-8")+ return config_path+++def _frame(event: str, data: dict[str, JsonValue] | str) -> bytes:+ encoded_data: Final = data if isinstance(data, str) else json.dumps(data)+ return f"event: {event}\ndata: {encoded_data}\n\n".encode()+++def _respond(request: Request) -> Reply:+ if request.method != "POST" or request.target != "/v1/threads/thread_abc/runs":+ return Reply(status=404, body=b'{"error":"unexpected upstream request"}')+ return Reply(+ content_type="text/event-stream",+ chunks=(+ _frame("thread.run.created", _QUEUED_RUN),+ _frame("thread.message.created", _MESSAGE_CREATED),+ _frame("thread.message.delta", _MESSAGE_DELTA),+ _frame("thread.run.completed", _COMPLETED_RUN),+ _frame("done", "[DONE]"),+ ),+ )+++def _parse_frame(frame: str) -> tuple[str, JsonValue]:+ lines: Final = frame.splitlines()+ event: Final = next((line.removeprefix("event: ") for line in lines if line.startswith("event: ")), "")+ data: Final = next((line.removeprefix("data: ") for line in lines if line.startswith("data: ")), "")+ return event, data if data == "[DONE]" else json.loads(data)+++def _parse_frames(body: str) -> tuple[tuple[str, JsonValue], ...]:+ return tuple(_parse_frame(frame) for frame in body.strip().split("\n\n"))+++_EXPECTED_FRAMES: Final = (+ ("thread.run.created", _QUEUED_RUN),+ ("thread.message.created", _MESSAGE_CREATED),+ ("thread.message.delta", _MESSAGE_DELTA),+ ("thread.run.completed", _COMPLETED_RUN),+ ("done", "[DONE]"),+)+++class _RecordingStream(httpx.SyncByteStream):+ def __init__(self, inner: httpx.SyncByteStream, sink: list[bytes]) -> None:+ self._inner: Final = inner+ self._sink: Final = sink++ def __iter__(self) -> Iterator[bytes]:+ for chunk in self._inner:+ self._sink.append(chunk)+ yield chunk++ def close(self) -> None:+ self._inner.close()+++class _RecordingTransport(httpx.BaseTransport):+ """Records the bytes the SDK client read off the proxy socket, so the done frame the SDK swallows is visible."""++ def __init__(self) -> None:+ self.received: Final[list[bytes]] = []+ self._inner: Final = httpx.HTTPTransport()++ def handle_request(self, request: httpx.Request) -> httpx.Response:+ response: Final = self._inner.handle_request(request)+ assert isinstance(response.stream, httpx.SyncByteStream)+ return httpx.Response(+ status_code=response.status_code,+ headers=response.headers,+ stream=_RecordingStream(response.stream, self.received),+ extensions=response.extensions,+ request=request,+ )++ def close(self) -> None:+ self._inner.close()++ def text(self) -> str:+ return b"".join(self.received).decode()++[email protected]("prefix", ("", "/v1"), ids=("root-alias", "v1-alias"))+def test_run_stream_relays_upstream_events(gateway: Gateway, tmp_path: Path, prefix: str) -> None:+ pytest.skip(+ "BUG: streamed run frames carry the event name inside data with no event: line and drop run options upstream"+ )+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ body: Final[dict[str, JsonValue]] = {**_RUN_REQUEST, "stream": True}+ response: Final = candidate.request("POST", f"{prefix}/threads/thread_abc/runs", body)+ assert response.status_code == 200, response.text+ assert response.headers["content-type"].startswith("text/event-stream"), response.text+ assert _parse_frames(response.text) == _EXPECTED_FRAMES, response.text+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], response.text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", response.text+ assert json.loads(requests[0].body) == body, response.text++[email protected]("prefix", ("", "/v1"), ids=("root-alias", "v1-alias"))+def test_sdk_run_stream_event_handler_sees_events(gateway: Gateway, tmp_path: Path, prefix: str) -> None:+ pytest.skip("BUG: runs.stream drops additional_messages, sampling, token caps and other run options upstream")+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ transport: Final = _RecordingTransport()+ with OpenAI(+ base_url=f"{str(candidate.client.base_url).rstrip('/')}{prefix}",+ api_key=candidate.key,+ max_retries=0,+ http_client=httpx.Client(transport=transport),+ ) as client:+ with client.beta.threads.runs.stream(+ thread_id="thread_abc",+ assistant_id="asst_abc",+ instructions="Be terse",+ additional_instructions="Cite sources",+ additional_messages=[{"role": "user", "content": "Also check page 2"}],+ metadata={"run": "r1"},+ model="gpt-4o",+ tools=[{"type": "code_interpreter"}],+ temperature=0.3,+ top_p=0.9,+ max_prompt_tokens=500,+ max_completion_tokens=50,+ truncation_strategy={"type": "last_messages", "last_messages": 4},+ tool_choice="auto",+ response_format={"type": "json_object"},+ parallel_tool_calls=False,+ reasoning_effort="low",+ ) as stream:+ events: Final = tuple((event.event, event.data.to_dict(mode="json")) for event in stream)+ response_text: Final = transport.text()+ assert events == _EXPECTED_FRAMES[:-1], response_text+ assert _parse_frames(response_text) == _EXPECTED_FRAMES, response_text+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], response_text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", response_text+ assert json.loads(requests[0].body) == {**_RUN_REQUEST, "stream": True}, response_text++[email protected]("prefix", ("", "/v1"), ids=("root-alias", "v1-alias"))+def test_sdk_run_create_stream_yields_events(gateway: Gateway, tmp_path: Path, prefix: str) -> None:+ pytest.skip("BUG: runs.create(stream=True) yields null event names and drops run options upstream")+ with wire_server(_respond) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ transport: Final = _RecordingTransport()+ with OpenAI(+ base_url=f"{str(candidate.client.base_url).rstrip('/')}{prefix}",+ api_key=candidate.key,+ max_retries=0,+ http_client=httpx.Client(transport=transport),+ ) as client:+ with client.beta.threads.runs.create(+ "thread_abc",+ assistant_id="asst_abc",+ instructions="Be terse",+ additional_instructions="Cite sources",+ additional_messages=[{"role": "user", "content": "Also check page 2"}],+ metadata={"run": "r1"},+ model="gpt-4o",+ tools=[{"type": "code_interpreter"}],+ temperature=0.3,+ top_p=0.9,+ max_prompt_tokens=500,+ max_completion_tokens=50,+ truncation_strategy={"type": "last_messages", "last_messages": 4},+ tool_choice="auto",+ response_format={"type": "json_object"},+ parallel_tool_calls=False,+ reasoning_effort="low",+ stream=True,+ ) as stream:+ events: Final = tuple((event.event, event.data.to_dict(mode="json")) for event in stream)+ response_text: Final = transport.text()+ assert events == _EXPECTED_FRAMES[:-1], response_text+ assert _parse_frames(response_text) == _EXPECTED_FRAMES, response_text+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], response_text+ assert requests[0].headers["authorization"] == "Bearer synthetic-openai-key", response_text+ assert json.loads(requests[0].body) == {**_RUN_REQUEST, "stream": True}, response_text+++_MARKER_MESSAGE: Final[dict[str, JsonValue]] = {+ "id": "msg_marker",+ "assistant_id": None,+ "attachments": [],+ "completed_at": None,+ "object": "thread.message",+ "content": [{"type": "text", "text": {"value": "marker", "annotations": []}}],+ "created_at": 1700000005,+ "incomplete_at": None,+ "incomplete_details": None,+ "metadata": {},+ "role": "user",+ "run_id": None,+ "status": "completed",+ "thread_id": "thread_abc",+}+_HELD_FRAME: Final = b":" + b"x" * 4_000_000 + b"\n\n"+++def _held_respond(gate: threading.Event, run_reply: Reply) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ if request.method == "POST" and request.target == "/v1/threads/thread_abc/runs":+ return run_reply+ if request.method == "GET" and request.target == "/v1/threads/thread_abc/runs/run_abc":+ return Reply(body=json.dumps(_QUEUED_RUN).encode())+ if request.method == "POST" and request.target == "/v1/threads/thread_abc/messages":+ return Reply(body=json.dumps(_MARKER_MESSAGE).encode())+ return Reply(status=404, body=b'{"error":"unexpected upstream request"}')++ assert run_reply.gate_after_first is gate+ return respond+++def _marker_message(base_url: str, key: str) -> str:+ with OpenAI(base_url=base_url, api_key=key, max_retries=0) as client:+ raw: Final = client.beta.threads.messages.with_raw_response.create("thread_abc", role="user", content="marker")+ assert json.loads(raw.http_response.text) == _MARKER_MESSAGE, raw.http_response.text+ return raw.http_response.text+++def test_run_stream_client_disconnect_releases_upstream_without_polling(gateway: Gateway, tmp_path: Path) -> None:+ pytest.skip(+ "BUG: runs.create(stream=True) yields null event names, so the first SDK event is not thread.run.created"+ )+ gate: Final = threading.Event()+ run_reply: Final = Reply(+ content_type="text/event-stream",+ chunks=(+ _frame("thread.run.created", _QUEUED_RUN),+ _HELD_FRAME,+ _frame("thread.message.created", _MESSAGE_CREATED),+ _frame("thread.run.completed", _COMPLETED_RUN),+ _frame("done", "[DONE]"),+ ),+ gate_after_first=gate,+ )+ with wire_server(_held_respond(gate, run_reply)) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ base_url: Final = f"{str(candidate.client.base_url).rstrip('/')}/v1"+ try:+ with OpenAI(base_url=base_url, api_key=candidate.key, max_retries=0) as client:+ with client.beta.threads.runs.create("thread_abc", assistant_id="asst_abc", stream=True) as stream:+ first: Final = next(iter(stream))+ finally:+ gate.set()+ response_text: Final = json.dumps({"event": first.event, "data": first.data.to_dict(mode="json")})+ assert (first.event, first.data.to_dict(mode="json")) == ("thread.run.created", _QUEUED_RUN), response_text+ assert wire.disconnected.get(timeout=10) == "/v1/threads/thread_abc/runs", response_text+ marker_text: Final = _marker_message(base_url, candidate.key)+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs"),+ ("POST", "/v1/threads/thread_abc/messages"),+ ], f"{response_text}\n{marker_text}"+ assert json.loads(requests[0].body) == {"assistant_id": "asst_abc", "stream": True}, response_text+++def test_run_client_disconnect_does_not_leave_the_proxy_polling(gateway: Gateway, tmp_path: Path) -> None:+ pytest.skip("BUG: after the client of a non-stream runs.create disconnects, the proxy keeps polling GET /runs/{id}")+ gate: Final = threading.Event()+ queued_body: Final = json.dumps(_QUEUED_RUN).encode()+ run_reply: Final = Reply(chunks=(queued_body[:20], queued_body[20:]), gate_after_first=gate)+ with wire_server(_held_respond(gate, run_reply)) as wire:+ config: Final = _assistant_config(tmp_path, f"{wire.url}/v1")+ with owned_proxy(gateway, tmp_path, {}, config=config) as candidate:+ base_url: Final = f"{str(candidate.client.base_url).rstrip('/')}/v1"+ try:+ with OpenAI(+ base_url=base_url, api_key=candidate.key, max_retries=0, timeout=httpx.Timeout(30, read=2)+ ) as client:+ with pytest.raises(APITimeoutError):+ client.beta.threads.runs.create("thread_abc", assistant_id="asst_abc")+ finally:+ gate.set()+ marker_text: Final = _marker_message(base_url, candidate.key)+ requests: Final = wire.drain()+ assert [(request.method, request.target) for request in requests] == [+ ("POST", "/v1/threads/thread_abc/runs"),+ ("POST", "/v1/threads/thread_abc/messages"),+ ], marker_text+ assert json.loads(requests[0].body) == {"assistant_id": "asst_abc"}, marker_text+ with OpenAI(base_url=base_url, api_key=candidate.key, max_retries=0) as client:+ raw: Final = client.beta.threads.runs.with_raw_response.create("thread_abc", assistant_id="asst_abc")+ assert raw.headers["content-type"].startswith("application/json"), raw.http_response.text+ assert json.loads(raw.http_response.text) == _QUEUED_RUN, raw.http_response.text+ assert raw.parse().status == "queued", raw.http_response.text+ assert [(request.method, request.target) for request in wire.drain()] == [+ ("POST", "/v1/threads/thread_abc/runs")+ ], raw.http_response.text