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
fix(proxy): build the OpenAPI schema off the event loop so a cold /openapi.json no longer stalls the worker (#47352)
Mateo Wang424687ce09b6
diff --git a/litellm/proxy/common_utils/openapi_route.py b/litellm/proxy/common_utils/openapi_route.pynew file mode 100644index 00000000000..69fbeb67277--- /dev/null+++ b/litellm/proxy/common_utils/openapi_route.py@@ -0,0 +1,82 @@+import asyncio+import functools+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from typing import Final, TypeAlias, TypeVar++from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse, Response+from pydantic import TypeAdapter+from starlette.routing import BaseRoute, Route++from litellm.proxy.common_utils.custom_openapi_spec import JsonObject++OpenAPISchema: TypeAlias = JsonObject+Inputs: Final = TypeVar("Inputs")+_SERVERS: Final = TypeAdapter(list[dict[str, object]])+++@dataclass(frozen=True, slots=True, eq=False)+class _SameSchema:+ schema: Mapping[str, object]++ def __eq__(self, other: object) -> bool:+ return isinstance(other, _SameSchema) and other.schema is self.schema++ def __hash__(self) -> int:+ return id(self.schema)+++def serve_openapi_off_the_event_loop(+ app: FastAPI,+ snapshot: Callable[[], Inputs],+ build: Callable[[Inputs], OpenAPISchema],+) -> None:+ openapi_url: Final = app.openapi_url+ if openapi_url is None:+ return+ build_lock: Final = asyncio.Lock()+ installed_openapi: Final = app.openapi++ async def built_schema() -> OpenAPISchema:+ async with build_lock:+ if app.openapi_schema:+ return app.openapi_schema+ inputs: Final = snapshot()+ schema: Final = await asyncio.to_thread(build, inputs)+ if app.openapi_schema is None and snapshot() == inputs:+ app.openapi_schema = schema+ return schema++ async def served_schema() -> OpenAPISchema:+ if app.openapi != installed_openapi:+ return app.openapi()+ return app.openapi_schema or await built_schema()++ async def openapi(request: Request) -> Response:+ schema: Final = await served_schema()+ scope_root_path: Final[object] = request.scope.get("root_path")+ root_path: Final = scope_root_path.rstrip("/") if isinstance(scope_root_path, str) else ""+ servers_root_path: Final = root_path if app.root_path_in_servers else ""+ return Response(_rendered(_SameSchema(schema), servers_root_path), media_type="application/json")++ app.router.routes[:] = [ # rebind-ok: the app owns its route table+ Route(openapi_url, openapi, include_in_schema=False) if _serves(route, openapi_url) else route+ for route in app.router.routes+ ]++[email protected]_cache(maxsize=1)+def _rendered(served: _SameSchema, root_path: str) -> bytes | memoryview:+ return JSONResponse(_with_root_path_server(served.schema, root_path) if root_path else served.schema).body+++def _with_root_path_server(schema: Mapping[str, object], root_path: str) -> Mapping[str, object]:+ servers: Final = _SERVERS.validate_python(schema.get("servers", []))+ if any(server.get("url") == root_path for server in servers):+ return schema+ return {**schema, "servers": [{"url": root_path}, *servers]}+++def _serves(route: BaseRoute, path: str) -> bool:+ return isinstance(route, Route) and route.path == pathdiff --git a/litellm/proxy/common_utils/openapi_schema_compat.py b/litellm/proxy/common_utils/openapi_schema_compat.pyindex 1826daa2762..5bc9121858c 100644--- a/litellm/proxy/common_utils/openapi_schema_compat.py+++ b/litellm/proxy/common_utils/openapi_schema_compat.py@@ -5,10 +5,33 @@ FastAPI 0.120+ has stricter schema generation that fails on certain types like oThis module provides a compatibility layer to handle these cases gracefully."""+import contextvars+import functoolsfrom typing import Finalfrom litellm._logging import verbose_proxy_logger+_BUILDING_OPENAPI_SCHEMA: Final = contextvars.ContextVar("building_openapi_schema", default=False)+++def _accept_unknown_types_while_building() -> None:+ from pydantic._internal._generate_schema import GenerateSchema+ from pydantic_core import core_schema++ reject_unknown_type: Final = (+ GenerateSchema._unknown_type_schema # pyright: ignore[reportPrivateUsage] # Pydantic schema internals+ )++ def unknown_type_schema(self: GenerateSchema, obj: object) -> core_schema.CoreSchema:+ if not _BUILDING_OPENAPI_SCHEMA.get():+ return reject_unknown_type(self, obj)+ if getattr(obj, "__module__", "") == "openai" and "Timeout" in str(obj):+ return core_schema.str_schema()+ return core_schema.any_schema()++ setattr(GenerateSchema, "_unknown_type_schema", unknown_type_schema)+def get_openapi_schema_with_compat(get_openapi_func,@@ -33,40 +56,9 @@ def get_openapi_schema_with_compat(Returns:OpenAPI schema dictionary"""- # FastAPI 0.120+ may fail schema generation for certain types (e.g., openai.Timeout)- # Patch Pydantic's schema generation to handle unknown types gracefullytry:- from pydantic._internal._generate_schema import GenerateSchema- from pydantic_core import core_schema-- # Store original method- original_unknown_type_schema: Final = (- GenerateSchema._unknown_type_schema # pyright: ignore[reportPrivateUsage] # Pydantic schema internals- )-- def patched_unknown_type_schema(self, obj):- """Patch to handle openai.Timeout and other non-serializable types"""- # Check if it's openai.Timeout or similar types- obj_str: Final = str(obj)- obj_module: Final = getattr(obj, "__module__", "")-- if (obj_module == "openai" and "Timeout" in obj_str) or (- hasattr(obj, "__name__") and obj.__name__ == "Timeout" and obj_module == "openai"- ):- # Return a simple string schema for Timeout types- return core_schema.str_schema()-- # For other unknown types, try to return a default schema- # This prevents the error from propagating- try:- return core_schema.any_schema()- except Exception:- # Last resort: return string schema- return core_schema.str_schema()-- # Apply patch- setattr(GenerateSchema, "_unknown_type_schema", patched_unknown_type_schema)-+ _accept_unknown_types_while_building()+ building: Final = _BUILDING_OPENAPI_SCHEMA.set(True)try:openapi_schema: Final = get_openapi_func(title=title,@@ -75,8 +67,7 @@ def get_openapi_schema_with_compat(routes=routes,)finally:- # Restore original method- setattr(GenerateSchema, "_unknown_type_schema", original_unknown_type_schema)+ _BUILDING_OPENAPI_SCHEMA.reset(building)return openapi_schemadiff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex bbdc996a027..581698626d5 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -1995,6 +1995,9 @@ vertex_live_passthrough_vertex_base: Final = VertexBase()### CUSTOM API DOCS [ENTERPRISE FEATURE] #### Custom OpenAPI schema generator to include only selected routesfrom fastapi.routing import APIWebSocketRoute+from starlette.routing import BaseRoute++from litellm.proxy.common_utils.openapi_route import OpenAPISchema, serve_openapi_off_the_event_loopdef _inject_websocket_stubs_into_openapi_schema(openapi_schema: dict, websocket_routes: list) -> dict:@@ -2041,10 +2044,19 @@ def _inject_websocket_stubs_into_openapi_schema(openapi_schema: dict, websocket_return openapi_schema-def get_openapi_schema():- if app.openapi_schema:- return app.openapi_schema+@dataclass(frozen=True, slots=True)+class _OpenAPIInputs:+ routes: tuple[BaseRoute, ...]+ loaded_lazy_modules: frozenset[str]++def _openapi_inputs() -> _OpenAPIInputs:+ from litellm.proxy._lazy_features import loaded_lazy_modules++ return _OpenAPIInputs(routes=tuple(app.routes), loaded_lazy_modules=loaded_lazy_modules(app))+++def _build_openapi_schema(inputs: _OpenAPIInputs) -> OpenAPISchema:# Use compatibility wrapper for FastAPI 0.120+ schema generationfrom litellm.proxy.common_utils.openapi_schema_compat import (get_openapi_schema_with_compat,@@ -2055,11 +2067,11 @@ def get_openapi_schema():title=app.title,version=app.version,description=app.description,- routes=app.routes,+ routes=list(inputs.routes),)# Find all WebSocket routes- websocket_routes: Final = [route for route in app.routes if isinstance(route, APIWebSocketRoute)]+ websocket_routes: Final = [route for route in inputs.routes if isinstance(route, APIWebSocketRoute)]# Add a synthetic GET stub for each so they render in Swagger UI,# without clobbering existing HTTP operations on the same path.@@ -2071,31 +2083,34 @@ def get_openapi_schema():openapi_schema = CustomOpenAPISpec.add_llm_api_request_schema_body(openapi_schema)# Stub unloaded lazy features so they appear as Swagger sections.- from litellm.proxy._lazy_features import inject_lazy_stubs, loaded_lazy_modules+ from litellm.proxy._lazy_features import inject_lazy_stubs- openapi_schema = inject_lazy_stubs(openapi_schema, loaded_lazy_modules(app))+ openapi_schema = inject_lazy_stubs(openapi_schema, inputs.loaded_lazy_modules)openapi_schema = ensure_unique_openapi_operation_ids(openapi_schema)# Fix Swagger UI execute path error when server_root_path is setif server_root_path:openapi_schema["servers"] = [{"url": "/" + server_root_path.strip("/")}]- app.openapi_schema = openapi_schema- return app.openapi_schema+ return openapi_schema-def custom_openapi():+def get_openapi_schema():if app.openapi_schema:return app.openapi_schema- openapi_schema = get_openapi_schema()+ app.openapi_schema = _build_openapi_schema(_openapi_inputs())+ return app.openapi_schema+- # Filter routes to include only specific ones- openai_routes: Final = LiteLLMRoutes.openai_routes.value- paths_to_include: Final[dict] = {}- for route in openai_routes:- if route in openapi_schema["paths"]:- paths_to_include[route] = openapi_schema["paths"][route]- openapi_schema["paths"] = paths_to_include+def _build_docs_filtered_openapi_schema(inputs: _OpenAPIInputs) -> OpenAPISchema:+ openapi_schema = _build_openapi_schema(inputs)++ all_paths: Final = openapi_schema.get("paths")+ openapi_schema["paths"] = (+ {route: all_paths[route] for route in LiteLLMRoutes.openai_routes.value if route in all_paths}+ if isinstance(all_paths, dict)+ else {}+ )# Add LLM API request schema bodies for documentationfrom litellm.proxy.common_utils.custom_openapi_spec import CustomOpenAPISpec@@ -2103,24 +2118,32 @@ def custom_openapi():openapi_schema = CustomOpenAPISpec.add_llm_api_request_schema_body(openapi_schema)# Stub unloaded lazy features so they appear as Swagger sections.- from litellm.proxy._lazy_features import inject_lazy_stubs, loaded_lazy_modules+ from litellm.proxy._lazy_features import inject_lazy_stubs- openapi_schema = inject_lazy_stubs(openapi_schema, loaded_lazy_modules(app))+ openapi_schema = inject_lazy_stubs(openapi_schema, inputs.loaded_lazy_modules)openapi_schema = ensure_unique_openapi_operation_ids(openapi_schema)# Fix Swagger UI execute path error when server_root_path is setif server_root_path:openapi_schema["servers"] = [{"url": "/" + server_root_path.strip("/")}]- app.openapi_schema = openapi_schema+ return openapi_schema+++def custom_openapi():+ if app.openapi_schema:+ return app.openapi_schema+ app.openapi_schema = _build_docs_filtered_openapi_schema(_openapi_inputs())return app.openapi_schemaif os.getenv("DOCS_FILTERED", "False") == "True" and premium_user:app.openapi = custom_openapi+ serve_openapi_off_the_event_loop(app, _openapi_inputs, _build_docs_filtered_openapi_schema)else:# For regular users, use get_openapi_schema to include LLM API schemasapp.openapi = get_openapi_schema+ serve_openapi_off_the_event_loop(app, _openapi_inputs, _build_openapi_schema)class UserAPIKeyCacheTTLEnum(enum.Enum):diff --git a/tests/unit/proxy/common_utils/test_openapi_route.py b/tests/unit/proxy/common_utils/test_openapi_route.pynew file mode 100644index 00000000000..1fe4aaf9e67--- /dev/null+++ b/tests/unit/proxy/common_utils/test_openapi_route.py@@ -0,0 +1,154 @@+import asyncio+import itertools+import threading+from _collections_abc import dict_items+from collections.abc import Callable+from typing import Final++import httpx+import pytest+from fastapi import FastAPI++from litellm.proxy.common_utils.custom_openapi_spec import JsonValue+from litellm.proxy.common_utils.openapi_route import OpenAPISchema, serve_openapi_off_the_event_loop++UNBLOCK_TIMEOUT_SECONDS: Final = 5+++def _route_paths(app: FastAPI) -> Callable[[], tuple[str, ...]]:+ return lambda: tuple(str(getattr(route, "path", "")) for route in app.routes)+++def _client(app: FastAPI, root_path: str = "") -> httpx.AsyncClient:+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app, root_path=root_path), base_url="http://proxy")+++async def _let_other_tasks_run() -> None:+ for _ in range(50):+ await asyncio.sleep(0)+++async def test_other_requests_are_answered_while_the_schema_builds():+ app: Final = FastAPI()+ app.add_api_route("/ping", lambda: "pong")+ build_started: Final = threading.Event()+ ping_answered: Final = threading.Event()++ def build(paths: tuple[str, ...]) -> OpenAPISchema:+ build_started.set()+ return {"ping_answered_during_build": ping_answered.wait(UNBLOCK_TIMEOUT_SECONDS)}++ serve_openapi_off_the_event_loop(app, _route_paths(app), build)+ async with _client(app) as client:+ schema_request: Final = asyncio.ensure_future(client.get("/openapi.json"))+ await asyncio.to_thread(build_started.wait, UNBLOCK_TIMEOUT_SECONDS)+ ping: Final = await client.get("/ping")+ ping_answered.set()+ schema: Final = await schema_request++ assert (ping.json(), schema.json()) == ("pong", {"ping_answered_during_build": True})+++async def test_a_route_added_during_the_build_is_in_the_next_schema():+ app: Final = FastAPI()+ build_started: Final = threading.Event()+ may_finish: Final = threading.Event()++ def build(paths: tuple[str, ...]) -> OpenAPISchema:+ build_started.set()+ may_finish.wait(UNBLOCK_TIMEOUT_SECONDS)+ return {"paths": [*paths]}++ serve_openapi_off_the_event_loop(app, _route_paths(app), build)+ async with _client(app) as client:+ first_request: Final = asyncio.ensure_future(client.get("/openapi.json"))+ await asyncio.to_thread(build_started.wait, UNBLOCK_TIMEOUT_SECONDS)+ app.add_api_route("/registered-mid-build", lambda: "late")+ may_finish.set()+ first: Final = await first_request+ second: Final = await client.get("/openapi.json")++ assert ("/registered-mid-build" in first.json()["paths"], "/registered-mid-build" in second.json()["paths"]) == (+ False,+ True,+ )+++async def test_concurrent_cold_requests_share_one_build():+ app: Final = FastAPI()+ build_numbers: Final = itertools.count()+ build_started: Final = threading.Event()+ may_finish: Final = threading.Event()++ def build(paths: tuple[str, ...]) -> OpenAPISchema:+ build_started.set()+ may_finish.wait(UNBLOCK_TIMEOUT_SECONDS)+ return {"build": next(build_numbers)}++ serve_openapi_off_the_event_loop(app, _route_paths(app), build)+ async with _client(app) as client:+ first_request: Final = asyncio.ensure_future(client.get("/openapi.json"))+ await asyncio.to_thread(build_started.wait, UNBLOCK_TIMEOUT_SECONDS)+ second_request: Final = asyncio.ensure_future(client.get("/openapi.json"))+ await _let_other_tasks_run()+ may_finish.set()+ responses: Final = await asyncio.gather(first_request, second_request)++ assert [response.json() for response in responses] == [{"build": 0}, {"build": 0}]+++async def test_warm_requests_reuse_the_rendered_schema():+ app: Final = FastAPI()+ renders: Final = itertools.count()++ class RenderCountingSchema(dict[str, JsonValue]):+ def items(self) -> "dict_items[str, JsonValue]":+ _ = next(renders)+ return super().items()++ serve_openapi_off_the_event_loop(app, _route_paths(app), lambda paths: RenderCountingSchema(paths=[*paths]))+ async with _client(app) as client:+ bodies: Final = [(await client.get("/openapi.json")).content for _ in range(3)]++ assert (len(set(bodies)), next(renders)) == (1, 1)+++async def test_a_rebuilt_schema_is_served_instead_of_the_previous_one():+ app: Final = FastAPI()+ builds: Final = itertools.count()+ serve_openapi_off_the_event_loop(app, _route_paths(app), lambda paths: {"build": next(builds)})++ async with _client(app) as client:+ first: Final = await client.get("/openapi.json")+ app.openapi_schema = None+ second: Final = await client.get("/openapi.json")++ assert (first.json(), second.json()) == ({"build": 0}, {"build": 1})++++async def test_an_app_that_replaces_its_openapi_function_serves_that_schema():+ app: Final = FastAPI()+ serve_openapi_off_the_event_loop(app, _route_paths(app), lambda paths: {"built_by": "the proxy"})+ app.openapi = lambda: {"built_by": "the operator"}++ async with _client(app) as client:+ response: Final = await client.get("/openapi.json")++ assert response.json() == {"built_by": "the operator"}++ ("servers", "expected"),+ [+ ([{"url": "https://docs.example"}], [{"url": "/api"}, {"url": "https://docs.example"}]),+ ([{"url": "/api"}], [{"url": "/api"}]),+ ],+)+async def test_the_root_path_is_listed_first_among_the_servers(servers: JsonValue, expected: JsonValue):+ app: Final = FastAPI()+ serve_openapi_off_the_event_loop(app, _route_paths(app), lambda paths: {"servers": servers})++ async with _client(app, root_path="/api") as client:+ response: Final = await client.get("/openapi.json")++ assert response.json()["servers"] == expecteddiff --git a/tests/unit/proxy/common_utils/test_openapi_schema_compat.py b/tests/unit/proxy/common_utils/test_openapi_schema_compat.pynew file mode 100644index 00000000000..39c508319f0--- /dev/null+++ b/tests/unit/proxy/common_utils/test_openapi_schema_compat.py@@ -0,0 +1,59 @@+import threading+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass, field+from typing import Final++import pytest+from pydantic import PydanticSchemaGenerationError, TypeAdapter++from litellm.proxy.common_utils.openapi_schema_compat import get_openapi_schema_with_compat++UNBLOCK_TIMEOUT_SECONDS: Final = 5+++@dataclass(frozen=True, slots=True)+class _BlockingBuild:+ started: threading.Event = field(default_factory=threading.Event)+ may_finish: threading.Event = field(default_factory=threading.Event)++ def __call__(self, **_: object) -> dict[str, object]:+ self.started.set()+ _ = self.may_finish.wait(UNBLOCK_TIMEOUT_SECONDS)+ return {}+++def test_only_the_build_documents_a_type_pydantic_cannot_describe():+ class Opaque:+ pass++ def build(**_: object) -> dict[str, object]:+ return {"opaque": TypeAdapter(Opaque).json_schema()}++ schema: Final = get_openapi_schema_with_compat(build, "title", "1.0.0", "", [])++ with pytest.raises(PydanticSchemaGenerationError):+ _ = TypeAdapter(Opaque)+ assert schema == {"opaque": {}}+++def test_code_outside_overlapping_builds_still_rejects_unknown_types():+ class Opaque:+ pass++ first: Final = _BlockingBuild()+ second: Final = _BlockingBuild()++ with ThreadPoolExecutor(max_workers=2) as pool:+ first_result: Final = pool.submit(get_openapi_schema_with_compat, first, "title", "1.0.0", "", [])+ _ = first.started.wait(UNBLOCK_TIMEOUT_SECONDS)+ second_result: Final = pool.submit(get_openapi_schema_with_compat, second, "title", "1.0.0", "", [])+ _ = second.started.wait(UNBLOCK_TIMEOUT_SECONDS)+ with pytest.raises(PydanticSchemaGenerationError):+ _ = TypeAdapter(Opaque)+ first.may_finish.set()+ _ = first_result.result()+ second.may_finish.set()+ _ = second_result.result()++ with pytest.raises(PydanticSchemaGenerationError):+ _ = TypeAdapter(Opaque)diff --git a/tests/unit/proxy/proxy_server/test_openapi_customization.py b/tests/unit/proxy/proxy_server/test_openapi_customization.pyindex 141b9f2a98a..6c588976efc 100644--- a/tests/unit/proxy/proxy_server/test_openapi_customization.py+++ b/tests/unit/proxy/proxy_server/test_openapi_customization.py@@ -13,16 +13,24 @@ Pins covered:from __future__ import annotations+import asyncio+import threadingfrom types import SimpleNamespace+from typing import Final+import httpximport pytestfrom fastapi import FastAPI+from pydantic import BaseModel, ConfigDict, GetJsonSchemaHandler+from pydantic.json_schema import JsonSchemaValue+from pydantic_core import CoreSchemafrom litellm.proxy.proxy_server import (_generate_stable_operation_id,_get_cors_config,_inject_websocket_stubs_into_openapi_schema,_strip_operation_id_method_suffix,+ app,custom_openapi,ensure_unique_openapi_operation_ids,get_openapi_schema,@@ -31,6 +39,8 @@ from litellm.proxy.proxy_server import (from .conftest import normalize+UNBLOCK_TIMEOUT_SECONDS: Final = 5+# ---------------------------------------------------------------------------# _generate_stable_operation_id# ---------------------------------------------------------------------------@@ -281,6 +291,37 @@ def test_get_openapi_schema_missing_app_attribute_raises_error(monkeypatch):get_openapi_schema()+async def test_a_request_is_answered_while_a_cold_openapi_json_builds(monkeypatch: pytest.MonkeyPatch):+ build_started: Final = threading.Event()+ liveliness_answered: Final = threading.Event()+ build_saw_the_answer: Final = threading.Event()++ class HoldsTheDocsBuild(BaseModel):+ model_config = ConfigDict(frozen=True)++ @classmethod+ def __get_pydantic_json_schema__(cls, schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue:+ build_started.set()+ if liveliness_answered.wait(UNBLOCK_TIMEOUT_SECONDS):+ build_saw_the_answer.set()+ return handler(schema)++ import litellm.proxy.proxy_server as ps++ proxy_app: Final = ps.app+ monkeypatch.setattr(proxy_app, "openapi_schema", None)+ monkeypatch.setattr(proxy_app.router, "routes", [*proxy_app.router.routes])+ proxy_app.add_api_route("/holds-the-docs-build", lambda: None, response_model=HoldsTheDocsBuild)+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=proxy_app), base_url="http://proxy") as client:+ docs_request: Final = asyncio.ensure_future(client.get("/openapi.json"))+ await asyncio.to_thread(build_started.wait, UNBLOCK_TIMEOUT_SECONDS)+ liveliness: Final = await client.get("/health/liveliness")+ liveliness_answered.set()+ docs: Final = await docs_request++ assert (liveliness.status_code, docs.status_code, build_saw_the_answer.is_set()) == (200, 200, True)++# ---------------------------------------------------------------------------# custom_openapi# ---------------------------------------------------------------------------