Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modifying exception classes that descend from BadRequestError … #6883

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 18 additions & 17 deletions docs/my-website/docs/exception_mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,29 @@ All exceptions can be imported from `litellm` - e.g. `from litellm import BadReq

## LiteLLM Exceptions

| Status Code | Error Type | Inherits from | Description |
|-------------|--------------------------|---------------|-------------|
| Status Code | Error Type | Inherits from | Description |
|-------------|--------------------------|---------------|-------------------------------------------------------------------------------------------------------------------------------------|
| 400 | BadRequestError | openai.BadRequestError |
| 400 | UnsupportedParamsError | litellm.BadRequestError | Raised when unsupported params are passed |
| 400 | ContextWindowExceededError| litellm.BadRequestError | Special error type for context window exceeded error messages - enables context window fallbacks |
| 400 | ContentPolicyViolationError| litellm.BadRequestError | Special error type for content policy violation error messages - enables content policy fallbacks |
| 400 | InvalidRequestError | openai.BadRequestError | Deprecated error, use BadRequestError instead |
| 400 | UnsupportedParamsError | litellm.BadRequestError | Raised when unsupported params are passed |
| 400 | ContextWindowExceededError| litellm.BadRequestError | Special error type for context window exceeded error messages - enables context window fallbacks |
| 400 | ContentPolicyViolationError| litellm.BadRequestError | Special error type for content policy violation error messages - enables content policy fallbacks |
| 400 | InvalidRequestError | openai.BadRequestError | Deprecated error, use BadRequestError instead |
| 400 | RejectedRequestError | openai.BadRequestError | Meant to help us catch guardrails-related errors on proxy. |
| 401 | AuthenticationError | openai.AuthenticationError |
| 403 | PermissionDeniedError | openai.PermissionDeniedError |
| 404 | NotFoundError | openai.NotFoundError | raise when invalid models passed, example gpt-8 |
| 408 | Timeout | openai.APITimeoutError | Raised when a timeout occurs |
| 404 | NotFoundError | openai.NotFoundError | raise when invalid models passed, example gpt-8 |
| 408 | Timeout | openai.APITimeoutError | Raised when a timeout occurs |
| 422 | UnprocessableEntityError | openai.UnprocessableEntityError |
| 429 | RateLimitError | openai.RateLimitError |
| 500 | APIConnectionError | openai.APIConnectionError | If any unmapped error is returned, we return this error |
| 500 | APIError | openai.APIError | Generic 500-status code error |
| 503 | ServiceUnavailableError | openai.APIStatusError | If provider returns a service unavailable error, this error is raised |
| >=500 | InternalServerError | openai.InternalServerError | If any unmapped 500-status code error is returned, this error is raised |
| N/A | APIResponseValidationError | openai.APIResponseValidationError | If Rules are used, and request/response fails a rule, this error is raised |
| N/A | BudgetExceededError | Exception | Raised for proxy, when budget is exceeded |
| N/A | JSONSchemaValidationError | litellm.APIResponseValidationError | Raised when response does not match expected json schema - used if `response_schema` param passed in with `enforce_validation=True` |
| N/A | MockException | Exception | Internal exception, raised by mock_completion class. Do not use directly |
| N/A | OpenAIError | openai.OpenAIError | Deprecated internal exception, inherits from openai.OpenAIError. |
| 500 | APIConnectionError | openai.APIConnectionError | If any unmapped error is returned, we return this error |
| 500 | APIError | openai.APIError | Generic 500-status code error |
| 503 | ServiceUnavailableError | openai.APIStatusError | If provider returns a service unavailable error, this error is raised |
| >=500 | InternalServerError | openai.InternalServerError | If any unmapped 500-status code error is returned, this error is raised |
| N/A | APIResponseValidationError | openai.APIResponseValidationError | If Rules are used, and request/response fails a rule, this error is raised |
| N/A | BudgetExceededError | Exception | Raised for proxy, when budget is exceeded |
| N/A | JSONSchemaValidationError | litellm.APIResponseValidationError | Raised when response does not match expected json schema - used if `response_schema` param passed in with `enforce_validation=True` |
| N/A | MockException | Exception | Internal exception, raised by mock_completion class. Do not use directly |
| N/A | OpenAIError | openai.OpenAIError | Deprecated internal exception, inherits from openai.OpenAIError. |



Expand Down
56 changes: 29 additions & 27 deletions litellm/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
import httpx
import openai

#this is an odd import. Seems like a testing artifact?
#from tests.old_proxy_tests.tests.test_gemini_context_caching import response

MOCKREQUEST = httpx.Request(method="GET", url="https://litellm.ai")

class AuthenticationError(openai.AuthenticationError): # type: ignore
def __init__(
Expand All @@ -35,9 +39,7 @@ def __init__(
self.num_retries = num_retries
self.response = response or httpx.Response(
status_code=self.status_code,
request=httpx.Request(
method="GET", url="https://litellm.ai"
), # mock request object
request=MOCKREQUEST, # mock request object
)
super().__init__(
self.message, response=self.response, body=None
Expand Down Expand Up @@ -81,9 +83,7 @@ def __init__(
self.num_retries = num_retries
self.response = response or httpx.Response(
status_code=self.status_code,
request=httpx.Request(
method="GET", url="https://litellm.ai"
), # mock request object
request=MOCKREQUEST, # mock request object
)
super().__init__(
self.message, response=self.response, body=None
Expand Down Expand Up @@ -122,16 +122,17 @@ def __init__(
self.model = model
self.llm_provider = llm_provider
self.litellm_debug_info = litellm_debug_info
response = httpx.Response(
response_content = getattr(response,"content",None) if response else None
response_request = getattr(response,"request",MOCKREQUEST) if response else MOCKREQUEST
_response = httpx.Response(
status_code=self.status_code,
request=httpx.Request(
method="GET", url="https://litellm.ai"
), # mock request object
request=response_request,
content=response_content,
)
self.max_retries = max_retries
self.num_retries = num_retries
super().__init__(
self.message, response=response, body=None
self.message, response=_response, body=None
) # Call the base class constructor with the parameters it needs

def __str__(self):
Expand Down Expand Up @@ -295,6 +296,7 @@ def __init__(
_response_headers = (
getattr(response, "headers", None) if response is not None else None
)

self.response = httpx.Response(
status_code=429,
headers=_response_headers,
Expand Down Expand Up @@ -334,18 +336,15 @@ def __init__(
response: Optional[httpx.Response] = None,
litellm_debug_info: Optional[str] = None,
):
self.status_code = 400
self.message = "litellm.ContextWindowExceededError: {}".format(message)
self.model = model
self.llm_provider = llm_provider
self.litellm_debug_info = litellm_debug_info
request = httpx.Request(method="POST", url="https://api.openai.com/v1")
self.response = httpx.Response(status_code=400, request=request)
super().__init__(
message=self.message,
model=self.model, # type: ignore
llm_provider=self.llm_provider, # type: ignore
response=self.response,
response=response,
litellm_debug_info=self.litellm_debug_info,
) # Call the base class constructor with the parameters it needs

Expand All @@ -355,7 +354,7 @@ def __str__(self):
_message += f" LiteLLM Retried: {self.num_retries} times"
if self.max_retries:
_message += f", LiteLLM Max Retries: {self.max_retries}"
return _message
return repr(_message)

def __repr__(self):
_message = self.message
Expand All @@ -376,7 +375,6 @@ def __init__(
request_data: dict,
litellm_debug_info: Optional[str] = None,
):
self.status_code = 400
self.message = "litellm.RejectedRequestError: {}".format(message)
self.model = model
self.llm_provider = llm_provider
Expand Down Expand Up @@ -424,13 +422,11 @@ def __init__(
self.model = model
self.llm_provider = llm_provider
self.litellm_debug_info = litellm_debug_info
request = httpx.Request(method="POST", url="https://api.openai.com/v1")
self.response = httpx.Response(status_code=400, request=request)
super().__init__(
message=self.message,
model=self.model, # type: ignore
llm_provider=self.llm_provider, # type: ignore
response=self.response,
response=response,
litellm_debug_info=self.litellm_debug_info,
) # Call the base class constructor with the parameters it needs

Expand Down Expand Up @@ -469,7 +465,7 @@ def __init__(
self.litellm_debug_info = litellm_debug_info
self.max_retries = max_retries
self.num_retries = num_retries
self.response = httpx.Response(
self.response = response or httpx.Response(
status_code=self.status_code,
request=httpx.Request(
method="POST",
Expand Down Expand Up @@ -515,7 +511,7 @@ def __init__(
self.litellm_debug_info = litellm_debug_info
self.max_retries = max_retries
self.num_retries = num_retries
self.response = httpx.Response(
self.response = response or httpx.Response(
status_code=self.status_code,
request=httpx.Request(
method="POST",
Expand Down Expand Up @@ -601,10 +597,10 @@ def __init__(
self.model = model
self.status_code = 500
self.litellm_debug_info = litellm_debug_info
self.request = httpx.Request(method="POST", url="https://api.openai.com/v1")
_request = request or httpx.Request(method="POST", url="https://api.openai.com/v1")
self.max_retries = max_retries
self.num_retries = num_retries
super().__init__(message=self.message, request=self.request)
super().__init__(message=self.message, request=_request)

def __str__(self):
_message = self.message
Expand Down Expand Up @@ -663,7 +659,7 @@ def __repr__(self):

class JSONSchemaValidationError(APIResponseValidationError):
def __init__(
self, model: str, llm_provider: str, raw_response: str, schema: str
self, model: str, llm_provider: str, raw_response: str, schema: str,
) -> None:
self.raw_response = raw_response
self.schema = schema
Expand Down Expand Up @@ -693,19 +689,25 @@ def __init__(
max_retries: Optional[int] = None,
num_retries: Optional[int] = None,
):
self.status_code = 400
self.message = "litellm.UnsupportedParamsError: {}".format(message)
self.model = model
self.llm_provider = llm_provider
self.litellm_debug_info = litellm_debug_info
response = response or httpx.Response(
status_code=self.status_code,
status_code=status_code,
request=httpx.Request(
method="GET", url="https://litellm.ai"
), # mock request object
)
self.max_retries = max_retries
self.num_retries = num_retries
super().__init__(
message=self.message,
model=self.model, # type: ignore
llm_provider=self.llm_provider, # type: ignore
response=response,
litellm_debug_info=self.litellm_debug_info,
)


LITELLM_EXCEPTION_TYPES = [
Expand Down
11 changes: 4 additions & 7 deletions tests/documentation_tests/test_exception_types.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import os
import sys
import traceback
import re
import litellm

from dotenv import load_dotenv

load_dotenv()
import io
import re

# Backup the original sys.path
original_sys_path = sys.path.copy()

sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
import litellm

public_exceptions = litellm.LITELLM_EXCEPTION_TYPES
# Regular expression to extract the error name
Expand All @@ -33,7 +31,7 @@

# Parse the documentation to extract documented keys
# repo_base = "./"
repo_base = "../../"
repo_base = "../"
print(os.listdir(repo_base))
docs_path = f"{repo_base}/docs/my-website/docs/exception_mapping.md" # Path to the documentation
documented_keys = set()
Expand All @@ -49,8 +47,7 @@
table_content = exceptions_section.group(1)

# Step 3: Create a pattern to capture the Error Types from each row
error_type_pattern = re.compile(r"\|\s*[^|]+\s*\|\s*([^\|]+?)\s*\|")

error_type_pattern = re.compile(r'\|\s*(?:\d+|>=500|N/A)\s*\|\s*([^|]+?)\s*\|')
# Extract the error types
exceptions = error_type_pattern.findall(table_content)
print(f"exceptions: {exceptions}")
Expand Down