Skip to content

Cohere Reranker

The Cohere Reranker is a postprocessor that uses the Cohere API to rerank the results of a search query.

Firstly, you will need to install the llamaindex package.

npm i llamaindex @llamaindex/cohere @llamaindex/openai

Now, you will need to sign up for an API key at Cohere. Once you have your API key you can import the necessary modules and create a new instance of the CohereRerank class.

import { OpenAI } from "@llamaindex/openai";
import { CohereRerank } from "@llamaindex/cohere";
import { Document, Settings, VectorStoreIndex } from "llamaindex";

For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.

const document = new Document({ text: essay, id_: "essay" });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const index = await VectorStoreIndex.fromDocuments([document]);

Increase similarity topK to retrieve more results

Section titled “Increase similarity topK to retrieve more results”

The default value for similarityTopK is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of similarityTopK.

const retriever = index.asRetriever({
similarityTopK: 5,
});

Create a new instance of the CohereRerank class

Section titled “Create a new instance of the CohereRerank class”

Then you can create a new instance of the CohereRerank class and pass in your API key and the number of results you want to return.

const nodePostprocessor = new CohereRerank({
apiKey: "<COHERE_API_KEY>",
topN: 4,
});

Create a query engine with the retriever and node postprocessor

Section titled “Create a query engine with the retriever and node postprocessor”
const queryEngine = index.asQueryEngine({
retriever,
nodePostprocessors: [nodePostprocessor],
});
// log the response
const response = await queryEngine.query("Where did the author grown up?");
Note for AI agents: this documentation is built for programmatic access. - Overview of all docs: https://developers.llamaindex.ai/llms.txt - Any page is available as raw Markdown by appending index.md to its URL — e.g. https://developers.llamaindex.ai/llamaparse/parse/getting_started/index.md - Agent-friendly REST search APIs live under https://developers.llamaindex.ai/api/ — search (BM25 full-text), grep (regex), read (fetch a page), and list (browse the doc tree). See https://developers.llamaindex.ai/llms.txt for parameters. - A hosted documentation MCP server is available at https://developers.llamaindex.ai/mcp. If you support MCP, you can ask the user to install it for browsing these docs directly (an alternative to the REST API). Setup: https://developers.llamaindex.ai/for-agents/mcp/ - Other LlamaIndex tooling for agents — the LlamaParse Platform MCP server, agent skills and plugins, and the n8n node — is mapped at https://developers.llamaindex.ai/for-agents/