Overview
The OpenAI Python SDK provides a hierarchy of exception classes to help you handle different error scenarios. All exceptions inherit fromopenai.APIError.
Exception Hierarchy
Basic Error Handling
Exception Classes
APIConnectionError
Raised when the SDK cannot connect to the API. Attributes:message(str) - Error descriptionrequest(httpx.Request) - The request that failed
APITimeoutError
Raised when a request times out. Inherits fromAPIConnectionError.
Timeout errors are automatically retried by default. See Retries for configuration.
APIStatusError
Base class for all HTTP status code errors (4xx and 5xx responses). Attributes:message(str) - Error descriptionrequest(httpx.Request) - The request that failedresponse(httpx.Response) - The error responsestatus_code(int) - HTTP status coderequest_id(str | None) - Request ID fromx-request-idheaderbody(object | None) - Response body (parsed JSON or raw string)code(str | None) - Error code from responseparam(str | None) - Parameter that caused the errortype(str | None) - Error type from response
BadRequestError (400)
The request was invalid or malformed.AuthenticationError (401)
Authentication failed (invalid API key).PermissionDeniedError (403)
The API key doesn’t have permission to access the resource.NotFoundError (404)
The requested resource doesn’t exist.ConflictError (409)
The request conflicts with the current state of the resource.Conflict errors (409) are automatically retried by default.
UnprocessableEntityError (422)
The request was well-formed but contains semantic errors.RateLimitError (429)
Rate limit exceeded. You’re sending requests too quickly.InternalServerError (500+)
The API encountered an internal error.Server errors (5xx) are automatically retried by default.
APIResponseValidationError
Raised when the API response doesn’t match the expected schema. Attributes:message(str) - Error descriptionrequest(httpx.Request) - The requestresponse(httpx.Response) - The responsestatus_code(int) - HTTP status codebody(object | None) - Response body
LengthFinishReasonError
Raised when a completion is truncated due to length limits. Attributes:completion(ChatCompletion) - The truncated completion
ContentFilterFinishReasonError
Raised when content is filtered due to content policy violations.InvalidWebhookSignatureError
Raised when webhook signature verification fails.Async Error Handling
Error handling works identically withAsyncOpenAI:
Request IDs
AllAPIStatusError exceptions include a request_id for debugging:
Retry Strategy
Some errors are automatically retried:- Connection errors - Network failures
- Timeout errors (408) - Request timeouts
- Conflict errors (409) - Resource conflicts
- Rate limit errors (429) - Too many requests
- Server errors (5xx) - Internal server errors
Best Practices
Related
- Retries - Automatic retry configuration
- Timeouts - Request timeout handling
- Client Initialization - Client configuration