0Pricing
AI Engineering Academy · درس

معالجة الأخطاء وحدود معدل الطلبات

عالجوا أخطاء API الشائعة، بما فيها استثناءات تجاوز حد المعدل، وأخطاء المصادقة، وانتهاء المهلة، باستخدام منطق إعادة المحاولة وأنماط التراجع الأُسّي.

معالجة الأخطاء وحدود معدل الطلبات درس مجاني في AI Engineering Academy على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في AI Engineering Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

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.

الأسئلة الشائعة

هل درس «معالجة الأخطاء وحدود معدل الطلبات» مجاني؟

نعم — نص درس «معالجة الأخطاء وحدود معدل الطلبات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Engineering Academy، انتقل إلى CoddyKit PRO. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.

ماذا ستتعلم في «معالجة الأخطاء وحدود معدل الطلبات»؟

عالجوا أخطاء API الشائعة، بما فيها استثناءات تجاوز حد المعدل، وأخطاء المصادقة، وانتهاء المهلة، باستخدام منطق إعادة المحاولة وأنماط التراجع الأُسّي. تتمرن على AI Engineering Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ AI Engineering Academy؟

لا تُشترط خبرة سابقة. AI Engineering Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «معالجة الأخطاء وحدود معدل الطلبات»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس AI Engineering Academy هذا؟

نعم. كل درس في AI Engineering Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. إعداد بيئة Python الخاصة بكم
  2. نقطة نهاية إكمالات المحادثة
  3. التحكم في سلوك النموذج باستخدام المعلمات
  4. معالجة الأخطاء وحدود معدل الطلبات
← العودة إلى AI Engineering Academy