跳至主要內容

例外對應

LiteLLM 會將所有提供者的例外對應至其 OpenAI 對應項目。

所有例外都可以從 litellm 匯入 - 例如 from litellm import BadRequestError

透過 AI 閘道而不是 SDK 呼叫嗎?請參閱 錯誤參考,了解 JSON 錯誤負載、回應標頭,以及如何區分閘道錯誤與提供者錯誤

LiteLLM 例外​

狀態碼錯誤類型繼承自說明
400BadRequestErroropenai.BadRequestError
400UnsupportedParamsErrorlitellm.BadRequestError在傳入不支援的參數時拋出
400ContextWindowExceededErrorlitellm.BadRequestError針對上下文視窗超出錯誤訊息的特殊錯誤類型 - 可啟用上下文視窗備援
400ContentPolicyViolationErrorlitellm.BadRequestError針對內容政策違規錯誤訊息的特殊錯誤類型 - 可啟用內容政策備援
400ImageFetchErrorlitellm.BadRequestError在擷取或處理圖片時發生錯誤時拋出
400InvalidRequestErroropenai.BadRequestError已棄用的錯誤,請改用 BadRequestError
401AuthenticationErroropenai.AuthenticationError
402PaymentRequiredErrorlitellm.BadRequestError當提供者回應 402 時拋出,例如帳戶額度已用盡。當路由器的某個模型群組還有其他部署時,會將該部署降溫
403PermissionDeniedErroropenai.PermissionDeniedError
404NotFoundErroropenai.NotFoundError在傳入無效模型時拋出,例如 gpt-8
408Timeoutopenai.APITimeoutError發生逾時時拋出
422UnprocessableEntityErroropenai.UnprocessableEntityError
429RateLimitErroropenai.RateLimitError
500APIConnectionErroropenai.APIConnectionError如果回傳任何未對應的錯誤,會回傳此錯誤
500APIErroropenai.APIError通用的 500 狀態碼錯誤
503ServiceUnavailableErroropenai.APIStatusError如果提供者回傳 service unavailable 錯誤,會拋出此錯誤
>=500InternalServerErroropenai.InternalServerError如果回傳任何未對應的 500 狀態碼錯誤,會拋出此錯誤
N/AAPIResponseValidationErroropenai.APIResponseValidationError如果使用 Rules,且請求/回應未通過規則,會拋出此錯誤
N/ABudgetExceededErrorException用於 proxy,當超出預算時拋出
N/AJSONSchemaValidationErrorlitellm.APIResponseValidationError當回應不符合預期的 json schema 時拋出 - 若與 enforce_validation=True 一起傳入 response_schema 參數時使用
N/AMockExceptionException內部例外,由 mock_completion 類別拋出。請勿直接使用
N/AOpenAIErroropenai.OpenAIError已棄用的內部例外,繼承自 openai.OpenAIError。

基本情況下我們會回傳 APIConnectionError

我們所有的例外都繼承自 OpenAI 的例外類型,因此您已經為該類型撰寫的任何錯誤處理,都能在 LiteLLM 上直接運作。

在所有情況下,回傳的例外都繼承自原始的 OpenAI Exception,但會額外包含 3 個屬性:

  • status_code - 例外的 http 狀態碼
  • message - 錯誤訊息
  • llm_provider - 引發例外的提供者

使用方式​

import litellm
import openai

try:
response = litellm.completion(
model="gpt-5.6-terra",
messages=[
{
"role": "user",
"content": "hello, write a 20 pageg essay"
}
],
timeout=0.01, # this will raise a timeout exception
)
except openai.APITimeoutError as e:
print("Passed: Raised correct exception. Got openai.APITimeoutError\nGood Job", e)
print(type(e))
pass

使用方式 - 擷取串流例外​

import litellm
try:
response = litellm.completion(
model="gpt-5.6-luna",
messages=[
{
"role": "user",
"content": "hello, write a 20 pg essay"
}
],
timeout=0.0001, # this will raise an exception
stream=True,
)
for chunk in response:
print(chunk)
except openai.APITimeoutError as e:
print("Passed: Raised correct exception. Got openai.APITimeoutError\nGood Job", e)
print(type(e))
pass
except Exception as e:
print(f"Did not raise error `openai.APITimeoutError`. Instead raised error type: {type(e)}, Error: {e}")

使用方式 - 是否應重試例外?​

import litellm
import openai

try:
response = litellm.completion(
model="gpt-5.6-terra",
messages=[
{
"role": "user",
"content": "hello, write a 20 pageg essay"
}
],
timeout=0.01, # this will raise a timeout exception
)
except openai.APITimeoutError as e:
should_retry = litellm._should_retry(e.status_code)
print(f"should_retry: {should_retry}")

進階​

存取提供者專屬錯誤詳細資訊​

LiteLLM 例外包含一個 provider_specific_fields 屬性,其中包含各提供者專屬的額外錯誤資訊。這對 Azure OpenAI 特別有用,因為它會提供詳細的內容篩選資訊。

Azure OpenAI - 內容政策違規內部錯誤存取​

當 Azure OpenAI 傳回內容政策違規時,您可以透過 innererror 欄位存取詳細的內容篩選結果:

import litellm
from litellm.exceptions import ContentPolicyViolationError

try:
response = litellm.completion(
model="azure/gpt-5.6-terra",
messages=[
{
"role": "user",
"content": "Some content that might violate policies"
}
]
)
except ContentPolicyViolationError as e:
# Access Azure-specific error details
if e.provider_specific_fields and "innererror" in e.provider_specific_fields:
innererror = e.provider_specific_fields["innererror"]

# Access content filter results
content_filter_result = innererror.get("content_filter_result", {})

print(f"Content filter code: {innererror.get('code')}")
print(f"Hate filtered: {content_filter_result.get('hate', {}).get('filtered')}")
print(f"Violence severity: {content_filter_result.get('violence', {}).get('severity')}")
print(f"Sexual content filtered: {content_filter_result.get('sexual', {}).get('filtered')}")

範例回應結構:

當呼叫 LiteLLM 代理時,內容政策違規會傳回詳細的篩選資訊:

{
"error": {
"message": "litellm.ContentPolicyViolationError: AzureException - The response was filtered due to the prompt triggering Azure OpenAI's content management policy...",
"type": null,
"param": null,
"code": "400",
"provider_specific_fields": {
"innererror": {
"code": "ResponsibleAIPolicyViolation",
"content_filter_result": {
"hate": {
"filtered": true,
"severity": "high"
},
"jailbreak": {
"filtered": false,
"detected": false
},
"self_harm": {
"filtered": false,
"severity": "safe"
},
"sexual": {
"filtered": false,
"severity": "safe"
},
"violence": {
"filtered": true,
"severity": "medium"
}
}
}
}
}
}

詳細資訊​

若要了解其實作方式 - 請查看程式碼

如果您想改進例外對應,請 建立 issue 或 提出 PR。

注意 對於 OpenAI 和 Azure,我們會回傳原始例外(因為它們屬於 OpenAI Error 類型)。但我們會為它們加上 'llm_provider' 屬性。查看程式碼

自訂對應清單​

基本情況下 - 我們會回傳 litellm.APIConnectionError 例外(繼承自 openai 的 APIConnectionError 例外)。

custom_llm_provider逾時ContextWindowExceededErrorBadRequestErrorNotFoundErrorContentPolicyViolationErrorAuthenticationErrorAPIErrorRateLimitErrorServiceUnavailableErrorPermissionDeniedErrorUnprocessableEntityError
openai✓✓✓✓✓
watsonx✓
text-completion-openai✓✓✓✓✓
custom_openai✓✓✓✓✓
openai_compatible_providers✓✓✓✓✓
anthropic✓✓✓✓✓✓✓
replicate✓✓✓✓✓✓✓
bedrock✓✓✓✓✓✓✓✓
sagemaker✓✓
vertex_ai✓✓✓✓
palm✓✓✓
gemini✓✓✓
cloudflare✓✓
cohere✓✓✓✓
cohere_chat✓✓✓✓
huggingface✓✓✓✓✓✓
ai21✓✓✓✓✓✓
nlp_cloud✓✓✓✓✓✓✓
together_ai✓✓✓✓
aleph_alpha✓✓
ollama✓✓✓
ollama_chat✓✓✓
vllm✓✓
azure✓✓✓✓✓✓✓
  • "✓" 表示指定的 custom_llm_provider 可以引發對應的例外。
  • 空白儲存格表示沒有關聯,或如函式所示,該提供者不會引發該特定例外類型。

若要更深入了解這些例外,您可以查看 此處 的實作以取得更多見解。

ContextWindowExceededError 是 InvalidRequestError 的子類別。引入它是為了讓例外處理情境有更細緻的區分。請參閱 此 issue 以了解更多。

歡迎對改善例外對應提出貢獻 歡迎