Skip to main content
Mastra v1 is coming in January 2026. Get ahead by starting new projects with the beta or upgrade your existing project today.

rerank()

The rerank() function provides advanced reranking capabilities for vector search results by combining semantic relevance, vector similarity, and position-based scoring.

function rerank(
results: QueryResult[],
query: string,
modelConfig: ModelConfig,
options?: RerankerFunctionOptions,
): Promise<RerankResult[]>;

Usage ExampleDirect link to Usage Example

import { openai } from "@ai-sdk/openai";
import { rerank } from "@mastra/rag";

const model = openai("gpt-4o-mini");

const rerankedResults = await rerank(
vectorSearchResults,
"How do I deploy to production?",
model,
{
weights: {
semantic: 0.5,
vector: 0.3,
position: 0.2,
},
topK: 3,
},
);

ParametersDirect link to Parameters

results:

QueryResult[]
The vector search results to rerank

query:

string
The search query text used to evaluate relevance

model:

MastraLanguageModel
The language Model to use for reranking

options?:

RerankerFunctionOptions
Options for the reranking model

The rerank function accepts any LanguageModel from the Vercel AI SDK. When using the Cohere model rerank-v3.5, it will automatically use Cohere's reranking capabilities.

Note: For semantic scoring to work properly during re-ranking, each result must include the text content in its metadata.text field.

RerankerFunctionOptionsDirect link to RerankerFunctionOptions

weights?:

WeightConfig
Weights for different scoring components (must add up to 1)
number

semantic?:

number (default: 0.4)
Weight for semantic relevance
number

vector?:

number (default: 0.4)
Weight for vector similarity
number

position?:

number (default: 0.2)
Weight for position-based scoring

queryEmbedding?:

number[]
Embedding of the query

topK?:

number
= 3
Number of top results to return

ReturnsDirect link to Returns

The function returns an array of RerankResult objects:

result:

QueryResult
The original query result

score:

number
Combined reranking score (0-1)

details:

ScoringDetails
Detailed scoring information

ScoringDetailsDirect link to ScoringDetails

semantic:

number
Semantic relevance score (0-1)

vector:

number
Vector similarity score (0-1)

position:

number
Position-based score (0-1)

queryAnalysis?:

object
Query analysis details
number

magnitude:

Magnitude of the query
number[]

dominantFeatures:

Dominant features of the query

On this page