From e28c6403aad2356ee42bd83e9346b26bccbf8564 Mon Sep 17 00:00:00 2001 From: Harrison Chase Date: Mon, 1 May 2023 15:40:16 -0700 Subject: [PATCH] Harrison/cohere reranker (#3904) --- .../retrievers/examples/cohere-reranker.ipynb | 418 ++++++++++++++++++ langchain/document_loaders/git.py | 2 +- .../document_compressors/__init__.py | 2 + .../document_compressors/cohere_rerank.py | 55 +++ 4 files changed, 476 insertions(+), 1 deletion(-) create mode 100644 docs/modules/indexes/retrievers/examples/cohere-reranker.ipynb create mode 100644 langchain/retrievers/document_compressors/cohere_rerank.py diff --git a/docs/modules/indexes/retrievers/examples/cohere-reranker.ipynb b/docs/modules/indexes/retrievers/examples/cohere-reranker.ipynb new file mode 100644 index 0000000000..7e4f4f0f35 --- /dev/null +++ b/docs/modules/indexes/retrievers/examples/cohere-reranker.ipynb @@ -0,0 +1,418 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "fc0db1bc", + "metadata": {}, + "source": [ + "# Cohere Reranker\n", + "\n", + "This notebook shows how to use [Cohere's rerank endpoint](https://docs.cohere.com/docs/reranking) in a retriever. This builds on top of ideas in the [ContextualCompressionRetriever](contextual-compression.ipynb)." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "28e8dc12", + "metadata": {}, + "outputs": [], + "source": [ + "# Helper function for printing docs\n", + "\n", + "def pretty_print_docs(docs):\n", + " print(f\"\\n{'-' * 100}\\n\".join([f\"Document {i+1}:\\n\\n\" + d.page_content for i, d in enumerate(docs)]))" + ] + }, + { + "cell_type": "markdown", + "id": "6fa3d916", + "metadata": {}, + "source": [ + "## Set up the base vector store retriever\n", + "Let's start by initializing a simple vector store retriever and storing the 2023 State of the Union speech (in chunks). We can set up the retriever to retrieve a high number (20) of docs." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "9fbcc58f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Document 1:\n", + "\n", + "One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n", + "\n", + "And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 2:\n", + "\n", + "As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \n", + "\n", + "While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 3:\n", + "\n", + "A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n", + "\n", + "And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 4:\n", + "\n", + "He met the Ukrainian people. \n", + "\n", + "From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n", + "\n", + "Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. \n", + "\n", + "In this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.” The Ukrainian Ambassador to the United States is here tonight.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 5:\n", + "\n", + "I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. \n", + "\n", + "I’ve worked on these issues a long time. \n", + "\n", + "I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. \n", + "\n", + "So let’s not abandon our streets. Or choose between safety and equal justice.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 6:\n", + "\n", + "Vice President Harris and I ran for office with a new economic vision for America. \n", + "\n", + "Invest in America. Educate Americans. Grow the workforce. Build the economy from the bottom up \n", + "and the middle out, not from the top down. \n", + "\n", + "Because we know that when the middle class grows, the poor have a ladder up and the wealthy do very well. \n", + "\n", + "America used to have the best roads, bridges, and airports on Earth. \n", + "\n", + "Now our infrastructure is ranked 13th in the world.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 7:\n", + "\n", + "And tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud. \n", + "\n", + "By the end of this year, the deficit will be down to less than half what it was before I took office. \n", + "\n", + "The only president ever to cut the deficit by more than one trillion dollars in a single year. \n", + "\n", + "Lowering your costs also means demanding more competition. \n", + "\n", + "I’m a capitalist, but capitalism without competition isn’t capitalism. \n", + "\n", + "It’s exploitation—and it drives up prices.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 8:\n", + "\n", + "For the past 40 years we were told that if we gave tax breaks to those at the very top, the benefits would trickle down to everyone else. \n", + "\n", + "But that trickle-down theory led to weaker economic growth, lower wages, bigger deficits, and the widest gap between those at the top and everyone else in nearly a century. \n", + "\n", + "Vice President Harris and I ran for office with a new economic vision for America.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 9:\n", + "\n", + "All told, we created 369,000 new manufacturing jobs in America just last year. \n", + "\n", + "Powered by people I’ve met like JoJo Burgess, from generations of union steelworkers from Pittsburgh, who’s here with us tonight. \n", + "\n", + "As Ohio Senator Sherrod Brown says, “It’s time to bury the label “Rust Belt.” \n", + "\n", + "It’s time. \n", + "\n", + "But with all the bright spots in our economy, record job growth and higher wages, too many families are struggling to keep up with the bills.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 10:\n", + "\n", + "I’m also calling on Congress: pass a law to make sure veterans devastated by toxic exposures in Iraq and Afghanistan finally get the benefits and comprehensive health care they deserve. \n", + "\n", + "And fourth, let’s end cancer as we know it. \n", + "\n", + "This is personal to me and Jill, to Kamala, and to so many of you. \n", + "\n", + "Cancer is the #2 cause of death in America–second only to heart disease.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 11:\n", + "\n", + "He will never extinguish their love of freedom. He will never weaken the resolve of the free world. \n", + "\n", + "We meet tonight in an America that has lived through two of the hardest years this nation has ever faced. \n", + "\n", + "The pandemic has been punishing. \n", + "\n", + "And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more. \n", + "\n", + "I understand.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 12:\n", + "\n", + "Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n", + "\n", + "Last year COVID-19 kept us apart. This year we are finally together again. \n", + "\n", + "Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n", + "\n", + "With a duty to one another to the American people to the Constitution. \n", + "\n", + "And with an unwavering resolve that freedom will always triumph over tyranny.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 13:\n", + "\n", + "I know. \n", + "\n", + "One of those soldiers was my son Major Beau Biden. \n", + "\n", + "We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. \n", + "\n", + "But I’m committed to finding out everything we can. \n", + "\n", + "Committed to military families like Danielle Robinson from Ohio. \n", + "\n", + "The widow of Sergeant First Class Heath Robinson. \n", + "\n", + "He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 14:\n", + "\n", + "And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. \n", + "\n", + "So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \n", + "\n", + "First, beat the opioid epidemic. \n", + "\n", + "There is so much we can do. Increase funding for prevention, treatment, harm reduction, and recovery.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 15:\n", + "\n", + "Third, support our veterans. \n", + "\n", + "Veterans are the best of us. \n", + "\n", + "I’ve always believed that we have a sacred obligation to equip all those we send to war and care for them and their families when they come home. \n", + "\n", + "My administration is providing assistance with job training and housing, and now helping lower-income veterans get VA care debt-free. \n", + "\n", + "Our troops in Iraq and Afghanistan faced many dangers.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 16:\n", + "\n", + "When we invest in our workers, when we build the economy from the bottom up and the middle out together, we can do something we haven’t done in a long time: build a better America. \n", + "\n", + "For more than two years, COVID-19 has impacted every decision in our lives and the life of the nation. \n", + "\n", + "And I know you’re tired, frustrated, and exhausted. \n", + "\n", + "But I also know this.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 17:\n", + "\n", + "Now is the hour. \n", + "\n", + "Our moment of responsibility. \n", + "\n", + "Our test of resolve and conscience, of history itself. \n", + "\n", + "It is in this moment that our character is formed. Our purpose is found. Our future is forged. \n", + "\n", + "Well I know this nation. \n", + "\n", + "We will meet the test. \n", + "\n", + "To protect freedom and liberty, to expand fairness and opportunity. \n", + "\n", + "We will save democracy. \n", + "\n", + "As hard as these times have been, I am more optimistic about America today than I have been my whole life.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 18:\n", + "\n", + "He didn’t know how to stop fighting, and neither did she. \n", + "\n", + "Through her pain she found purpose to demand we do better. \n", + "\n", + "Tonight, Danielle—we are. \n", + "\n", + "The VA is pioneering new ways of linking toxic exposures to diseases, already helping more veterans get benefits. \n", + "\n", + "And tonight, I’m announcing we’re expanding eligibility to veterans suffering from nine respiratory cancers.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 19:\n", + "\n", + "I understand. \n", + "\n", + "I remember when my Dad had to leave our home in Scranton, Pennsylvania to find work. I grew up in a family where if the price of food went up, you felt it. \n", + "\n", + "That’s why one of the first things I did as President was fight to pass the American Rescue Plan. \n", + "\n", + "Because people were hurting. We needed to act, and we did. \n", + "\n", + "Few pieces of legislation have done more in a critical moment in our history to lift us out of crisis.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 20:\n", + "\n", + "So let’s not abandon our streets. Or choose between safety and equal justice. \n", + "\n", + "Let’s come together to protect our communities, restore trust, and hold law enforcement accountable. \n", + "\n", + "That’s why the Justice Department required body cameras, banned chokeholds, and restricted no-knock warrants for its officers.\n" + ] + } + ], + "source": [ + "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", + "from langchain.embeddings import OpenAIEmbeddings\n", + "from langchain.document_loaders import TextLoader\n", + "from langchain.vectorstores import FAISS\n", + "\n", + "documents = TextLoader('../../../state_of_the_union.txt').load()\n", + "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)\n", + "texts = text_splitter.split_documents(documents)\n", + "retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever(search_kwargs={\"k\": 20})\n", + "\n", + "query = \"What did the president say about Ketanji Brown Jackson\"\n", + "docs = retriever.get_relevant_documents(query)\n", + "pretty_print_docs(docs)" + ] + }, + { + "cell_type": "markdown", + "id": "b7648612", + "metadata": {}, + "source": [ + "## Doing reranking with CohereRerank\n", + "Now let's wrap our base retriever with a `ContextualCompressionRetriever`. We'll add an `CohereRerank`, uses the Cohere rerank endpoint to rerank the returned results." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "9a658023", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Document 1:\n", + "\n", + "One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n", + "\n", + "And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 2:\n", + "\n", + "I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. \n", + "\n", + "I’ve worked on these issues a long time. \n", + "\n", + "I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. \n", + "\n", + "So let’s not abandon our streets. Or choose between safety and equal justice.\n", + "----------------------------------------------------------------------------------------------------\n", + "Document 3:\n", + "\n", + "A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n", + "\n", + "And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system.\n" + ] + } + ], + "source": [ + "from langchain.llms import OpenAI\n", + "from langchain.retrievers import ContextualCompressionRetriever\n", + "from langchain.retrievers.document_compressors import CohereRerank\n", + "\n", + "llm = OpenAI(temperature=0)\n", + "compressor = CohereRerank()\n", + "compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever)\n", + "\n", + "compressed_docs = compression_retriever.get_relevant_documents(\"What did the president say about Ketanji Jackson Brown\")\n", + "pretty_print_docs(compressed_docs)" + ] + }, + { + "cell_type": "markdown", + "id": "b83dfedb", + "metadata": {}, + "source": [ + "You can of course use this retriever within a QA pipeline" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "367dafe0", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.chains import RetrievalQA" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "ae697ca4", + "metadata": {}, + "outputs": [], + "source": [ + "chain = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), retriever=compression_retriever)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "46ee62fc", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'query': 'What did the president say about Ketanji Brown Jackson',\n", + " 'result': \" The president said that Ketanji Brown Jackson is one of the nation's top legal minds and that she is a consensus builder who has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"}" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "chain({\"query\": query})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "700a8133", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.1" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/langchain/document_loaders/git.py b/langchain/document_loaders/git.py index a862e8f031..fb4e05ed4d 100644 --- a/langchain/document_loaders/git.py +++ b/langchain/document_loaders/git.py @@ -54,7 +54,7 @@ class GitLoader(BaseLoader): file_path = os.path.join(self.repo_path, item.path) - ignored_files = repo.ignored([file_path]) + ignored_files = repo.ignored([file_path]) # type: ignore if len(ignored_files): continue diff --git a/langchain/retrievers/document_compressors/__init__.py b/langchain/retrievers/document_compressors/__init__.py index 528eae7194..410ad540d1 100644 --- a/langchain/retrievers/document_compressors/__init__.py +++ b/langchain/retrievers/document_compressors/__init__.py @@ -5,6 +5,7 @@ from langchain.retrievers.document_compressors.chain_extract import ( from langchain.retrievers.document_compressors.chain_filter import ( LLMChainFilter, ) +from langchain.retrievers.document_compressors.cohere_rerank import CohereRerank from langchain.retrievers.document_compressors.embeddings_filter import ( EmbeddingsFilter, ) @@ -14,4 +15,5 @@ __all__ = [ "EmbeddingsFilter", "LLMChainExtractor", "LLMChainFilter", + "CohereRerank", ] diff --git a/langchain/retrievers/document_compressors/cohere_rerank.py b/langchain/retrievers/document_compressors/cohere_rerank.py new file mode 100644 index 0000000000..43b084d770 --- /dev/null +++ b/langchain/retrievers/document_compressors/cohere_rerank.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Sequence + +from pydantic import root_validator + +from langchain.retrievers.document_compressors.base import BaseDocumentCompressor +from langchain.schema import Document +from langchain.utils import get_from_dict_or_env + +if TYPE_CHECKING: + from cohere import Client + + +class CohereRerank(BaseDocumentCompressor): + client: Client + top_n: int = 3 + model: str = "rerank-english-v2.0" + + @root_validator() + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + cohere_api_key = get_from_dict_or_env( + values, "cohere_api_key", "COHERE_API_KEY" + ) + try: + import cohere + + values["client"] = cohere.Client(cohere_api_key) + except ImportError: + raise ValueError( + "Could not import cohere python package. " + "Please install it with `pip install cohere`." + ) + return values + + def compress_documents( + self, documents: Sequence[Document], query: str + ) -> Sequence[Document]: + doc_list = list(documents) + _docs = [d.page_content for d in doc_list] + results = self.client.rerank( + model=self.model, query=query, documents=_docs, top_n=self.top_n + ) + final_results = [] + for r in results: + doc = doc_list[r.index] + doc.metadata["relevance_score"] = r.relevance_score + final_results.append(doc) + return final_results + + async def acompress_documents( + self, documents: Sequence[Document], query: str + ) -> Sequence[Document]: + raise NotImplementedError