> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenlab.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# معالجة الأخطاء

> التعامل مع أخطاء API بشكل مناسب

## تنسيق استجابة الخطأ

كل الأخطاء تعيد تنسيق JSON ثابت مع [تلميحات Agent-First](/guides/agent-first-api) اختيارية:

```json theme={null}
{
  "error": {
    "message": "Human-readable error description",
    "type": "error_type",
    "code": "error_code",
    "param": "parameter_name",
    "did_you_mean": "suggested_model",
    "suggestions": [{"id": "model-id"}],
    "hint": "Next step guidance",
    "retryable": true,
    "retry_after": 30
  }
}
```

الحقول الأساسية المطلوبة (`message`, `type`) موجودة دائمًا. الحقلان `code` و`param` اختياريان ولا يظهران إلا عند الحاجة. حقول التلميح (`did_you_mean`, `suggestions`, `hint`, `retryable`, `retry_after`, `balance_usd`, `estimated_cost_usd`) هي امتدادات اختيارية لتصحيح ذاتي لوكلاء الذكاء الاصطناعي. راجع [دليل Agent-First API](/guides/agent-first-api) للتفاصيل.

تستخدم نقاط النهاية المتوافقة مع OpenAI أنواع أخطاء بوابة TokenLab المستقرة. تستخدم نقاط النهاية المتوافقة مع Anthropic وGemini عائلات أخطائها وشكل الاستجابات الخاصة بها.

## رموز حالة HTTP

| الكود | الوصف                                               |
| ----- | --------------------------------------------------- |
| 400   | طلب خاطئ - معلمات غير صالحة                         |
| 401   | غير مصرح - مفتاح API مفقود أو غير صالح              |
| 402   | يتطلب دفع - رصيد غير كافٍ                           |
| 403   | ممنوع - الوصول مرفوض أو النموذج غير مسموح به        |
| 404   | غير موجود - النموذج أو المورد غير موجود             |
| 413   | الحِمل أكبر من المسموح - تجاوز حجم الإدخال أو الملف |
| 429   | عدد الطلبات أكبر من المسموح - تجاوز حد المعدل       |
| 500   | خطأ داخلي في الخادم                                 |
| 502   | بوابة خاطئة - خطأ من المزود الأعلى                  |
| 503   | الخدمة غير متاحة - الخدمة غير متاحة مؤقتًا          |
| 504   | نفاذ مهلة البوابة - انقضت مهلة الطلب                |

## أنواع الأخطاء

### أخطاء المصادقة (401)

| النوع             | الرمز             | الوصف                       |
| ----------------- | ----------------- | --------------------------- |
| `invalid_api_key` | `invalid_api_key` | مفتاح API مفقود أو غير صالح |
| `expired_api_key` | `expired_api_key` | تم إبطال مفتاح API          |

```python theme={null}
from openai import OpenAI, AuthenticationError

try:
    response = client.chat.completions.create(...)
except AuthenticationError as e:
    print(f"Authentication failed: {e.message}")
```

### أخطاء الدفع (402)

| النوع                  | الرمز                  | الوصف                              |
| ---------------------- | ---------------------- | ---------------------------------- |
| `insufficient_balance` | `insufficient_balance` | رصيد الحساب منخفض جدًا             |
| `quota_exceeded`       | `quota_exceeded`       | تم الوصول إلى حد استخدام مفتاح API |

```python theme={null}
from openai import OpenAI, APIStatusError

try:
    response = client.chat.completions.create(...)
except APIStatusError as e:
    if e.status_code == 402:
        print("Please top up your account balance")
```

### أخطاء الوصول (403)

| النوع           | الرمز               | الوصف                               |
| --------------- | ------------------- | ----------------------------------- |
| `access_denied` | `access_denied`     | تم رفض الوصول إلى المورد            |
| `access_denied` | `model_not_allowed` | النموذج غير مسموح به لمفتاح API هذا |

```json theme={null}
{
  "error": {
    "message": "You don't have permission to access this model",
    "type": "access_denied",
    "code": "model_not_allowed"
  }
}
```

### أخطاء التحقق (400)

| النوع                     | الوصف                                              |
| ------------------------- | -------------------------------------------------- |
| `invalid_request_error`   | معلمات الطلب غير صالحة                             |
| `context_length_exceeded` | الإدخال طويل جدًا بالنسبة لطول سياق النموذج        |
| `model_not_found`         | النموذج المطلوب غير متوفر في العقدة العامة الحالية |

```json theme={null}
{
  "error": {
    "message": "Model not found: please check the model name",
    "type": "invalid_request_error",
    "param": "model",
    "code": "model_not_found",
    "did_you_mean": "gpt-5.4",
    "suggestions": [{"id": "gpt-5.4"}, {"id": "gpt-5-mini"}],
    "hint": "Did you mean 'gpt-5.4'? Use GET https://api.tokenlab.sh/v1/models to list all available models."
  }
}
```

لا تميز المسارات العامة بين حالات الخطأ الإملائي أو المخفي أو المؤجل أو غير العام في جسم الاستجابة. إذا لم يكن النموذج متوفرًا حاليًا عبر العقدة العامة، تعيد TokenLab `model_not_found`.

### أخطاء حد المعدل (429)

عند تجاوز حدود المعدل:

```json theme={null}
{
  "error": {
    "message": "Rate limit: 1000 rpm exceeded",
    "type": "rate_limit_exceeded",
    "code": "rate_limit_exceeded",
    "retryable": true,
    "retry_after": 8,
    "hint": "Rate limited. Retry after 8s. Current limit: 1000/min for user role."
  }
}
```

**الرؤوس المضمنة:**

```
Retry-After: 8
```

يشير كل من ترويسة `Retry-After` وحقل `retry_after` إلى عدد الثواني الدقيق للانتظار قبل إعادة المحاولة.

### الحِمل أكبر من المسموح (413)

عندما يتجاوز حجم الإدخال أو الملف الحدود:

```json theme={null}
{
  "error": {
    "message": "Input size exceeds maximum allowed",
    "type": "invalid_request_error",
    "code": "payload_too_large"
  }
}
```

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

* ملف صورة كبير جدًا (الحد الأقصى 20MB)
* ملف صوتي كبير جدًا (الحد الأقصى 25MB)
* نص الإدخال يتجاوز طول سياق النموذج

### أخطاء المزود الأعلى (502، 503)

| النوع                 | الوصف                |
| --------------------- | -------------------- |
| `upstream_error`      | أعاد المزود خطأً     |
| `all_channels_failed` | لا توجد مزودات متاحة |
| `timeout_error`       | انتهت مهلة الطلب     |

عندما تفشل كل القنوات، تتضمن الاستجابة نماذج بديلة:

```json theme={null}
{
  "error": {
    "message": "Model claude-opus-4-6 temporarily unavailable",
    "code": "all_channels_failed",
    "retryable": true,
    "retry_after": 30,
    "alternatives": [
      {"id": "claude-sonnet-4-6", "status": "available", "tags": []},
      {"id": "gpt-5-mini", "status": "available", "tags": []}
    ],
    "hint": "Retry in 30s or switch to an available model."
  }
}
```

## معالجة الأخطاء في Python

```python theme={null}
from openai import OpenAI, APIError, RateLimitError, APIConnectionError

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.tokenlab.sh/v1"
)

def chat_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4o",
                messages=messages
            )
        except RateLimitError as e:
            if attempt < max_retries - 1:
                import time
                time.sleep(2 ** attempt)  # Exponential backoff
                continue
            raise
        except APIConnectionError as e:
            print(f"Connection error: {e}")
            raise
        except APIError as e:
            print(f"API error: {e.status_code} - {e.message}")
            raise
```

## معالجة الأخطاء في JavaScript

```javascript theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-your-api-key',
  baseURL: 'https://api.tokenlab.sh/v1'
});

async function chatWithRetry(messages, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await client.chat.completions.create({
        model: 'gpt-4o',
        messages
      });
    } catch (error) {
      if (error instanceof OpenAI.RateLimitError) {
        if (attempt < maxRetries - 1) {
          await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
          continue;
        }
      }
      throw error;
    }
  }
}
```

## أفضل الممارسات

<AccordionGroup>
  <Accordion title="تنفيذ التراجع الأسي">
    عند تقييد المعدل، انتظر فترات أطول تدريجيًا بين محاولات إعادة المحاولة:

    ```python theme={null}
    wait_time = 2 ** attempt  # 1s, 2s, 4s, 8s...
    ```
  </Accordion>

  <Accordion title="تعيين مهلات زمنية">
    دائمًا قم بتعيين مهلات زمنية معقولة لتجنب الطلبات المعلقة:

    ```python theme={null}
    client = OpenAI(timeout=60.0)  # 60 second timeout
    ```
  </Accordion>

  <Accordion title="تسجيل الأخطاء لأغراض التصحيح">
    سجّل استجابة الخطأ الكاملة بما في ذلك معرف الطلب للدعم:

    ```python theme={null}
    except APIError as e:
        logger.error(f"API Error: {e.status_code} - {e.message}")
    ```
  </Accordion>

  <Accordion title="معالجة الأخطاء الخاصة بالنماذج">
    بعض النماذج لها متطلبات محددة (مثل max tokens، تنسيقات الصور).
    تحقق من صحة المدخلات قبل إرسال الطلبات.
  </Accordion>
</AccordionGroup>
