litellm/litellm/proxy/common_utils/openapi_schema_compat.py
Mateo Wang 58258409c9
refactor(proxy): expose public names for private proxy helpers (#45170)
* refactor(proxy): expose public names for private proxy helpers

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(proxy): keep original class names behind public aliases

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(proxy): preserve internal callback filtering

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(proxy): keep _PROXY_ class names for managed files hooks

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(proxy): keep old private names in package exports

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(proxy): preserve recursive auth helper name

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(proxy): align MCP limiter tests with server enforcement

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(proxy): match main's MCP limiter tests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(proxy): keep old private names bound in importing modules

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(proxy): preserve compatibility imports through strict lint

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(proxy): use exact pyright suppression in password helper test

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* style(proxy): add reasons to compatibility import noqa comments

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(proxy): update IN-list baseline for renamed helpers

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 18:59:27 -07:00

116 lines
4.4 KiB
Python

"""
Utility module for handling OpenAPI schema generation compatibility with FastAPI 0.120+.
FastAPI 0.120+ has stricter schema generation that fails on certain types like openai.Timeout.
This module provides a compatibility layer to handle these cases gracefully.
"""
from typing import Any, Final
from litellm._logging import verbose_proxy_logger
def get_openapi_schema_with_compat(
get_openapi_func,
title: str,
version: str,
description: str,
routes: list,
) -> dict[str, Any]:
"""
Generate OpenAPI schema with compatibility handling for FastAPI 0.120+.
This function patches Pydantic's schema generation to handle non-serializable types
like openai.Timeout that cause PydanticSchemaGenerationError in FastAPI 0.120+.
Args:
get_openapi_func: The FastAPI get_openapi function
title: API title
version: API version
description: API description
routes: List of routes
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 gracefully
try:
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)
try:
openapi_schema: Final = get_openapi_func(
title=title,
version=version,
description=description,
routes=routes,
)
finally:
# Restore original method
setattr(GenerateSchema, "_unknown_type_schema", original_unknown_type_schema)
return openapi_schema
except (ImportError, AttributeError) as e:
# If patching fails, try normal generation with error handling
verbose_proxy_logger.debug("Could not patch Pydantic schema generation: %s. Trying normal generation.", e)
try:
return get_openapi_func(
title=title,
version=version,
description=description,
routes=routes,
)
except Exception as pydantic_error:
# Check if it's a PydanticSchemaGenerationError by checking the error type name
# This avoids import issues if PydanticSchemaGenerationError is not available
error_type_name: Final = type(pydantic_error).__name__
if error_type_name == "PydanticSchemaGenerationError" or "PydanticSchemaGenerationError" in str(
type(pydantic_error)
):
# If we still get the error, log it and return minimal schema
verbose_proxy_logger.warning(
"PydanticSchemaGenerationError during schema generation: %s", pydantic_error
)
return {
"openapi": "3.0.0",
"info": {
"title": title,
"version": version,
"description": description or "",
},
"paths": {},
"components": {"schemas": {}},
}
else:
# Re-raise if it's a different error
raise