---
title: "Reranking"
description: "Order documents by how well they answer a query, with Laravel AI's Reranking API and a Workers AI model."
---

> Documentation Index
> Fetch the complete documentation index at: https://laravel-cf-workersai.meirdick.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Reranking

Reranking sorts a list of texts by how well each one answers a query. It is most useful after a vector search: fetch more results than you need with [embeddings](/docs/guides/embeddings/), then rerank them and keep the best. It needs no extra config, and your `workers-ai` provider entry works on both the [direct route and the gateway route](/docs/concepts/routes/).

## Rerank documents

```php
use Laravel\Ai\Reranking;

$response = Reranking::of([
    'A hammer is a tool.',
    'An apple is a fruit.',
    'A car has wheels.',
])->limit(2)->rerank('Which one is food?', provider: 'workers-ai');

$response->first()->document; // 'An apple is a fruit.'
$response->first()->score;    // the relevance score
$response->first()->index;    // 1, its position in your list
$response->documents();       // the texts, best first
```

Without `limit()`, you get every document back, best first.

## Rerank a collection

Laravel AI's `rerank()` collection method works too. The first argument is the field to compare, a list of fields, or a closure that returns the text. You get your original items back, best first.

```php
$posts = Post::all()->rerank('body', 'How do I reset my password?', provider: 'workers-ai');

$posts = Post::all()->rerank(['title', 'body'], 'How do I reset my password?', limit: 5, provider: 'workers-ai');
```

## Omit the provider name

Laravel AI's `default_for_reranking` is `cohere` until you change it. Set it in `config/ai.php` to leave out `provider:`:

```php
'default_for_reranking' => 'workers-ai',
```

## Choose a model

The default is `@cf/baai/bge-reranker-base`. To change it, set `models.reranking.default` on the provider entry in `config/ai.php`, or pass `model:` to `rerank()`.

## Test your code

```php
use Laravel\Ai\Reranking;

Reranking::fake();

// run your code, then:
Reranking::assertReranked(fn ($prompt) => $prompt->query === 'Which one is food?');
```

## Cost

Cloudflare bills reranking in neurons, and the package reports them with the `WorkersAiUsageReported` event. See [Cost tracking](/docs/guides/cost-tracking/). On `laravel/ai` 1.x, `$response->usage->inputTokens` holds the token count.

Source: https://laravel-cf-workersai.meirdick.com/docs/guides/reranking/index.mdx
