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

# Rerank documents

POST https://api.tramlabs.io/v1/rerank
Content-Type: application/json

Rerank documents theo query. Tương thích với Cohere Rerank API.


Reference: https://docs.tramlabs.io/api/endpoints/images/rerank/create-rerank

## Authentication

- `Authorization` header (bearer token, required) — API key làm bearer token. Tạo API key tại [Console](https://console.tramlabs.io/keys).

## Request

### Body (application/json)

This endpoint expects a RerankRequest.

- `model` (string, required) — Model ID (ví dụ: `cohere-rerank-v3.5`)
- `query` (string, required) — Query dùng để rerank documents
- `documents` (list of RerankRequestDocumentsItems, required) — Danh sách documents cần rerank (string hoặc object)
- `top_n` (integer, optional) — Số documents trả về (mặc định trả tất cả)
- `rank_fields` (list of string, optional) — Các trường dùng để ranking (khi documents là object)
- `return_documents` (boolean, optional) — Trả lại nội dung document trong response
- `max_chunks_per_doc` (integer, optional) — Số chunks tối đa mỗi document
- `max_tokens_per_doc` (integer, optional) — Số tokens tối đa mỗi document

## Response

### 200

Thành công

- `id` (string, optional)
- `results` (list of RerankResponseResultsItems, optional)
- `meta` (RerankResponseMeta, optional)

## Errors

### 400 Bad Request Error

Request không hợp lệ

- `error` (ErrorResponseError, optional)

### 401 Unauthorized Error

API key không hợp lệ hoặc thiếu

- `error` (ErrorResponseError, optional)

### 403 Forbidden Error

Vượt budget hoặc model không được phép

- `error` (ErrorResponseError, optional)

### 429 Too Many Requests Error

Rate limit exceeded

- `error` (ErrorResponseError, optional)

## Types

### RerankRequestDocumentsItems

- string
- map from string to any

### RerankResponseResultsItems

- `index` (integer, optional) — Vị trí document trong danh sách gốc
- `relevance_score` (double, optional) — Điểm relevance (0–1)
- `document` (RerankResponseResultsItemsDocument, optional)

### RerankResponseMeta

- `api_version` (RerankResponseMetaApiVersion, optional)
- `billed_units` (RerankResponseMetaBilledUnits, optional)
- `tokens` (RerankResponseMetaTokens, optional)

### ErrorResponseError

- `message` (string, optional)
- `type` (string, optional)
- `code` (string, optional)

### RerankResponseResultsItemsDocument

- `text` (string, optional)

### RerankResponseMetaApiVersion

### RerankResponseMetaBilledUnits

- `search_units` (integer, optional)
- `total_tokens` (integer, optional)

### RerankResponseMetaTokens

- `input_tokens` (integer, optional)
- `output_tokens` (integer, optional)

## Examples

**Request**

```json
{
  "model": "cohere-rerank-v3.5",
  "query": "What is the capital of France?",
  "documents": [
    "Paris is the capital of France.",
    "Berlin is the capital of Germany."
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.tramlabs.io/v1/rerank"

payload = {
    "model": "cohere-rerank-v3.5",
    "query": "What is the capital of France?",
    "documents": ["Paris is the capital of France.", "Berlin is the capital of Germany."]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://api.tramlabs.io/v1/rerank';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"cohere-rerank-v3.5","query":"What is the capital of France?","documents":["Paris is the capital of France.","Berlin is the capital of Germany."]}'
};

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

```go
package main

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

func main() {

	url := "https://api.tramlabs.io/v1/rerank"

	payload := strings.NewReader("{\n  \"model\": \"cohere-rerank-v3.5\",\n  \"query\": \"What is the capital of France?\",\n  \"documents\": [\n    \"Paris is the capital of France.\",\n    \"Berlin is the capital of Germany.\"\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
require 'uri'
require 'net/http'

url = URI("https://api.tramlabs.io/v1/rerank")

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\": \"cohere-rerank-v3.5\",\n  \"query\": \"What is the capital of France?\",\n  \"documents\": [\n    \"Paris is the capital of France.\",\n    \"Berlin is the capital of Germany.\"\n  ]\n}"

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

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

HttpResponse<String> response = Unirest.post("https://api.tramlabs.io/v1/rerank")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"cohere-rerank-v3.5\",\n  \"query\": \"What is the capital of France?\",\n  \"documents\": [\n    \"Paris is the capital of France.\",\n    \"Berlin is the capital of Germany.\"\n  ]\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.tramlabs.io/v1/rerank', [
  'body' => '{
  "model": "cohere-rerank-v3.5",
  "query": "What is the capital of France?",
  "documents": [
    "Paris is the capital of France.",
    "Berlin is the capital of Germany."
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.tramlabs.io/v1/rerank");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"cohere-rerank-v3.5\",\n  \"query\": \"What is the capital of France?\",\n  \"documents\": [\n    \"Paris is the capital of France.\",\n    \"Berlin is the capital of Germany.\"\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "cohere-rerank-v3.5",
  "query": "What is the capital of France?",
  "documents": ["Paris is the capital of France.", "Berlin is the capital of Germany."]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.tramlabs.io/v1/rerank")! 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()
```