!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Providers](/v0.1/docs/integrations/platforms/)
    
    *   [Providers](/v0.1/docs/integrations/platforms/)
    *   [Anthropic](/v0.1/docs/integrations/platforms/anthropic/)
    *   [AWS](/v0.1/docs/integrations/platforms/aws/)
    *   [Google](/v0.1/docs/integrations/platforms/google/)
    *   [Microsoft](/v0.1/docs/integrations/platforms/microsoft/)
    *   [OpenAI](/v0.1/docs/integrations/platforms/openai/)
*   [Components](/v0.1/docs/integrations/components/)
    
    *   [LLMs](/v0.1/docs/integrations/llms/)
        
    *   [Chat models](/v0.1/docs/integrations/chat/)
        
    *   [Document loaders](/v0.1/docs/integrations/document_loaders/)
        
    *   [Document transformers](/v0.1/docs/integrations/document_transformers/)
        
    *   [Document compressors](/v0.1/docs/integrations/document_compressors/)
        
        *   [Cohere Rerank](/v0.1/docs/integrations/document_compressors/cohere_rerank/)
    *   [Text embedding models](/v0.1/docs/integrations/text_embedding/)
        
    *   [Vector stores](/v0.1/docs/integrations/vectorstores/)
        
    *   [Retrievers](/v0.1/docs/integrations/retrievers/)
        
    *   [Tools](/v0.1/docs/integrations/tools/)
        
    *   [Agents and toolkits](/v0.1/docs/integrations/toolkits/)
        
    *   [Chat Memory](/v0.1/docs/integrations/chat_memory/)
        
    *   [Stores](/v0.1/docs/integrations/stores/)
        

*   [](/v0.1/)
*   [Components](/v0.1/docs/integrations/components/)
*   [Document compressors](/v0.1/docs/integrations/document_compressors/)
*   Cohere Rerank

On this page

Cohere Rerank
=============

Reranking documents can greatly improve any RAG application and document retrieval system.

At a high level, a rerank API is a language model which analyzes documents and reorders them based on their relevance to a given query.

Cohere offers an API for reranking documents. In this example we'll show you how to use it.

Setup[​](#setup "Direct link to Setup")
---------------------------------------

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/cohere

    yarn add @langchain/cohere

    pnpm add @langchain/cohere

    import { CohereRerank } from "@langchain/cohere";import { Document } from "@langchain/core/documents";const query = "What is the capital of the United States?";const docs = [  new Document({    pageContent:      "Carson City is the capital city of the American state of Nevada. At the 2010 United States Census, Carson City had a population of 55,274.",  }),  new Document({    pageContent:      "The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean that are a political division controlled by the United States. Its capital is Saipan.",  }),  new Document({    pageContent:      "Charlotte Amalie is the capital and largest city of the United States Virgin Islands. It has about 20,000 people. The city is on the island of Saint Thomas.",  }),  new Document({    pageContent:      "Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district. The President of the USA and many major national government offices are in the territory. This makes it the political center of the United States of America.",  }),  new Document({    pageContent:      "Capital punishment (the death penalty) has existed in the United States since before the United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states. The federal government (including the United States military) also uses capital punishment.",  }),];const cohereRerank = new CohereRerank({  apiKey: process.env.COHERE_API_KEY, // Default  model: "rerank-english-v2.0", // Default});const rerankedDocuments = await cohereRerank.rerank(docs, query, {  topN: 5,});console.log(rerankedDocuments);/**[  { index: 3, relevanceScore: 0.9871293 },  { index: 1, relevanceScore: 0.29961726 },  { index: 4, relevanceScore: 0.27542195 },  { index: 0, relevanceScore: 0.08977329 },  { index: 2, relevanceScore: 0.041462272 }] */

#### API Reference:

*   [CohereRerank](https://api.js.langchain.com/classes/langchain_cohere.CohereRerank.html) from `@langchain/cohere`
*   [Document](https://api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents`

Here, we can see the `.rerank()` method returns just the index of the documents (matching the indexes of the input documents) and their relevancy scores.

If we'd like to have the documents returned from the method itself, we can use the `.compressDocuments()` method.

    import { CohereRerank } from "@langchain/cohere";import { Document } from "@langchain/core/documents";const query = "What is the capital of the United States?";const docs = [  new Document({    pageContent:      "Carson City is the capital city of the American state of Nevada. At the 2010 United States Census, Carson City had a population of 55,274.",  }),  new Document({    pageContent:      "The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean that are a political division controlled by the United States. Its capital is Saipan.",  }),  new Document({    pageContent:      "Charlotte Amalie is the capital and largest city of the United States Virgin Islands. It has about 20,000 people. The city is on the island of Saint Thomas.",  }),  new Document({    pageContent:      "Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district. The President of the USA and many major national government offices are in the territory. This makes it the political center of the United States of America.",  }),  new Document({    pageContent:      "Capital punishment (the death penalty) has existed in the United States since before the United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states. The federal government (including the United States military) also uses capital punishment.",  }),];const cohereRerank = new CohereRerank({  apiKey: process.env.COHERE_API_KEY, // Default  topN: 3, // Default  model: "rerank-english-v2.0", // Default});const rerankedDocuments = await cohereRerank.compressDocuments(docs, query);console.log(rerankedDocuments);/**[  Document {    pageContent: 'Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district. The President of the USA and many major national government offices are in the territory. This makes it the political center of the United States of America.',    metadata: { relevanceScore: 0.9871293 }  },  Document {    pageContent: 'The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean that are a political division controlled by the United States. Its capital is Saipan.',    metadata: { relevanceScore: 0.29961726 }  },  Document {    pageContent: 'Capital punishment (the death penalty) has existed in the United States since before the United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states. The federal government (including the United States military) also uses capital punishment.',    metadata: { relevanceScore: 0.27542195 }  }] */

#### API Reference:

*   [CohereRerank](https://api.js.langchain.com/classes/langchain_cohere.CohereRerank.html) from `@langchain/cohere`
*   [Document](https://api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents`

From the results, we can see it returned the top 3 documents, and assigned a `relevanceScore` to each.

As expected, the document with the highest `relevanceScore` is the one that references Washington, D.C., with a score of `98.7%`!

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Document compressors

](/v0.1/docs/integrations/document_compressors/)[

Next

Text embedding models

](/v0.1/docs/integrations/text_embedding/)

*   [Setup](#setup)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.