Error Handling and Rate Limits
Handle common API errors including rate limit exceptions, authentication errors, and timeouts with retry logic and exponential backoff patterns.
Error Handling and Rate Limits is a free AI Engineering Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Engineering Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why API Errors Happen
Lots can go wrong on an API call: overload, low quota, dropped network, a bad request. Treating calls as infallible guarantees fragile code — know the error types first.
OpenAI Error Types Overview
The SDK raises specific exceptions like RateLimitError and AuthenticationError. Only transient ones, such as rate limits and network drops, are worth retrying — the rest won't fix themselves.
Catching Errors with Try-Except
Wrap each call in try-except and catch specific exceptions, not a bare except. That way you respond smartly to each failure instead of hiding bugs. The code shows how.
import openai
client = openai.OpenAI()
try:
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Hello!'}]
)
print(response.choices[0].message.content)
except openai.AuthenticationError as e:
print('Bad API key. Check OPENAI_API_KEY environment variable.')
raise # do not retry
except openai.RateLimitError as e:
print('Rate limited. Back off and retry.')
except openai.APIConnectionError as e:
print('Network error:', e)
except openai.APIStatusError as e:
print('Server error', e.status_code, e.message)Understanding Rate Limits
OpenAI enforces two rate limits at once: requests per minute (RPM) and tokens per minute (TPM). One huge prompt can blow your TPM in a single request. Both return a 429.
Exponential Backoff: The Right Retry Strategy
Hit a rate limit? Wait, then retry with exponential backoff: 1s, 2s, 4s, doubling each time. Add a little jitter and a max retry count so you never loop forever. See the code.
import time
import random
import openai
client = openai.OpenAI()
def call_with_backoff(messages, max_retries=5):
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model='gpt-4o-mini',
messages=messages
)
except openai.RateLimitError:
if attempt == max_retries - 1:
raise
wait = (2 ** attempt) + random.uniform(0, 1)
print(f'Rate limited. Waiting {wait:.1f}s (attempt {attempt+1})')
time.sleep(wait)
except (openai.APIConnectionError, openai.APIStatusError):
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt)Using the tenacity Library
Don't hand-roll retries — the tenacity library does it cleanly. Decorate your function with @retry and it handles backoff, jitter, and retry conditions for you.
from tenacity import retry, wait_random_exponential, stop_after_attempt
import openai
client = openai.OpenAI()
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6)
)
def completion_with_backoff(**kwargs):
return client.chat.completions.create(**kwargs)
response = completion_with_backoff(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Tell me a joke.'}]
)
print(response.choices[0].message.content)Timeout Configuration
A hung request can freeze your app forever, so always set a timeout. The SDK takes a timeout in seconds, on the client or per call. Pick it to fit your expected response length.
import openai
# Set a default timeout for all requests from this client
client = openai.OpenAI(timeout=30.0)
# Or override per request
try:
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Summarize the French Revolution.'}],
timeout=60.0
)
except openai.APITimeoutError:
print('Request timed out. Try a shorter prompt or increase timeout.')Handling Authentication Errors
An AuthenticationError (401) means your key is wrong, expired, or revoked — retrying never helps. Log it, alert, and fail fast instead of burning your retry budget.
import os
import openai
api_key = os.environ.get('OPENAI_API_KEY')
if not api_key:
raise EnvironmentError(
'OPENAI_API_KEY not set. Export it before running.'
)
client = openai.OpenAI(api_key=api_key)
try:
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Hello'}]
)
except openai.AuthenticationError:
# Do NOT retry - the key itself is invalid
raise RuntimeError('Invalid API key. Check OPENAI_API_KEY.')Quota vs Rate Limits
Both look like RateLimitError, but they differ: rate limits are per-minute throttles that reset on their own, while quota limits are spending caps that need more credits.
Logging Errors for Debugging
In production, log every error with context: the type, model, parameters, token count, time, and the request ID. That request ID is exactly what OpenAI support needs. See the code.
import logging
import openai
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
client = openai.OpenAI()
def safe_completion(model, messages):
try:
response = client.chat.completions.create(
model=model, messages=messages
)
return response
except openai.RateLimitError as e:
logger.warning(
'Rate limit hit',
extra={'model': model, 'error': str(e)}
)
raise
except openai.APIStatusError as e:
logger.error(
'API server error',
extra={
'status_code': e.status_code,
'request_id': e.request_id,
'model': model
}
)
raiseError Handling in Production Apps
A solid production strategy: fail fast on unrecoverable errors, retry transient ones with backoff, and give graceful fallbacks. Never let one API error crash your whole server.
Quick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
You learned to handle failure: OpenAI raises specific exceptions, rate limits need backoff with jitter, and auth errors should fail fast. Next: writing powerful prompts.
Frequently asked questions
Is the “Error Handling and Rate Limits” lesson free?
Yes — the full text of “Error Handling and Rate Limits” is free to read here on the web, and the AI Engineering Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Engineering Academy course, upgrade to CoddyKit PRO.
What will I learn in “Error Handling and Rate Limits”?
Handle common API errors including rate limit exceptions, authentication errors, and timeouts with retry logic and exponential backoff patterns. You practise AI Engineering Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Engineering Academy?
No prior experience is required. AI Engineering Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Error Handling and Rate Limits” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Engineering Academy lesson?
Yes. Every AI Engineering Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Setting Up Your Python Environment
- The Chat Completions Endpoint
- Controlling Model Behavior with Parameters
- Error Handling and Rate Limits