> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.empiriolabs.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.empiriolabs.ai/_mcp/server.

# Rerank documents

POST https://api.empiriolabs.ai/v1/reranks
Content-Type: application/json

Sort candidate `documents` by semantic relevance to a `query`. Returns each
document's original index plus a 0-1 relevance score (higher = more
relevant). Score is relative to the request and not comparable across
requests.

Built for RAG and search refinement: feed in the top-N hits from your
vector store / BM25 / hybrid retriever, and the model returns a tighter,
better-ordered shortlist.


Reference: https://docs.empiriolabs.ai/api-reference/api-reference/reranks/create-reranks

## Authentication

- `Authorization` header (bearer token, required) — Pass your EmpirioLabs API key as a bearer token. The Anthropic-style `x-api-key` header is also accepted on every endpoint.

## Request

### Body (application/json)

This endpoint expects an object.

- `model` (string, required) — Reranking model id, for example `qwen3-rerank`.
- `query` (string, required) — Query text. Max 4,000 tokens.
- `documents` (list of string, required) — Candidate documents to sort. Max 500 items, each up to 4,000 tokens.
- `top_n` (integer, optional) — Number of top-ranked documents to return. Defaults to all.
- `instruct` (string, optional) — Custom English instruction guiding the sort. Defaults to a Q&A retrieval policy. Pass `"Retrieve semantically similar text."` for similarity sorting.
- `return_documents` (boolean, optional, default: false) — When true, return the original document text alongside each result.

## Response

### 200

Sorted relevance scores, most relevant first.

- `object` (string, optional)
- `model` (string, optional)
- `results` (list of V1ReranksPostResponsesContentApplicationJsonSchemaResultsItems, optional)
- `usage` (Usage, optional)

## Errors

### 400 Bad Request Error

The request is invalid and nothing is billed. `error.param` names the field to fix. A missing or blank `model` returns `missing_required_parameter`; a body that is not a JSON object returns `invalid_request`; and a body that is not valid JSON, including one with `NaN` or `Infinity`, returns `invalid_json`.

- `error` (ErrorError, required)

### 401 Unauthorized Error

The API key is missing, invalid, inactive, or expired.

- `error` (ErrorError, required)

### 402 Payment Required Error

The account cannot cover the pay-as-you-go amount required by the request (`insufficient_credits`), or the account's spending limit is reached (`spending_limit_reached`). An active plan can run a request at zero balance only when the entire request is covered by remaining allowance. Partly covered requests require enough balance for the full remainder before work starts.

- `error` (ErrorError, required)

### 403 Forbidden Error

The account or API key cannot make this request, for example a restricted account or a model that is not available on the account.

- `error` (ErrorError, required)

### 404 Not Found Error

The resource was not found, for example an unknown model ID or job ID.

- `error` (ErrorError, required)

### 429 Too Many Requests Error

An account rate limit was reached: requests per minute (type `requests`, code `rate_limit_exceeded`) or tokens per minute (type `tokens`, code `token_rate_limit_exceeded`). Retry with backoff.

- `error` (ErrorError, required)

### 500 Internal Server Error

The request could not be completed this time. Retry it with backoff.

- `error` (ErrorError, required)

## Types

### V1ReranksPostResponsesContentApplicationJsonSchemaResultsItems

- `index` (integer, optional) — Original index of the document in the input array.
- `relevance_score` (double, optional) — 0-1 score; higher = more relevant. Not comparable across requests.
- `document` (V1ReranksPostResponsesContentApplicationJsonSchemaResultsItemsDocument, optional) — Returned only when `return_documents` is true.

### Usage

- `prompt_tokens` (integer, optional)
- `completion_tokens` (integer, optional)
- `total_tokens` (integer, optional)

### ErrorError

- `message` (string, required) — What went wrong. For a request error it names the field to fix.
- `type` (string, required) — Error category, which follows the HTTP status: `insufficient_quota` for `402`, `requests` or `tokens` for a `429` (the limit that was reached), and `server_error` for a `5xx`. Other errors are `invalid_request_error`, or a more specific category such as `authentication_error`, `permission_error`, or `not_found_error`.
- `param` (string, required, nullable) — The request field the error is about, or null.
- `code` (string, required, nullable) — Machine-readable error code, for example `invalid_value`, `missing_required_parameter`, `invalid_api_key`, `insufficient_credits`, `model_not_found`, or `rate_limit_exceeded`. Null when the error has no code.
- `request_id` (string, required) — Request identifier. Include it when you contact support.

### V1ReranksPostResponsesContentApplicationJsonSchemaResultsItemsDocument

Returned only when `return_documents` is true.

- `text` (string, optional)

## Examples

**Request**

```json
{
  "model": "qwen3-rerank",
  "query": "What is a rerank model?",
  "documents": [
    "Rerank models sort candidate documents by relevance.",
    "Quantum computing is a cutting-edge field of computer science.",
    "Pre-trained language models advanced rerank models."
  ]
}
```

**Response**

```json
{
  "object": "list",
  "model": "qwen3-rerank",
  "results": [
    {
      "index": 0,
      "relevance_score": 0.93,
      "document": {
        "text": "Rerank models sort candidate documents by relevance."
      }
    },
    {
      "index": 2,
      "relevance_score": 0.34,
      "document": {
        "text": "Pre-trained language models advanced rerank models."
      }
    }
  ],
  "usage": {
    "prompt_tokens": 0,
    "completion_tokens": 0,
    "total_tokens": 79
  }
}
```

**SDK Code**

```python default
import requests

url = "https://api.empiriolabs.ai/v1/reranks"

payload = {
    "model": "qwen3-rerank",
    "query": "What is a rerank model?",
    "documents": ["Rerank models sort candidate documents by relevance.", "Quantum computing is a cutting-edge field of computer science.", "Pre-trained language models advanced rerank models."]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript default
const url = 'https://api.empiriolabs.ai/v1/reranks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"qwen3-rerank","query":"What is a rerank model?","documents":["Rerank models sort candidate documents by relevance.","Quantum computing is a cutting-edge field of computer science.","Pre-trained language models advanced rerank models."]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go default
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.empiriolabs.ai/v1/reranks"

	payload := strings.NewReader("{\n  \"model\": \"qwen3-rerank\",\n  \"query\": \"What is a rerank model?\",\n  \"documents\": [\n    \"Rerank models sort candidate documents by relevance.\",\n    \"Quantum computing is a cutting-edge field of computer science.\",\n    \"Pre-trained language models advanced rerank models.\"\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby default
require 'uri'
require 'net/http'

url = URI("https://api.empiriolabs.ai/v1/reranks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"qwen3-rerank\",\n  \"query\": \"What is a rerank model?\",\n  \"documents\": [\n    \"Rerank models sort candidate documents by relevance.\",\n    \"Quantum computing is a cutting-edge field of computer science.\",\n    \"Pre-trained language models advanced rerank models.\"\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java default
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.empiriolabs.ai/v1/reranks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"qwen3-rerank\",\n  \"query\": \"What is a rerank model?\",\n  \"documents\": [\n    \"Rerank models sort candidate documents by relevance.\",\n    \"Quantum computing is a cutting-edge field of computer science.\",\n    \"Pre-trained language models advanced rerank models.\"\n  ]\n}")
  .asString();
```

```php default
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.empiriolabs.ai/v1/reranks', [
  'body' => '{
  "model": "qwen3-rerank",
  "query": "What is a rerank model?",
  "documents": [
    "Rerank models sort candidate documents by relevance.",
    "Quantum computing is a cutting-edge field of computer science.",
    "Pre-trained language models advanced rerank models."
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp default
using RestSharp;

var client = new RestClient("https://api.empiriolabs.ai/v1/reranks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"qwen3-rerank\",\n  \"query\": \"What is a rerank model?\",\n  \"documents\": [\n    \"Rerank models sort candidate documents by relevance.\",\n    \"Quantum computing is a cutting-edge field of computer science.\",\n    \"Pre-trained language models advanced rerank models.\"\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift default
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "qwen3-rerank",
  "query": "What is a rerank model?",
  "documents": ["Rerank models sort candidate documents by relevance.", "Quantum computing is a cutting-edge field of computer science.", "Pre-trained language models advanced rerank models."]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.empiriolabs.ai/v1/reranks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```