Skip to content

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

test(integration): build OpenAI and Anthropic SDK models before tests start threads (#46797)

yucheng-berri250e6bd24b16
diff --git a/tests/integration/_support/sdk_models.py b/tests/integration/_support/sdk_models.py
new file mode 100644
index 00000000000..06e94b349d5
--- /dev/null
+++ b/tests/integration/_support/sdk_models.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+from collections.abc import Iterator
+from typing import Final
+
+import anthropic
+import openai
+from pydantic import BaseModel
+
+_SDK_PACKAGES: Final = frozenset({openai.__name__, anthropic.__name__})
+
+
+def _subclasses(model: type[BaseModel]) -> Iterator[type[BaseModel]]:
+ for subclass in model.__subclasses__():
+ yield subclass
+ yield from _subclasses(subclass)
+
+
+def build_sdk_models() -> None:
+ """Build every pydantic model the OpenAI and Anthropic SDKs define now rather than on its first use."""
+ for model in frozenset(_subclasses(BaseModel)):
+ if model.__module__.partition(".")[0] in _SDK_PACKAGES:
+ _ = model.model_rebuild(raise_errors=False)
diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py
index a4bd6092a0c..e82430c3add 100644
--- a/tests/integration/conftest.py
+++ b/tests/integration/conftest.py
@@ -25,6 +25,7 @@ from tests.integration._support.manifest import OWNED_DIRECTORIES
from tests.integration._support.ordering import collected_case, fixture_groups, scheduling_groups
from tests.integration._support.provider import SharedProvider, shared_provider
from tests.integration._support.routing import RoutingPlugin
+from tests.integration._support.sdk_models import build_sdk_models
from tests.integration._support.workers import gateway_profile, start_worker_stacks, worker_stack
from tests.integration.run import GITHUB_FILES
@@ -70,6 +71,7 @@ def pytest_configure(config: pytest.Config) -> None:
config.stash[REPORTS] = []
config.stash[SHARD_FILES] = _shard_files(SHARD_PATH.validate_python(config.getoption("integration_shard_files")))
config.pluginmanager.register(IntegrationReportPlugin(config))
+ build_sdk_models()
if os.environ.get("INTEGRATION_ROUTING"):
config.pluginmanager.register(RoutingPlugin(config))
diff --git a/tests/unit/integration_support/test_sdk_models.py b/tests/unit/integration_support/test_sdk_models.py
new file mode 100644
index 00000000000..285d3d78fff
--- /dev/null
+++ b/tests/unit/integration_support/test_sdk_models.py
@@ -0,0 +1,128 @@
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Final
+
+_REPOSITORY: Final = Path(__file__).resolve().parents[3]
+_CONCURRENT_FIRST_USE: Final = """
+import sys
+import threading
+
+from anthropic.types import Message, RawContentBlockDeltaEvent
+from openai.types.chat import ChatCompletion, ChatCompletionChunk
+from openai.types.responses import Response, ResponseTextDeltaEvent
+
+from tests.integration._support.sdk_models import build_sdk_models
+
+USAGE = {"input_tokens": 1, "output_tokens": 1}
+PAYLOADS = (
+ (
+ Response,
+ {
+ "id": "resp_1",
+ "object": "response",
+ "created_at": 1,
+ "model": "gpt-4.1-mini",
+ "status": "completed",
+ "output": [
+ {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": "hi", "annotations": []}],
+ }
+ ],
+ "usage": {**USAGE, "total_tokens": 2},
+ },
+ ),
+ (
+ ChatCompletion,
+ {
+ "id": "chatcmpl_1",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-4o-mini",
+ "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "hi"}}],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ ),
+ (
+ Message,
+ {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5",
+ "content": [{"type": "text", "text": "hi"}],
+ "stop_reason": "end_turn",
+ "usage": USAGE,
+ },
+ ),
+ (
+ ResponseTextDeltaEvent,
+ {
+ "type": "response.output_text.delta",
+ "item_id": "msg_1",
+ "output_index": 0,
+ "content_index": 0,
+ "sequence_number": 1,
+ "delta": "hi",
+ "logprobs": [],
+ },
+ ),
+ (
+ ChatCompletionChunk,
+ {
+ "id": "chatcmpl_1",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "gpt-4o-mini",
+ "choices": [{"index": 0, "finish_reason": None, "delta": {"role": "assistant", "content": "hi"}}],
+ },
+ ),
+ (
+ RawContentBlockDeltaEvent,
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "hi"}},
+ ),
+)
+THREADS = 30
+
+sys.setswitchinterval(1e-6)
+build_sdk_models()
+gate = threading.Barrier(THREADS)
+failures = []
+
+
+def first_use():
+ gate.wait()
+ for model, payload in PAYLOADS:
+ try:
+ model.model_construct(**payload)
+ except Exception as error:
+ failures.append(f"{model.__name__}: {type(error).__name__}: {error}")
+
+
+threads = [threading.Thread(target=first_use) for _ in range(THREADS)]
+for thread in threads:
+ thread.start()
+for thread in threads:
+ thread.join()
+print(sorted(set(failures)))
+"""
+
+
+def test_sdk_models_built_up_front_survive_concurrent_first_use_from_many_threads() -> None:
+ completed: Final = subprocess.run(
+ (sys.executable, "-P", "-c", _CONCURRENT_FIRST_USE),
+ env={**os.environ, "PYTHONPATH": str(_REPOSITORY)},
+ capture_output=True,
+ text=True,
+ timeout=120,
+ check=False,
+ )
+ assert completed.returncode == 0, completed.stderr
+ assert completed.stdout.strip() == "[]", completed.stdout