mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
* ci: restructure lint, unit and smoke workflows * ci: preserve source formatting in tier workflows * ci: retire per-shard coverage flags and tighten the tier workflow guards * test(ci): freeze the workflow startup safety models * ci: keep the current required check names running until the ruleset moves to the tier collectors --------- Co-authored-by: yuneng <yuneng@berri.ai>
174 lines
6.1 KiB
Python
174 lines
6.1 KiB
Python
"""
|
|
Per-feature OpenAPI snapshot for lazy-loaded routers.
|
|
|
|
The committed JSON is generated by `python -m litellm.proxy._lazy_openapi_snapshot`
|
|
and consumed at runtime so /openapi.json can show full route info for unloaded
|
|
features without importing them. test-linting.yml (mirrored locally by
|
|
`make check`) regenerates this file and fails when the committed copy differs,
|
|
then rebuilds schema.d.ts from app.openapi() with the snapshot injected. After
|
|
changing any lazily loaded route or this generator, rerun the module and commit
|
|
the JSON, then run `npm run gen:api` in ui/litellm-dashboard and commit schema.d.ts.
|
|
"""
|
|
|
|
import json
|
|
import re
|
|
import sys
|
|
from collections.abc import Callable, Mapping
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING, Final
|
|
|
|
from typing_extensions import ReadOnly, TypedDict
|
|
|
|
if TYPE_CHECKING:
|
|
from fastapi import FastAPI
|
|
|
|
from litellm.proxy._lazy_features import LazyFeature
|
|
|
|
SNAPSHOT_FILE: Final = Path(__file__).parent / "_lazy_openapi_snapshot.json"
|
|
HTTP_METHOD_SUFFIXES: Final = {
|
|
"delete",
|
|
"get",
|
|
"head",
|
|
"options",
|
|
"patch",
|
|
"post",
|
|
"put",
|
|
"trace",
|
|
}
|
|
|
|
|
|
def _stabilize_multi_method_route_ids(routes) -> None:
|
|
"""FastAPI derives route IDs from a set of methods; make snapshots stable."""
|
|
|
|
for route in routes:
|
|
methods = sorted(getattr(route, "methods", None) or [])
|
|
if len(methods) <= 1 or not getattr(route, "path_format", None):
|
|
continue
|
|
|
|
operation_id = f"{route.name}{route.path_format}"
|
|
operation_id = re.sub(r"\W", "_", operation_id)
|
|
route.unique_id = f"{operation_id}_{methods[0].lower()}"
|
|
|
|
|
|
def load_snapshot() -> dict[str, dict] | None:
|
|
if not SNAPSHOT_FILE.exists():
|
|
return None
|
|
try:
|
|
with SNAPSHOT_FILE.open() as f:
|
|
return json.load(f)
|
|
except (json.JSONDecodeError, OSError):
|
|
return None
|
|
|
|
|
|
def _normalize_operation_ids(paths: dict[str, dict]) -> None:
|
|
"""Make FastAPI-generated operation IDs stable for multi-method routes.
|
|
|
|
FastAPI derives the default operation ID suffix from the first item in the
|
|
route's methods set. For routes registered with several HTTP methods, that
|
|
set iteration order can vary between processes, which makes the snapshot
|
|
drift even when no routes changed.
|
|
"""
|
|
for path_ops in paths.values():
|
|
if not isinstance(path_ops, dict):
|
|
continue
|
|
|
|
methods = {method for method in path_ops if method in HTTP_METHOD_SUFFIXES}
|
|
if not methods:
|
|
continue
|
|
|
|
for method, operation in path_ops.items():
|
|
if method not in HTTP_METHOD_SUFFIXES or not isinstance(operation, dict):
|
|
continue
|
|
|
|
operation_id = operation.get("operationId")
|
|
if not isinstance(operation_id, str):
|
|
continue
|
|
|
|
for suffix in methods:
|
|
suffix_token = f"_{suffix}"
|
|
if operation_id.endswith(suffix_token):
|
|
operation["operationId"] = operation_id[: -len(suffix_token)] + f"_{method}"
|
|
break
|
|
|
|
|
|
class SnapshotFragment(TypedDict):
|
|
paths: ReadOnly[Mapping[str, Mapping[str, object]]]
|
|
components: ReadOnly[Mapping[str, Mapping[str, object]]]
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class SnapshotResult:
|
|
fragments: Mapping[str, SnapshotFragment]
|
|
skipped: tuple[str, ...]
|
|
|
|
|
|
def _register_feature(app: "FastAPI", feat: "LazyFeature") -> str | None:
|
|
import importlib
|
|
|
|
try:
|
|
feat.register_fn(app, importlib.import_module(feat.module_path))
|
|
except Exception as exc:
|
|
sys.stderr.write(f"warning: skip {feat.name}: {exc}\n")
|
|
return feat.name
|
|
return None
|
|
|
|
|
|
def _feature_fragment(app: "FastAPI", feat: "LazyFeature", used_operation_ids: set[str]) -> SnapshotFragment | None:
|
|
from fastapi.openapi.utils import get_openapi
|
|
|
|
from litellm.proxy.proxy_server import ensure_unique_openapi_operation_ids
|
|
|
|
feat_routes: Final = [r for r in app.routes if feat.matches(getattr(r, "path", ""))]
|
|
if not feat_routes:
|
|
return None
|
|
_stabilize_multi_method_route_ids(feat_routes)
|
|
full: Final = get_openapi(title=app.title, version=app.version, routes=feat_routes)
|
|
paths: Final = full.get("paths", {})
|
|
_normalize_operation_ids(paths)
|
|
for path_ops in paths.values():
|
|
for method, op in path_ops.items():
|
|
if isinstance(op, dict):
|
|
operation_id = op.get("operationId")
|
|
if isinstance(operation_id, str):
|
|
for suffix in HTTP_METHOD_SUFFIXES:
|
|
if operation_id.endswith(f"_{suffix}"):
|
|
op["operationId"] = operation_id[: -len(suffix)] + method
|
|
break
|
|
op["tags"] = [feat.name]
|
|
unique: Final = ensure_unique_openapi_operation_ids(full, used_operation_ids)
|
|
return {
|
|
"paths": paths,
|
|
"components": {"schemas": unique.get("components", {}).get("schemas", {})},
|
|
}
|
|
|
|
|
|
def generate_snapshot() -> SnapshotResult:
|
|
from litellm.proxy._lazy_features import LAZY_FEATURES
|
|
from litellm.proxy.proxy_server import app
|
|
|
|
skipped: Final = tuple(name for feat in LAZY_FEATURES if (name := _register_feature(app, feat)) is not None)
|
|
used_operation_ids: Final[set[str]] = set()
|
|
fragments: Final = {
|
|
feat.name: fragment
|
|
for feat in LAZY_FEATURES
|
|
if (fragment := _feature_fragment(app, feat, used_operation_ids)) is not None
|
|
}
|
|
return SnapshotResult(fragments=fragments, skipped=skipped)
|
|
|
|
|
|
def main(snapshot_file: Path = SNAPSHOT_FILE, generate: Callable[[], SnapshotResult] = generate_snapshot) -> int:
|
|
result: Final = generate()
|
|
if result.skipped:
|
|
sys.stderr.write(
|
|
f"error: {len(result.skipped)} feature(s) failed to import, so their fragments would vanish from the "
|
|
f"snapshot: {', '.join(result.skipped)}\n"
|
|
)
|
|
return 1
|
|
snapshot_file.write_text(json.dumps(result.fragments, indent=2, sort_keys=True) + "\n")
|
|
sys.stdout.write(f"wrote {len(result.fragments)} feature fragments to {snapshot_file}\n")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|