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]

[Bug Fix] Add swagger docs for LiteLLM /chat/completions, /embeddings, /responses (#12618)

Ishaan Jaff46c950b17bb9
diff --git a/.github/workflows/test-litellm.yml b/.github/workflows/test-litellm.yml
index 3a61728305f..df6dfa2e686 100644
--- a/.github/workflows/test-litellm.yml
+++ b/.github/workflows/test-litellm.yml
@@ -7,7 +7,7 @@ on:
jobs:
test:
runs-on: ubuntu-latest
- timeout-minutes: 15
+ timeout-minutes: 20
steps:
- uses: actions/checkout@v4
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index b281c20b25b..fc2920ae093 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -16,7 +16,11 @@ from pydantic import (
from typing_extensions import Required, TypedDict
from litellm.types.integrations.slack_alerting import AlertType
-from litellm.types.llms.openai import AllMessageValues, OpenAIFileObject
+from litellm.types.llms.openai import (
+ AllMessageValues,
+ ChatCompletionRequest,
+ OpenAIFileObject,
+)
from litellm.types.mcp import (
MCPAuthType,
MCPSpecVersion,
@@ -558,44 +562,14 @@ class LiteLLMPromptInjectionParams(LiteLLMPydanticObjectBase):
)
return values
-
######### Request Class Definition ######
-class ProxyChatCompletionRequest(LiteLLMPydanticObjectBase):
- model: str
- messages: List[Dict[str, str]]
- temperature: Optional[float] = None
- top_p: Optional[float] = None
- n: Optional[int] = None
- stream: Optional[bool] = None
- stop: Optional[List[str]] = None
- max_tokens: Optional[int] = None
- presence_penalty: Optional[float] = None
- frequency_penalty: Optional[float] = None
- logit_bias: Optional[Dict[str, float]] = None
- user: Optional[str] = None
- response_format: Optional[Dict[str, str]] = None
- seed: Optional[int] = None
- tools: Optional[List[str]] = None
- tool_choice: Optional[str] = None
- functions: Optional[List[str]] = None # soon to be deprecated
- function_call: Optional[str] = None # soon to be deprecated
-
+class ProxyChatCompletionRequest(ChatCompletionRequest):
# Optional LiteLLM params
- caching: Optional[bool] = None
- api_base: Optional[str] = None
- api_version: Optional[str] = None
- api_key: Optional[str] = None
- num_retries: Optional[int] = None
- context_window_fallback_dict: Optional[Dict[str, str]] = None
- fallbacks: Optional[List[str]] = None
- metadata: Optional[Dict[str, str]] = {}
- deployment_id: Optional[str] = None
- request_timeout: Optional[int] = None
-
- model_config = ConfigDict(
- extra="allow"
- ) # allow params not defined here, these fall in litellm.completion(**kwargs)
-
+ guardrails: Optional[List[str]]
+ caching: Optional[bool]
+ num_retries: Optional[int]
+ context_window_fallback_dict: Optional[Dict[str, str]]
+ fallbacks: Optional[List[str]]
class ModelInfoDelete(LiteLLMPydanticObjectBase):
id: str
diff --git a/litellm/proxy/common_utils/custom_openapi_spec.py b/litellm/proxy/common_utils/custom_openapi_spec.py
new file mode 100644
index 00000000000..f2960bac297
--- /dev/null
+++ b/litellm/proxy/common_utils/custom_openapi_spec.py
@@ -0,0 +1,240 @@
+from typing import Any, Dict, List, Optional, Type
+
+from litellm._logging import verbose_proxy_logger
+
+
+class CustomOpenAPISpec:
+ """
+ Handler for customizing OpenAPI specifications with Pydantic models
+ for documentation purposes without runtime validation.
+ """
+
+ CHAT_COMPLETION_PATHS = [
+ "/v1/chat/completions",
+ "/chat/completions",
+ "/engines/{model}/chat/completions",
+ "/openai/deployments/{model}/chat/completions"
+ ]
+
+ EMBEDDING_PATHS = [
+ "/v1/embeddings",
+ "/embeddings",
+ "/engines/{model}/embeddings",
+ "/openai/deployments/{model}/embeddings"
+ ]
+
+ RESPONSES_API_PATHS = [
+ "/v1/responses",
+ "/responses"
+ ]
+
+ @staticmethod
+ def get_pydantic_schema(model_class) -> Optional[Dict[str, Any]]:
+ """
+ Get JSON schema from a Pydantic model, handling both v1 and v2 APIs.
+
+ Args:
+ model_class: Pydantic model class
+
+ Returns:
+ JSON schema dict or None if failed
+ """
+ try:
+ # Try Pydantic v2 method first
+ return model_class.model_json_schema() # type: ignore
+ except AttributeError:
+ try:
+ # Fallback to Pydantic v1 method
+ return model_class.schema() # type: ignore
+ except AttributeError:
+ # If both methods fail, return None
+ return None
+
+ @staticmethod
+ def add_schema_to_components(openapi_schema: Dict[str, Any], schema_name: str, schema_def: Dict[str, Any]) -> None:
+ """
+ Add a schema definition to the OpenAPI components/schemas section.
+
+ Args:
+ openapi_schema: The OpenAPI schema dict to modify
+ schema_name: Name for the schema component
+ schema_def: The schema definition
+ """
+ # Ensure components/schemas structure exists
+ if "components" not in openapi_schema:
+ openapi_schema["components"] = {}
+ if "schemas" not in openapi_schema["components"]:
+ openapi_schema["components"]["schemas"] = {}
+
+ # Add the schema
+ openapi_schema["components"]["schemas"][schema_name] = schema_def
+
+ @staticmethod
+ def add_request_body_to_paths(openapi_schema: Dict[str, Any], paths: List[str], schema_ref: str) -> None:
+ """
+ Add request body schema reference to specified paths.
+
+ Args:
+ openapi_schema: The OpenAPI schema dict to modify
+ paths: List of paths to update
+ schema_ref: Reference to the schema component (e.g., "#/components/schemas/ModelName")
+ """
+ for path in paths:
+ if path in openapi_schema.get("paths", {}) and "post" in openapi_schema["paths"][path]:
+ openapi_schema["paths"][path]["post"]["requestBody"] = {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": schema_ref
+ }
+ }
+ }
+ }
+
+ @staticmethod
+ def add_request_schema(
+ openapi_schema: Dict[str, Any],
+ model_class: Type,
+ schema_name: str,
+ paths: List[str],
+ operation_name: str
+ ) -> Dict[str, Any]:
+ """
+ Generic method to add a request schema to OpenAPI specification.
+
+ Args:
+ openapi_schema: The OpenAPI schema dict to modify
+ model_class: The Pydantic model class to get schema from
+ schema_name: Name for the schema component
+ paths: List of paths to add the request body to
+ operation_name: Name of the operation for logging (e.g., "chat completion", "embedding")
+
+ Returns:
+ Modified OpenAPI schema
+ """
+ try:
+ # Get the schema for the model class
+ request_schema = CustomOpenAPISpec.get_pydantic_schema(model_class)
+
+ # Only proceed if we successfully got the schema
+ if request_schema is not None:
+ # Add schema to components
+ CustomOpenAPISpec.add_schema_to_components(openapi_schema, schema_name, request_schema)
+
+ # Add request body to specified endpoints
+ CustomOpenAPISpec.add_request_body_to_paths(
+ openapi_schema,
+ paths,
+ f"#/components/schemas/{schema_name}"
+ )
+
+ verbose_proxy_logger.debug(f"Successfully added {schema_name} schema to OpenAPI spec")
+ else:
+ verbose_proxy_logger.debug(f"Could not get schema for {schema_name}")
+
+ except Exception as e:
+ # If schema addition fails, continue without it
+ verbose_proxy_logger.debug(f"Failed to add {operation_name} request schema: {str(e)}")
+
+ return openapi_schema
+
+ @staticmethod
+ def add_chat_completion_request_schema(openapi_schema: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Add ProxyChatCompletionRequest schema to chat completion endpoints for documentation.
+ This shows the request body in Swagger without runtime validation.
+
+ Args:
+ openapi_schema: The OpenAPI schema dict to modify
+
+ Returns:
+ Modified OpenAPI schema
+ """
+ try:
+ from litellm.proxy._types import ProxyChatCompletionRequest
+
+ return CustomOpenAPISpec.add_request_schema(
+ openapi_schema=openapi_schema,
+ model_class=ProxyChatCompletionRequest,
+ schema_name="ProxyChatCompletionRequest",
+ paths=CustomOpenAPISpec.CHAT_COMPLETION_PATHS,
+ operation_name="chat completion"
+ )
+ except ImportError as e:
+ verbose_proxy_logger.debug(f"Failed to import ProxyChatCompletionRequest: {str(e)}")
+ return openapi_schema
+
+ @staticmethod
+ def add_embedding_request_schema(openapi_schema: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Add EmbeddingRequest schema to embedding endpoints for documentation.
+ This shows the request body in Swagger without runtime validation.
+
+ Args:
+ openapi_schema: The OpenAPI schema dict to modify
+
+ Returns:
+ Modified OpenAPI schema
+ """
+ try:
+ from litellm.types.embedding import EmbeddingRequest
+
+ return CustomOpenAPISpec.add_request_schema(
+ openapi_schema=openapi_schema,
+ model_class=EmbeddingRequest,
+ schema_name="EmbeddingRequest",
+ paths=CustomOpenAPISpec.EMBEDDING_PATHS,
+ operation_name="embedding"
+ )
+ except ImportError as e:
+ verbose_proxy_logger.debug(f"Failed to import EmbeddingRequest: {str(e)}")
+ return openapi_schema
+
+ @staticmethod
+ def add_responses_api_request_schema(openapi_schema: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Add ResponsesAPIRequestParams schema to responses API endpoints for documentation.
+ This shows the request body in Swagger without runtime validation.
+
+ Args:
+ openapi_schema: The OpenAPI schema dict to modify
+
+ Returns:
+ Modified OpenAPI schema
+ """
+ try:
+ from litellm.types.llms.openai import ResponsesAPIRequestParams
+
+ return CustomOpenAPISpec.add_request_schema(
+ openapi_schema=openapi_schema,
+ model_class=ResponsesAPIRequestParams,
+ schema_name="ResponsesAPIRequestParams",
+ paths=CustomOpenAPISpec.RESPONSES_API_PATHS,
+ operation_name="responses API"
+ )
+ except ImportError as e:
+ verbose_proxy_logger.debug(f"Failed to import ResponsesAPIRequestParams: {str(e)}")
+ return openapi_schema
+
+ @staticmethod
+ def add_llm_api_request_schema_body(openapi_schema: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Add LLM API request schema bodies to OpenAPI specification for documentation.
+
+ Args:
+ openapi_schema: The base OpenAPI schema
+
+ Returns:
+ OpenAPI schema with added request body schemas
+ """
+ # Add chat completion request schema
+ openapi_schema = CustomOpenAPISpec.add_chat_completion_request_schema(openapi_schema)
+
+ # Add embedding request schema
+ openapi_schema = CustomOpenAPISpec.add_embedding_request_schema(openapi_schema)
+
+ # Add responses API request schema
+ openapi_schema = CustomOpenAPISpec.add_responses_api_request_schema(openapi_schema)
+
+ return openapi_schema
\ No newline at end of file
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 15329589bb8..a427253a22e 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -734,6 +734,11 @@ def custom_openapi():
if route in openapi_schema["paths"]:
paths_to_include[route] = openapi_schema["paths"][route]
openapi_schema["paths"] = paths_to_include
+
+ # Add LLM API request schema bodies for documentation
+ from litellm.proxy.common_utils.custom_openapi_spec import CustomOpenAPISpec
+ openapi_schema = CustomOpenAPISpec.add_llm_api_request_schema_body(openapi_schema)
+
app.openapi_schema = openapi_schema
return app.openapi_schema
diff --git a/tests/test_litellm/proxy/common_utils/test_custom_openapi_spec.py b/tests/test_litellm/proxy/common_utils/test_custom_openapi_spec.py
new file mode 100644
index 00000000000..8dd99e2ae59
--- /dev/null
+++ b/tests/test_litellm/proxy/common_utils/test_custom_openapi_spec.py
@@ -0,0 +1,91 @@
+"""
+Simple unit tests for CustomOpenAPISpec class.
+
+Tests basic functionality of OpenAPI schema generation.
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from litellm.proxy.common_utils.custom_openapi_spec import CustomOpenAPISpec
+
+
+class TestCustomOpenAPISpec:
+ """Test suite for CustomOpenAPISpec class."""
+
+ @pytest.fixture
+ def base_openapi_schema(self):
+ """Base OpenAPI schema for testing."""
+ return {
+ "openapi": "3.0.0",
+ "info": {"title": "Test API", "version": "1.0.0"},
+ "paths": {
+ "/v1/chat/completions": {
+ "post": {
+ "summary": "Chat completions"
+ }
+ },
+ "/v1/embeddings": {
+ "post": {
+ "summary": "Embeddings"
+ }
+ },
+ "/v1/responses": {
+ "post": {
+ "summary": "Responses API"
+ }
+ }
+ }
+ }
+
+ @patch('litellm.proxy.common_utils.custom_openapi_spec.CustomOpenAPISpec.add_request_schema')
+ def test_add_chat_completion_request_schema(self, mock_add_schema, base_openapi_schema):
+ """Test that chat completion schema is added correctly."""
+ mock_add_schema.return_value = base_openapi_schema
+
+ with patch('litellm.proxy._types.ProxyChatCompletionRequest') as mock_model:
+ result = CustomOpenAPISpec.add_chat_completion_request_schema(base_openapi_schema)
+
+ mock_add_schema.assert_called_once_with(
+ openapi_schema=base_openapi_schema,
+ model_class=mock_model,
+ schema_name="ProxyChatCompletionRequest",
+ paths=CustomOpenAPISpec.CHAT_COMPLETION_PATHS,
+ operation_name="chat completion"
+ )
+ assert result == base_openapi_schema
+
+ @patch('litellm.proxy.common_utils.custom_openapi_spec.CustomOpenAPISpec.add_request_schema')
+ def test_add_embedding_request_schema(self, mock_add_schema, base_openapi_schema):
+ """Test that embedding schema is added correctly."""
+ mock_add_schema.return_value = base_openapi_schema
+
+ with patch('litellm.types.embedding.EmbeddingRequest') as mock_model:
+ result = CustomOpenAPISpec.add_embedding_request_schema(base_openapi_schema)
+
+ mock_add_schema.assert_called_once_with(
+ openapi_schema=base_openapi_schema,
+ model_class=mock_model,
+ schema_name="EmbeddingRequest",
+ paths=CustomOpenAPISpec.EMBEDDING_PATHS,
+ operation_name="embedding"
+ )
+ assert result == base_openapi_schema
+
+ @patch('litellm.proxy.common_utils.custom_openapi_spec.CustomOpenAPISpec.add_request_schema')
+ def test_add_responses_api_request_schema(self, mock_add_schema, base_openapi_schema):
+ """Test that responses API schema is added correctly."""
+ mock_add_schema.return_value = base_openapi_schema
+
+ with patch('litellm.types.llms.openai.ResponsesAPIRequestParams') as mock_model:
+ result = CustomOpenAPISpec.add_responses_api_request_schema(base_openapi_schema)
+
+ mock_add_schema.assert_called_once_with(
+ openapi_schema=base_openapi_schema,
+ model_class=mock_model,
+ schema_name="ResponsesAPIRequestParams",
+ paths=CustomOpenAPISpec.RESPONSES_API_PATHS,
+ operation_name="responses API"
+ )
+ assert result == base_openapi_schema
\ No newline at end of file