0Pricing
AI Engineering Academy · Leçon

Gestion des erreurs et limites de débit

Gérez les erreurs courantes de l’API, notamment les exceptions dues aux limites de débit, les erreurs d’authentification et les délais d’attente, grâce à une logique de nouvelle tentative et à des mécanismes de temporisation exponentielle.

Gestion des erreurs et limites de débit est une leçon AI Engineering Academy gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage AI Engineering Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours AI Engineering Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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
            }
        )
        raise

Error 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.

Questions Fréquemment Posées

La leçon « Gestion des erreurs et limites de débit » est-elle gratuite ?

Oui — le texte complet de « Gestion des erreurs et limites de débit » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours AI Engineering Academy, passe à CoddyKit PRO. Le cours AI Engineering Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Gestion des erreurs et limites de débit » ?

Gérez les erreurs courantes de l’API, notamment les exceptions dues aux limites de débit, les erreurs d’authentification et les délais d’attente, grâce à une logique de nouvelle tentative et à des mé… Tu pratiques AI Engineering Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer AI Engineering Academy ?

Aucune expérience préalable n'est requise. AI Engineering Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.

Combien de temps prend la leçon « Gestion des erreurs et limites de débit » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon AI Engineering Academy ?

Oui. Chaque leçon AI Engineering Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Configurer votre environnement Python
  2. Le point d’accès Chat Completions
  3. Contrôler le comportement du modèle avec des paramètres
  4. Gestion des erreurs et limites de débit
← Retour à AI Engineering Academy