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

# إعادة ترتيب المستندات (Rerank Documents)

> إعادة ترتيب المستندات بناءً على مدى صلتها بالاستعلام

إعادة ترتيب المستندات باستخدام نماذج التشابه الدلالي (semantic similarity). مفيد لتحسين نتائج البحث وتطبيقات RAG.

## جسم الطلب

**مهلة الطلبات المتزامنة:** ينتظر هذا الـ endpoint غير الخاص بالمحادثة حتى ينتهي النموذج الذي تم التوجيه إليه. قد تتجاوز المدخلات الكبيرة أو الصوت الطويل أو الدُفعات الكبيرة القيمة الافتراضية الشائعة للعميل وهي 30s، لذا اضبط مهلة عميل HTTP على `120s` على الأقل.

<ParamField body="model" type="string" required>
  معرف نموذج إعادة الترتيب (reranker) المراد استخدامه (على سبيل المثال، `qwen3-vl-rerank`).
</ParamField>

<ParamField body="query" type="string" required>
  الاستعلام الذي سيتم ترتيب المستندات بناءً عليه. الحد الأقصى للطول: `32,000` حرف.
</ParamField>

<ParamField body="documents" type="array" required>
  قائمة المستندات (نصوص) المراد إعادة ترتيبها. الحدود: حتى `1,000` مستند، وكل مستند حتى `100,000` حرف، وبحد أقصى `2,000,000` حرف لجميع المستندات.
</ParamField>

<ParamField body="top_n" type="integer">
  عدد أفضل النتائج التي سيتم إرجاعها. القيمة الافتراضية هي جميع المستندات. يجب أن تكون القيمة `1` على الأقل وألا تتجاوز `documents.length`. لا تملك TokenLab حاليًا حدًا أدنى خاصًا بالمزوّد تتم إدارته؛ إذا نشر مزوّد حدًا لاحقًا، فيجب إضافته أولًا إلى حقيقة شكل طلب rerank قبل توثيقه أو فرضه.
</ParamField>

<ParamField body="return_documents" type="boolean" default="false">
  ما إذا كان سيتم تضمين نص المستند الأصلي في الاستجابة.
</ParamField>

## الاستجابة (Response)

<ResponseField name="results" type="array">
  قائمة مرتبة من المستندات مع الدرجات.

  تحتوي كل نتيجة على:

  * `index` (integer): فهرس المستند الأصلي
  * `relevance_score` (number): درجة الصلة (0-1)
  * `document` (string): النص الأصلي (إذا كان `return_documents=true`)
</ResponseField>

<ResponseField name="model" type="string">
  النموذج المستخدم لإعادة الترتيب.
</ResponseField>

<ResponseField name="usage" type="object">
  إحصائيات استخدام الـ token.
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.tokenlab.sh/v1/rerank" \
    -H "Authorization: Bearer sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "qwen3-vl-rerank",
      "query": "What is machine learning?",
      "documents": [
        "Machine learning is a subset of AI",
        "The weather is nice today",
        "Deep learning uses neural networks"
      ],
      "top_n": 2,
      "return_documents": true
    }'
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api.tokenlab.sh/v1/rerank",
      headers={"Authorization": "Bearer sk-your-api-key"},
      json={
          "model": "qwen3-vl-rerank",
          "query": "What is machine learning?",
          "documents": [
              "Machine learning is a subset of AI",
              "The weather is nice today",
              "Deep learning uses neural networks"
          ],
          "top_n": 2
      }
  )

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.tokenlab.sh/v1/rerank', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'qwen3-vl-rerank',
      query: 'What is machine learning?',
      documents: [
        'Machine learning is a subset of AI',
        'The weather is nice today',
        'Deep learning uses neural networks'
      ],
      top_n: 2
    })
  });

  const data = await response.json();
  console.log(data.results);
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "net/http"
  )

  func main() {
      payload := map[string]interface{}{
          "model": "qwen3-vl-rerank",
          "query": "What is machine learning?",
          "documents": []string{
              "Machine learning is a subset of AI",
              "The weather is nice today",
              "Deep learning uses neural networks",
          },
          "top_n": 2,
      }
      body, _ := json.Marshal(payload)

      req, _ := http.NewRequest("POST", "https://api.tokenlab.sh/v1/rerank", bytes.NewBuffer(body))
      req.Header.Set("Authorization", "Bearer sk-your-api-key")
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      var result map[string]interface{}
      json.NewDecoder(resp.Body).Decode(&result)
      fmt.Println(result["results"])
  }
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init('https://api.tokenlab.sh/v1/rerank');

  curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => [
          'Content-Type: application/json',
          'Authorization: Bearer sk-your-api-key'
      ],
      CURLOPT_POSTFIELDS => json_encode([
          'model' => 'qwen3-vl-rerank',
          'query' => 'What is machine learning?',
          'documents' => [
              'Machine learning is a subset of AI',
              'The weather is nice today',
              'Deep learning uses neural networks'
          ],
          'top_n' => 2
      ])
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($response, true);
  print_r($data['results']);
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "results": [
      {
        "index": 0,
        "relevance_score": 0.95,
        "document": "Machine learning is a subset of AI"
      },
      {
        "index": 2,
        "relevance_score": 0.82,
        "document": "Deep learning uses neural networks"
      }
    ],
    "model": "qwen3-vl-rerank",
    "usage": {
      "prompt_tokens": 45,
      "total_tokens": 45
    }
  }
  ```
</ResponseExample>
