# Rerank

Order your documents by a question.

1. [Pick a rerank model](#1-pick-a-rerank-model).
2. [Send the question and the documents](#2-send-the-question-and-the-documents).
3. [Read the order](#3-read-the-order).

## 1. Pick a rerank model

A rerank model reads a question and a list of documents, and scores each document by how well it answers. A search that already found fifty candidates sends them here to put the best on top. Copy its model ID from its page in *Models* and send it in `model` as it stands.

## 2. Send the question and the documents

Send the question in `query` and the documents in `documents` to `/v1/rerank`. Yacine's Souk Bot answers the customers of a clothing shop in Oran. Asked about refunds, it sends the shop's help texts and keeps the two best.

```python
import json
import os
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/rerank"
MODEL = "cohere/rerank-4-pro"

documents = [
    "Deposits are held for the life of the account.",
    "A cancelled order refunds the deposit within 14 days.",
    "Delivery outside Algiers takes three to five days.",
    "Refunds return to the original payment method.",
]

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(
        {
            "model": MODEL,
            "query": "Is the deposit refundable if I cancel?",
            "documents": documents,
            "top_n": 2,
        }
    ).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    answer = json.load(response)

for result in answer["results"]:
    index = result["index"]
    print(index, result["relevance_score"], documents[index])
print(answer["usage"]["cost"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/rerank";
const MODEL = "cohere/rerank-4-pro";

const documents = [
  "Deposits are held for the life of the account.",
  "A cancelled order refunds the deposit within 14 days.",
  "Delivery outside Algiers takes three to five days.",
  "Refunds return to the original payment method.",
];

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    query: "Is the deposit refundable if I cancel?",
    documents,
    top_n: 2,
  }),
});
const answer = await response.json();

for (const result of answer.results) {
  console.log(result.index, result.relevance_score, documents[result.index]);
}
console.log(answer.usage.cost);
```

```go
package main

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

const (
	address = "https://opendunes.com/v1/rerank"
	model   = "cohere/rerank-4-pro"
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	documents := []string{
		"Deposits are held for the life of the account.",
		"A cancelled order refunds the deposit within 14 days.",
		"Delivery outside Algiers takes three to five days.",
		"Refunds return to the original payment method.",
	}

	body, err := json.Marshal(map[string]any{
		"model":     model,
		"query":     "Is the deposit refundable if I cancel?",
		"documents": documents,
		"top_n":     2,
	})
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("POST", address, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var answer struct {
		Results []struct {
			Index          int     `json:"index"`
			RelevanceScore float64 `json:"relevance_score"`
		} `json:"results"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	for _, result := range answer.Results {
		document := documents[result.Index]
		fmt.Println(result.Index, result.RelevanceScore, document)
	}
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/rerank"
MODEL="cohere/rerank-4-pro"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "query": "Is the deposit refundable if I cancel?",
    "documents": [
      "Deposits are held for the life of the account.",
      "A cancelled order refunds the deposit within 14 days.",
      "Delivery outside Algiers takes three to five days.",
      "Refunds return to the original payment method."
    ],
    "top_n": 2
  }'
```

| You send | Holds |
|---|---|
| `model` | a rerank model's ID |
| `query` | the question the documents are matched against |
| `documents` | the documents to score: strings, or objects |
| `top_n` | how many results come back, best first |

Every field: [Ranking](/docs/reference/rerank).

<div class="watch-out">
<p><code>top_n</code> trims what comes back, never what is scored. Every document you send is scored and charged.</p>
</div>

<div class="buttons">
<a href="/models?modality=rerank" class="button primary">Browse rerank models</a>
</div>

## 3. Read the order

`200`, with the documents in order, best first.

| Field | Holds |
|---|---|
| `results` | `top_n` entries, best first |
| `index` | in each entry: the document's place in what you sent, from 0 |
| `relevance_score` | in each entry: how well the document answers the question |
| `document` | in each entry: the document you sent, echoed back as its `text`, or its `image` |
| `usage` | `search_units`: the searches counted. `total_tokens`: the tokens read. `cost`: the charge, in DA |

Two headers come back.

| Header | Holds |
|---|---|
| `X-Generation-Id` | the request's receipt: [Receipt](/docs/reference/generation) |
| `X-Balance-Available` | your balance after this charge, in µDA |

## What it cost

Charged in DA from your balance the moment the answer ends, and read in `usage.cost`. Only what you send is counted: the ranking that comes back never is. A rerank model sells one of two things, and its page in *Models* says which, at what rate.

| The model sells | Charged on |
|---|---|
| a search | `search_units`: the searches the answer reports |
| tokens | `total_tokens`: the length of the question and the documents |

Both counts ride every answer; the model's own meter decides which one is charged.

On a model that sells a search, one request can count more than one search: the count in `search_units` is the one charged.

An error before the model answers charges nothing. An answer with no result still charges: the documents were scored.

## Errors

The body says why.

| Status | When |
|---|---|
| 400 | `model`, `query` or `documents` is missing, or a field has the wrong type |
| 401 | the key is missing, wrong, disabled or expired |
| 402 | your balance is at zero or below, cannot pay the request's hold, or the key's cap is spent; `error.metadata.limit_source` names which, and `deposit_url` or `key_url` says where to lift it. After up to 60 seconds of waiting for money your running requests hold, the 402 carries `Retry-After: 60` |
| 404 | `model` is not a rerank model on sale |
| 429 | the API key's own rate limit is reached (`metadata.limit_source` is `key`), or the provider is limiting its rate; `Retry-After` says how many seconds to wait |
| 502 | the model is down, or answered with nothing usable |

What to do on each: [Errors and retries](/docs/errors-and-retries).
