From 47d37db2d228c819372c9bec1dacf38621fe0c60 Mon Sep 17 00:00:00 2001 From: Harrison Chase Date: Fri, 24 Mar 2023 07:46:49 -0700 Subject: [PATCH] WIP: Harrison/base retriever (#1765) --- .../agents/examples/agent_vectorstore.ipynb | 23 +-- .../chat/examples/chat_vector_db.ipynb | 30 ++-- docs/modules/chat/examples/vector_db_qa.ipynb | 18 +-- .../examples/vector_db_qa_with_sources.ipynb | 34 ++-- docs/modules/indexes.rst | 16 +- .../chain_examples/chat_vector_db.ipynb | 105 ++++++------- .../indexes/chain_examples/vector_db_qa.ipynb | 63 ++++---- .../vector_db_qa_with_sources.ipynb | 57 ++++--- docs/modules/indexes/getting_started.ipynb | 147 ++++++++++++++---- docs/modules/indexes/how_to_guides.rst | 4 +- .../chatgpt-plugin-retriever.ipynb | 2 +- .../vectorstore-retriever.ipynb | 93 +++++++++++ docs/use_cases/evaluation.rst | 2 +- .../evaluation/agent_vectordb_sota_pg.ipynb | 67 ++++---- .../data_augmented_question_answering.ipynb | 7 +- .../evaluation/qa_benchmarking_pg.ipynb | 20 +-- .../evaluation/qa_benchmarking_sota.ipynb | 89 +---------- langchain/chains/chat_vector_db/__init__.py | 0 .../chains/conversational_retrieval/base.py | 13 +- langchain/chains/qa_with_sources/retrieval.py | 2 +- langchain/chains/qa_with_sources/vector_db.py | 11 +- langchain/chains/retrieval_qa/base.py | 11 +- .../retrievers/chatgpt_plugin_retriever.py | 2 +- langchain/schema.py | 6 +- langchain/vectorstores/base.py | 26 +++- 25 files changed, 509 insertions(+), 339 deletions(-) create mode 100644 docs/modules/indexes/retriever_examples/vectorstore-retriever.ipynb create mode 100644 langchain/chains/chat_vector_db/__init__.py diff --git a/docs/modules/agents/examples/agent_vectorstore.ipynb b/docs/modules/agents/examples/agent_vectorstore.ipynb index f8e67218..5f776e54 100644 --- a/docs/modules/agents/examples/agent_vectorstore.ipynb +++ b/docs/modules/agents/examples/agent_vectorstore.ipynb @@ -22,7 +22,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 1, "id": "2e87c10a", "metadata": {}, "outputs": [], @@ -30,13 +30,14 @@ "from langchain.embeddings.openai import OpenAIEmbeddings\n", "from langchain.vectorstores import Chroma\n", "from langchain.text_splitter import CharacterTextSplitter\n", - "from langchain import OpenAI, VectorDBQA\n", + "from langchain.llms import OpenAI\n", + "from langchain.chains import RetrievalQA\n", "llm = OpenAI(temperature=0)" ] }, { "cell_type": "code", - "execution_count": 37, + "execution_count": 2, "id": "f2675861", "metadata": {}, "outputs": [ @@ -62,17 +63,17 @@ }, { "cell_type": "code", - "execution_count": 38, + "execution_count": 4, "id": "bc5403d4", "metadata": {}, "outputs": [], "source": [ - "state_of_union = VectorDBQA.from_chain_type(llm=llm, chain_type=\"stuff\", vectorstore=docsearch)" + "state_of_union = RetrievalQA.from_chain_type(llm=llm, chain_type=\"stuff\", retriever=docsearch.as_retriever())" ] }, { "cell_type": "code", - "execution_count": 39, + "execution_count": 5, "id": "1431cded", "metadata": {}, "outputs": [], @@ -82,7 +83,7 @@ }, { "cell_type": "code", - "execution_count": 40, + "execution_count": 6, "id": "915d3ff3", "metadata": {}, "outputs": [], @@ -92,7 +93,7 @@ }, { "cell_type": "code", - "execution_count": 41, + "execution_count": 7, "id": "96a2edf8", "metadata": {}, "outputs": [ @@ -109,7 +110,7 @@ "docs = loader.load()\n", "ruff_texts = text_splitter.split_documents(docs)\n", "ruff_db = Chroma.from_documents(ruff_texts, embeddings, collection_name=\"ruff\")\n", - "ruff = VectorDBQA.from_chain_type(llm=llm, chain_type=\"stuff\", vectorstore=ruff_db)" + "ruff = RetrievalQA.from_chain_type(llm=llm, chain_type=\"stuff\", retriever=ruff_db.as_retriever())" ] }, { @@ -264,9 +265,9 @@ "id": "9161ba91", "metadata": {}, "source": [ - "You can also set `return_direct=True` if you intend to use the agent as a router and just want to directly return the result of the VectorDBQaChain.\n", + "You can also set `return_direct=True` if you intend to use the agent as a router and just want to directly return the result of the RetrievalQAChain.\n", "\n", - "Notice that in the above examples the agent did some extra work after querying the VectorDBQAChain. You can avoid that and just return the result directly." + "Notice that in the above examples the agent did some extra work after querying the RetrievalQAChain. You can avoid that and just return the result directly." ] }, { diff --git a/docs/modules/chat/examples/chat_vector_db.ipynb b/docs/modules/chat/examples/chat_vector_db.ipynb index 6f3301db..a2a964f7 100644 --- a/docs/modules/chat/examples/chat_vector_db.ipynb +++ b/docs/modules/chat/examples/chat_vector_db.ipynb @@ -9,7 +9,7 @@ "\n", "This notebook goes over how to set up a chat model to chat with a vector database.\n", "\n", - "This notebook is very similar to the example of using an LLM in the ChatVectorDBChain. The only differences here are (1) using a ChatModel, and (2) passing in a ChatPromptTemplate (optimized for chat models)." + "This notebook is very similar to the example of using an LLM in the ConversationalRetrievalChain. The only differences here are (1) using a ChatModel, and (2) passing in a ChatPromptTemplate (optimized for chat models)." ] }, { @@ -24,7 +24,7 @@ "from langchain.embeddings.openai import OpenAIEmbeddings\n", "from langchain.vectorstores import Chroma\n", "from langchain.text_splitter import CharacterTextSplitter\n", - "from langchain.chains import ChatVectorDBChain" + "from langchain.chains import ConversationalRetrievalChain" ] }, { @@ -157,7 +157,7 @@ "id": "3c96b118", "metadata": {}, "source": [ - "We now initialize the ChatVectorDBChain" + "We now initialize the ConversationalRetrievalChain" ] }, { @@ -169,7 +169,7 @@ }, "outputs": [], "source": [ - "qa = ChatVectorDBChain.from_llm(ChatOpenAI(temperature=0), vectorstore,qa_prompt=prompt)" + "qa = ConversationalRetrievalChain.from_llm(ChatOpenAI(temperature=0), vectorstore,qa_prompt=prompt)" ] }, { @@ -205,7 +205,7 @@ { "data": { "text/plain": [ - "\"The President nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to serve on the United States Supreme Court. He described her as one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and a consensus builder. He also mentioned that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" + "\"The President nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to serve on the United States Supreme Court. He described her as one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and a consensus builder. She has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, "execution_count": 9, @@ -227,7 +227,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 10, "id": "00b4cf00", "metadata": { "tags": [] @@ -241,7 +241,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 11, "id": "f01828d1", "metadata": { "tags": [] @@ -250,10 +250,10 @@ { "data": { "text/plain": [ - "'The context does not provide information about the predecessor of Ketanji Brown Jackson.'" + "\"The President mentioned Circuit Court of Appeals Judge Ketanji Brown Jackson as the nominee for the United States Supreme Court. He described her as one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. The President did not mention any specific sources of support for Judge Jackson, but he did note that advancing immigration reform is supported by everyone from labor unions to religious leaders to the U.S. Chamber of Commerce.\"" ] }, - "execution_count": 13, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } @@ -267,14 +267,14 @@ "id": "2324cdc6-98bf-4708-b8cd-02a98b1e5b67", "metadata": {}, "source": [ - "## Chat Vector DB with streaming to `stdout`\n", + "## ConversationalRetrievalChain with streaming to `stdout`\n", "\n", "Output from the chain will be streamed to `stdout` token by token in this example." ] }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 12, "id": "2efacec3-2690-4b05-8de3-a32fd2ac3911", "metadata": { "tags": [] @@ -285,7 +285,7 @@ "from langchain.llms import OpenAI\n", "from langchain.callbacks.base import CallbackManager\n", "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n", - "from langchain.chains.chat_vector_db.prompts import CONDENSE_QUESTION_PROMPT\n", + "from langchain.chains.chat_index.prompts import CONDENSE_QUESTION_PROMPT\n", "from langchain.chains.question_answering import load_qa_chain\n", "\n", "# Construct a ChatVectorDBChain with a streaming llm for combine docs\n", @@ -296,12 +296,12 @@ "question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)\n", "doc_chain = load_qa_chain(streaming_llm, chain_type=\"stuff\", prompt=prompt)\n", "\n", - "qa = ChatVectorDBChain(vectorstore=vectorstore, combine_docs_chain=doc_chain, question_generator=question_generator)" + "qa = ConversationalRetrievalChain(retriever=vectorstore.as_retriever(), combine_docs_chain=doc_chain, question_generator=question_generator)\n" ] }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 13, "id": "fd6d43f4-7428-44a4-81bc-26fe88a98762", "metadata": { "tags": [] @@ -323,7 +323,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 14, "id": "5ab38978-f3e8-4fa7-808c-c79dec48379a", "metadata": { "tags": [] diff --git a/docs/modules/chat/examples/vector_db_qa.ipynb b/docs/modules/chat/examples/vector_db_qa.ipynb index 7ee0bc4d..368af6e3 100644 --- a/docs/modules/chat/examples/vector_db_qa.ipynb +++ b/docs/modules/chat/examples/vector_db_qa.ipynb @@ -5,16 +5,16 @@ "id": "07c1e3b9", "metadata": {}, "source": [ - "# Vector DB Question/Answering\n", + "# Retrieval Question/Answering\n", "\n", "This example showcases using a chat model to do question answering over a vector database.\n", "\n", - "This notebook is very similar to the example of using an LLM in the ChatVectorDBChain. The only differences here are (1) using a ChatModel, and (2) passing in a ChatPromptTemplate (optimized for chat models)." + "This notebook is very similar to the example of using an LLM in the RetrievalQA. The only differences here are (1) using a ChatModel, and (2) passing in a ChatPromptTemplate (optimized for chat models)." ] }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 7, "id": "82525493", "metadata": {}, "outputs": [], @@ -22,7 +22,7 @@ "from langchain.embeddings.openai import OpenAIEmbeddings\n", "from langchain.vectorstores import Chroma\n", "from langchain.text_splitter import CharacterTextSplitter\n", - "from langchain.chains import VectorDBQA" + "from langchain.chains import RetrievalQA" ] }, { @@ -100,28 +100,28 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 8, "id": "3018f865", "metadata": {}, "outputs": [], "source": [ "chain_type_kwargs = {\"prompt\": prompt}\n", - "qa = VectorDBQA.from_chain_type(llm=ChatOpenAI(), chain_type=\"stuff\", vectorstore=docsearch, chain_type_kwargs=chain_type_kwargs)" + "qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(), chain_type=\"stuff\", retriever=docsearch.as_retriever(), chain_type_kwargs=chain_type_kwargs)\n" ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 9, "id": "032a47f8", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "\"The President nominated Ketanji Brown Jackson as a Judge for the United States Supreme Court. He described her as one of the nation's top legal minds and a former top litigator in private practice, a former federal public defender, and a consensus builder.\"" + "\"The president nominated Ketanji Brown Jackson to serve on the United States Supreme Court. He referred to her as one of our nation's top legal minds, a former federal public defender, a consensus builder, and from a family of public school educators and police officers. Since she's been nominated, she has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, - "execution_count": 7, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } diff --git a/docs/modules/chat/examples/vector_db_qa_with_sources.ipynb b/docs/modules/chat/examples/vector_db_qa_with_sources.ipynb index c58a8dbc..88d01a22 100644 --- a/docs/modules/chat/examples/vector_db_qa_with_sources.ipynb +++ b/docs/modules/chat/examples/vector_db_qa_with_sources.ipynb @@ -5,11 +5,11 @@ "id": "efc5be67", "metadata": {}, "source": [ - "# VectorDB Question Answering with Sources\n", + "# Retrieval Question Answering with Sources\n", "\n", - "This notebook goes over how to do question-answering with sources with a chat model over a vector database. It does this by using the `VectorDBQAWithSourcesChain`, which does the lookup of the documents from a vector database. \n", + "This notebook goes over how to do question-answering with sources with a chat model over a vector database. It does this by using the `RetrievalQAWithSourcesChain`, which does the lookup of the documents from a vector database. \n", "\n", - "This notebook is very similar to the example of using an LLM in the ChatVectorDBChain. The only differences here are (1) using a ChatModel, and (2) passing in a ChatPromptTemplate (optimized for chat models)." + "This notebook is very similar to the example of using an LLM in the RetrievalQAWithSources. The only differences here are (1) using a ChatModel, and (2) passing in a ChatPromptTemplate (optimized for chat models)." ] }, { @@ -51,6 +51,8 @@ "name": "stdout", "output_type": "stream", "text": [ + "Running Chroma using direct local API.\n", + "Using DuckDB in-memory for database. Data will be transient.\n", "Running Chroma using direct local API.\n", "Using DuckDB in-memory for database. Data will be transient.\n" ] @@ -62,12 +64,12 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 9, "id": "8aa571ae", "metadata": {}, "outputs": [], "source": [ - "from langchain.chains import VectorDBQAWithSourcesChain" + "from langchain.chains import RetrievalQAWithSourcesChain" ] }, { @@ -101,7 +103,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 6, "id": "ed00e906", "metadata": {}, "outputs": [], @@ -130,23 +132,23 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 10, "id": "aa859d4c", "metadata": {}, "outputs": [], "source": [ "chain_type_kwargs = {\"prompt\": prompt}\n", - "chain = VectorDBQAWithSourcesChain.from_chain_type(\n", + "chain = RetrievalQAWithSourcesChain.from_chain_type(\n", " ChatOpenAI(temperature=0), \n", " chain_type=\"stuff\", \n", - " vectorstore=docsearch,\n", + " retriever=docsearch.as_retriever(),\n", " chain_type_kwargs=chain_type_kwargs\n", ")" ] }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 11, "id": "8ba36fa7", "metadata": {}, "outputs": [ @@ -154,10 +156,10 @@ "data": { "text/plain": [ "{'answer': 'The President honored Justice Stephen Breyer, an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court, for his dedicated service to the country. \\n',\n", - " 'sources': '30-pl'}" + " 'sources': '31-pl'}" ] }, - "execution_count": 19, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } @@ -165,6 +167,14 @@ "source": [ "chain({\"question\": \"What did the president say about Justice Breyer\"}, return_only_outputs=True)" ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8308fbf7", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { diff --git a/docs/modules/indexes.rst b/docs/modules/indexes.rst index 1dca0186..5d58558a 100644 --- a/docs/modules/indexes.rst +++ b/docs/modules/indexes.rst @@ -3,16 +3,24 @@ Indexes Indexes refer to ways to structure documents so that LLMs can best interact with them. This module contains utility functions for working with documents, different types of indexes, and then examples for using those indexes in chains. -LangChain provides common indices for working with data (most prominently support for vector databases). -For more complicated index structures, it is worth checking out `LlamaIndex `_. + +The most common way that indexes are used in chains is in a "retrieval" step. +This step refers to taking a user's query and returning the most relevant documents. +We draw this distinction because (1) an index can be used for other things besides retrieval, and (2) retrieval can use other logic besides an index to find relevant documents. +We therefor have a concept of a "Retriever" interface - this is the interface that most chains work with. + +Most of the time when we talk about indexes and retrieval we are talking about indexing and retrieving unstructured data (like text documents). +For interacting with structured data (SQL tables, etc) or APIs, please see the corresponding use case sections for links to relevant functionality. +The primary index and retrieval types supported by LangChain are currently centered around vector databases, and therefore +a lot of the functionality we dive deep on those topics. The following sections of documentation are provided: -- `Getting Started <./indexes/getting_started.html>`_: An overview of all the functionality LangChain provides for working with indexes. +- `Getting Started <./indexes/getting_started.html>`_: An overview of the base "Retriever" interface, and then all the functionality LangChain provides for working with indexes. - `Key Concepts <./indexes/key_concepts.html>`_: A conceptual guide going over the various concepts related to indexes and the tools needed to create them. -- `How-To Guides <./indexes/how_to_guides.html>`_: A collection of how-to guides. These highlight how to use all the relevant tools, the different types of vector databases, and how to use indexes in chains. +- `How-To Guides <./indexes/how_to_guides.html>`_: A collection of how-to guides. These highlight how to use all the relevant tools, the different types of vector databases, different types of retrievers, and how to use retrievers and indexes in chains. .. toctree:: diff --git a/docs/modules/indexes/chain_examples/chat_vector_db.ipynb b/docs/modules/indexes/chain_examples/chat_vector_db.ipynb index d5b7148d..8d6adc9e 100644 --- a/docs/modules/indexes/chain_examples/chat_vector_db.ipynb +++ b/docs/modules/indexes/chain_examples/chat_vector_db.ipynb @@ -5,9 +5,9 @@ "id": "134a0785", "metadata": {}, "source": [ - "# Chat Vector DB\n", + "# Chat Index\n", "\n", - "This notebook goes over how to set up a chain to chat with a vector database. The only difference between this chain and the [VectorDBQAChain](./vector_db_qa.ipynb) is that this allows for passing in of a chat history which can be used to allow for follow up questions." + "This notebook goes over how to set up a chain to chat with an index. The only difference between this chain and the [RetrievalQAChain](./vector_db_qa.ipynb) is that this allows for passing in of a chat history which can be used to allow for follow up questions." ] }, { @@ -23,7 +23,7 @@ "from langchain.vectorstores import Chroma\n", "from langchain.text_splitter import CharacterTextSplitter\n", "from langchain.llms import OpenAI\n", - "from langchain.chains import ChatVectorDBChain" + "from langchain.chains import ConversationalRetrievalChain" ] }, { @@ -109,7 +109,7 @@ "id": "3c96b118", "metadata": {}, "source": [ - "We now initialize the ChatVectorDBChain" + "We now initialize the ConversationalRetrievalChain" ] }, { @@ -121,7 +121,7 @@ }, "outputs": [], "source": [ - "qa = ChatVectorDBChain.from_llm(OpenAI(temperature=0), vectorstore)" + "qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore)" ] }, { @@ -220,22 +220,22 @@ "metadata": {}, "source": [ "## Return Source Documents\n", - "You can also easily return source documents from the ChatVectorDBChain. This is useful for when you want to inspect what documents were returned." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "562769c6", - "metadata": {}, - "outputs": [], - "source": [ - "qa = ChatVectorDBChain.from_llm(OpenAI(temperature=0), vectorstore, return_source_documents=True)" + "You can also easily return source documents from the ConversationalRetrievalChain. This is useful for when you want to inspect what documents were returned." ] }, { "cell_type": "code", "execution_count": 11, + "id": "562769c6", + "metadata": {}, + "outputs": [], + "source": [ + "qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore, return_source_documents=True)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, "id": "ea478300", "metadata": {}, "outputs": [], @@ -247,17 +247,17 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 13, "id": "4cb75b4e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd 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.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0)" + "Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd 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.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0)" ] }, - "execution_count": 15, + "execution_count": 13, "metadata": {}, "output_type": "execute_result" } @@ -271,13 +271,13 @@ "id": "4f49beab", "metadata": {}, "source": [ - "## Chat Vector DB with `search_distance`\n", + "## ConversationalRetrievalChain with `search_distance`\n", "If you are using a vector store that supports filtering by search distance, you can add a threshold value parameter." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "id": "5ed8d612", "metadata": {}, "outputs": [], @@ -287,12 +287,12 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "id": "6a7b3459", "metadata": {}, "outputs": [], "source": [ - "qa = ChatVectorDBChain.from_llm(OpenAI(temperature=0), vectorstore, return_source_documents=True)\n", + "qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore, return_source_documents=True)\n", "chat_history = []\n", "query = \"What did the president say about Ketanji Brown Jackson\"\n", "result = qa({\"question\": query, \"chat_history\": chat_history, \"vectordbkwargs\": vectordbkwargs})" @@ -303,25 +303,25 @@ "id": "99b96dae", "metadata": {}, "source": [ - "## Chat Vector DB with `map_reduce`\n", - "We can also use different types of combine document chains with the Chat Vector DB chain." + "## ConversationalRetrievalChain with `map_reduce`\n", + "We can also use different types of combine document chains with the ConversationalRetrievalChain chain." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "id": "e53a9d66", "metadata": {}, "outputs": [], "source": [ "from langchain.chains import LLMChain\n", "from langchain.chains.question_answering import load_qa_chain\n", - "from langchain.chains.chat_vector_db.prompts import CONDENSE_QUESTION_PROMPT" + "from langchain.chains.chat_index.prompts import CONDENSE_QUESTION_PROMPT" ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 19, "id": "bf205e35", "metadata": {}, "outputs": [], @@ -330,8 +330,8 @@ "question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)\n", "doc_chain = load_qa_chain(llm, chain_type=\"map_reduce\")\n", "\n", - "chain = ChatVectorDBChain(\n", - " vectorstore=vectorstore,\n", + "chain = ConversationalRetrievalChain(\n", + " retriever=vectorstore.as_retriever(),\n", " question_generator=question_generator,\n", " combine_docs_chain=doc_chain,\n", ")" @@ -339,7 +339,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 20, "id": "78155887", "metadata": {}, "outputs": [], @@ -351,7 +351,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 21, "id": "e54b5fa2", "metadata": {}, "outputs": [ @@ -361,7 +361,7 @@ "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, from a family of public school educators and police officers, a consensus builder, and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, - "execution_count": 11, + "execution_count": 21, "metadata": {}, "output_type": "execute_result" } @@ -375,14 +375,14 @@ "id": "a2fe6b14", "metadata": {}, "source": [ - "## Chat Vector DB with Question Answering with sources\n", + "## ConversationalRetrievalChain with Question Answering with sources\n", "\n", "You can also use this chain with the question answering with sources chain." ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 22, "id": "d1058fd2", "metadata": {}, "outputs": [], @@ -392,7 +392,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 23, "id": "a6594482", "metadata": {}, "outputs": [], @@ -401,8 +401,8 @@ "question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)\n", "doc_chain = load_qa_with_sources_chain(llm, chain_type=\"map_reduce\")\n", "\n", - "chain = ChatVectorDBChain(\n", - " vectorstore=vectorstore,\n", + "chain = ConversationalRetrievalChain(\n", + " retriever=vectorstore.as_retriever(),\n", " question_generator=question_generator,\n", " combine_docs_chain=doc_chain,\n", ")" @@ -410,7 +410,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 24, "id": "e2badd21", "metadata": {}, "outputs": [], @@ -422,7 +422,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 25, "id": "edb31fe5", "metadata": {}, "outputs": [ @@ -432,7 +432,7 @@ "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, from a family of public school educators and police officers, a consensus builder, and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \\nSOURCES: ../../state_of_the_union.txt\"" ] }, - "execution_count": 16, + "execution_count": 25, "metadata": {}, "output_type": "execute_result" } @@ -446,14 +446,14 @@ "id": "2324cdc6-98bf-4708-b8cd-02a98b1e5b67", "metadata": {}, "source": [ - "## Chat Vector DB with streaming to `stdout`\n", + "## ConversationalRetrievalChain with streaming to `stdout`\n", "\n", "Output from the chain will be streamed to `stdout` token by token in this example." ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 26, "id": "2efacec3-2690-4b05-8de3-a32fd2ac3911", "metadata": { "tags": [] @@ -463,7 +463,7 @@ "from langchain.chains.llm import LLMChain\n", "from langchain.callbacks.base import CallbackManager\n", "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n", - "from langchain.chains.chat_vector_db.prompts import CONDENSE_QUESTION_PROMPT, QA_PROMPT\n", + "from langchain.chains.chat_index.prompts import CONDENSE_QUESTION_PROMPT, QA_PROMPT\n", "from langchain.chains.question_answering import load_qa_chain\n", "\n", "# Construct a ChatVectorDBChain with a streaming llm for combine docs\n", @@ -474,12 +474,13 @@ "question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)\n", "doc_chain = load_qa_chain(streaming_llm, chain_type=\"stuff\", prompt=QA_PROMPT)\n", "\n", - "qa = ChatVectorDBChain(vectorstore=vectorstore, combine_docs_chain=doc_chain, question_generator=question_generator)" + "qa = ConversationalRetrievalChain(\n", + " retriever=vectorstore.as_retriever(), combine_docs_chain=doc_chain, question_generator=question_generator)" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 27, "id": "fd6d43f4-7428-44a4-81bc-26fe88a98762", "metadata": { "tags": [] @@ -501,7 +502,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 28, "id": "5ab38978-f3e8-4fa7-808c-c79dec48379a", "metadata": { "tags": [] @@ -532,7 +533,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 29, "id": "a7ba9d8c", "metadata": {}, "outputs": [], @@ -542,12 +543,12 @@ " for human, ai in inputs:\n", " res.append(f\"Human:{human}\\nAI:{ai}\")\n", " return \"\\n\".join(res)\n", - "qa = ChatVectorDBChain.from_llm(OpenAI(temperature=0), vectorstore, get_chat_history=get_chat_history)" + "qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore, get_chat_history=get_chat_history)" ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 30, "id": "a3e33c0d", "metadata": {}, "outputs": [], @@ -559,7 +560,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 31, "id": "936dc62f", "metadata": {}, "outputs": [ @@ -569,7 +570,7 @@ "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, - "execution_count": 11, + "execution_count": 31, "metadata": {}, "output_type": "execute_result" } diff --git a/docs/modules/indexes/chain_examples/vector_db_qa.ipynb b/docs/modules/indexes/chain_examples/vector_db_qa.ipynb index 8510e331..e5a1b8f6 100644 --- a/docs/modules/indexes/chain_examples/vector_db_qa.ipynb +++ b/docs/modules/indexes/chain_examples/vector_db_qa.ipynb @@ -5,9 +5,9 @@ "id": "07c1e3b9", "metadata": {}, "source": [ - "# Vector DB Question/Answering\n", + "# Retrieval Question/Answering\n", "\n", - "This example showcases question answering over a vector database." + "This example showcases question answering over an index." ] }, { @@ -20,7 +20,8 @@ "from langchain.embeddings.openai import OpenAIEmbeddings\n", "from langchain.vectorstores import Chroma\n", "from langchain.text_splitter import CharacterTextSplitter\n", - "from langchain import OpenAI, VectorDBQA" + "from langchain.llms import OpenAI\n", + "from langchain.chains import RetrievalQA" ] }, { @@ -56,7 +57,7 @@ "metadata": {}, "outputs": [], "source": [ - "qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", vectorstore=docsearch)" + "qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", retriever=docsearch.as_retriever())" ] }, { @@ -68,7 +69,7 @@ { "data": { "text/plain": [ - "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice and federal public defender, from a family of public school educators and police officers, a consensus builder, and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" + "\" The president said that she is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support, from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, "execution_count": 4, @@ -87,7 +88,7 @@ "metadata": {}, "source": [ "## Chain Type\n", - "You can easily specify different chain types to load and use in the VectorDBQA chain. For a more detailed walkthrough of these types, please see [this notebook](question_answering.ipynb).\n", + "You can easily specify different chain types to load and use in the RetrievalQA chain. For a more detailed walkthrough of these types, please see [this notebook](question_answering.ipynb).\n", "\n", "There are two ways to load different chain types. First, you can specify the chain type argument in the `from_chain_type` method. This allows you to pass in the name of the chain type you want to use. For example, in the below we change the chain type to `map_reduce`." ] @@ -99,7 +100,7 @@ "metadata": {}, "outputs": [], "source": [ - "qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type=\"map_reduce\", vectorstore=docsearch)" + "qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"map_reduce\", retriever=docsearch.as_retriever())" ] }, { @@ -111,7 +112,7 @@ { "data": { "text/plain": [ - "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, from a family of public school educators and police officers, a consensus builder, and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" + "\" The president said that Judge Ketanji Brown Jackson is one of our nation's top legal minds, a former top litigator in private practice and a former federal public defender, from a family of public school educators and police officers, a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, "execution_count": 6, @@ -129,24 +130,24 @@ "id": "60368f38", "metadata": {}, "source": [ - "The above way allows you to really simply change the chain_type, but it does provide a ton of flexibility over parameters to that chain type. If you want to control those parameters, you can load the chain directly (as you did in [this notebook](question_answering.ipynb)) and then pass that directly to the the VectorDBQA chain with the `combine_documents_chain` parameter. For example:" + "The above way allows you to really simply change the chain_type, but it does provide a ton of flexibility over parameters to that chain type. If you want to control those parameters, you can load the chain directly (as you did in [this notebook](question_answering.ipynb)) and then pass that directly to the the RetrievalQA chain with the `combine_documents_chain` parameter. For example:" ] }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 9, "id": "7b403f0d", "metadata": {}, "outputs": [], "source": [ "from langchain.chains.question_answering import load_qa_chain\n", "qa_chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"stuff\")\n", - "qa = VectorDBQA(combine_documents_chain=qa_chain, vectorstore=docsearch)" + "qa = RetrievalQA(combine_documents_chain=qa_chain, retriever=docsearch.as_retriever())" ] }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 10, "id": "9e04a9ac", "metadata": {}, "outputs": [ @@ -156,7 +157,7 @@ "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, - "execution_count": 19, + "execution_count": 10, "metadata": {}, "output_type": "execute_result" } @@ -177,7 +178,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 11, "id": "a45232a2", "metadata": {}, "outputs": [], @@ -196,28 +197,28 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 13, "id": "9b5c8d1d", "metadata": {}, "outputs": [], "source": [ "chain_type_kwargs = {\"prompt\": PROMPT}\n", - "qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", vectorstore=docsearch, chain_type_kwargs=chain_type_kwargs)" + "qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", retriever=docsearch.as_retriever(), chain_type_kwargs=chain_type_kwargs)" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 14, "id": "26ee7671", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "\" Il Presidente ha detto che Ketanji Brown Jackson è uno dei pensatori legali più importanti del nostro Paese, che continuerà l'eccellente eredità di giustizia Breyer. È un ex principale litigante in pratica privata, un ex difensore federale pubblico e appartiene a una famiglia di insegnanti e poliziotti delle scuole pubbliche. È un costruttore di consenso che ha ricevuto un ampio supporto da parte di Fraternal Order of Police e giudici designati da democratici e repubblicani.\"" + "\" Il presidente ha detto che Ketanji Brown Jackson è una delle menti legali più importanti del paese, che continuerà l'eccellenza di Justice Breyer e che ha ricevuto un ampio sostegno, da Fraternal Order of Police a ex giudici nominati da democratici e repubblicani.\"" ] }, - "execution_count": 8, + "execution_count": 14, "metadata": {}, "output_type": "execute_result" } @@ -238,17 +239,17 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 15, "id": "af093aba", "metadata": {}, "outputs": [], "source": [ - "qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", vectorstore=docsearch, return_source_documents=True)" + "qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", retriever=docsearch.as_retriever(), return_source_documents=True)" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 16, "id": "eac11321", "metadata": {}, "outputs": [], @@ -259,17 +260,17 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 17, "id": "7d75945a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "\" The president said that Ketanji Brown Jackson is one of our nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.\"" + "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice and a former federal public defender from a family of public school educators and police officers, and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, - "execution_count": 10, + "execution_count": 17, "metadata": {}, "output_type": "execute_result" } @@ -280,20 +281,20 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 18, "id": "35b4f31f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "[Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd 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.', lookup_str='', metadata={}, lookup_index=0),\n", - " Document(page_content='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\\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \\n\\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \\n\\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \\n\\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \\n\\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', lookup_str='', metadata={}, lookup_index=0),\n", - " Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \\n\\nAs 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\\nWhile 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\\nAnd 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\\nSo tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \\n\\nFirst, beat the opioid epidemic.', lookup_str='', metadata={}, lookup_index=0),\n", - " Document(page_content='As I’ve told Xi Jinping, it is never a good bet to bet against the American people. \\n\\nWe’ll create good jobs for millions of Americans, modernizing roads, airports, ports, and waterways all across America. \\n\\nAnd we’ll do it all to withstand the devastating effects of the climate crisis and promote environmental justice. \\n\\nWe’ll build a national network of 500,000 electric vehicle charging stations, begin to replace poisonous lead pipes—so every child—and every American—has clean water to drink at home and at school, provide affordable high-speed internet for every American—urban, suburban, rural, and tribal communities. \\n\\n4,000 projects have already been announced. \\n\\nAnd tonight, I’m announcing that this year we will start fixing over 65,000 miles of highway and 1,500 bridges in disrepair. \\n\\nWhen we use taxpayer dollars to rebuild America – we are going to Buy American: buy American products to support American jobs.', lookup_str='', metadata={}, lookup_index=0)]" + "[Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd 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.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0),\n", + " Document(page_content='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\\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \\n\\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \\n\\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \\n\\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \\n\\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0),\n", + " Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \\n\\nAs 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\\nWhile 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\\nAnd 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\\nSo tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \\n\\nFirst, beat the opioid epidemic.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0),\n", + " Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \\n\\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \\n\\nThat ends on my watch. \\n\\nMedicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. \\n\\nWe’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. \\n\\nLet’s pass the Paycheck Fairness Act and paid leave. \\n\\nRaise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. \\n\\nLet’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0)]" ] }, - "execution_count": 11, + "execution_count": 18, "metadata": {}, "output_type": "execute_result" } diff --git a/docs/modules/indexes/chain_examples/vector_db_qa_with_sources.ipynb b/docs/modules/indexes/chain_examples/vector_db_qa_with_sources.ipynb index 580f502d..d921b794 100644 --- a/docs/modules/indexes/chain_examples/vector_db_qa_with_sources.ipynb +++ b/docs/modules/indexes/chain_examples/vector_db_qa_with_sources.ipynb @@ -5,9 +5,9 @@ "id": "efc5be67", "metadata": {}, "source": [ - "# VectorDB Question Answering with Sources\n", + "# Retrieval Question Answering with Sources\n", "\n", - "This notebook goes over how to do question-answering with sources over a vector database. It does this by using the `VectorDBQAWithSourcesChain`, which does the lookup of the documents from a vector database. " + "This notebook goes over how to do question-answering with sources over an Index. It does this by using the `RetrievalQAWithSourcesChain`, which does the lookup of the documents from an Index. " ] }, { @@ -41,7 +41,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 3, "id": "0e745d99", "metadata": {}, "outputs": [ @@ -50,8 +50,7 @@ "output_type": "stream", "text": [ "Running Chroma using direct local API.\n", - "Using DuckDB in-memory for database. Data will be transient.\n", - "Exiting: Cleaning up .chroma directory\n" + "Using DuckDB in-memory for database. Data will be transient.\n" ] } ], @@ -61,40 +60,40 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 4, "id": "8aa571ae", "metadata": {}, "outputs": [], "source": [ - "from langchain.chains import VectorDBQAWithSourcesChain" + "from langchain.chains import RetrievalQAWithSourcesChain" ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 5, "id": "aa859d4c", "metadata": {}, "outputs": [], "source": [ "from langchain import OpenAI\n", "\n", - "chain = VectorDBQAWithSourcesChain.from_chain_type(OpenAI(temperature=0), chain_type=\"stuff\", vectorstore=docsearch)" + "chain = RetrievalQAWithSourcesChain.from_chain_type(OpenAI(temperature=0), chain_type=\"stuff\", retriever=docsearch.as_retriever())" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 6, "id": "8ba36fa7", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "{'answer': ' The president thanked Justice Breyer for his service and mentioned his legacy of excellence.\\n',\n", - " 'sources': '30-pl'}" + "{'answer': ' The president honored Justice Breyer for his service and mentioned his legacy of excellence.\\n',\n", + " 'sources': '31-pl'}" ] }, - "execution_count": 8, + "execution_count": 6, "metadata": {}, "output_type": "execute_result" } @@ -109,35 +108,35 @@ "metadata": {}, "source": [ "## Chain Type\n", - "You can easily specify different chain types to load and use in the VectorDBQAWithSourcesChain chain. For a more detailed walkthrough of these types, please see [this notebook](qa_with_sources.ipynb).\n", + "You can easily specify different chain types to load and use in the RetrievalQAWithSourcesChain chain. For a more detailed walkthrough of these types, please see [this notebook](qa_with_sources.ipynb).\n", "\n", "There are two ways to load different chain types. First, you can specify the chain type argument in the `from_chain_type` method. This allows you to pass in the name of the chain type you want to use. For example, in the below we change the chain type to `map_reduce`." ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 7, "id": "8b35b30a", "metadata": {}, "outputs": [], "source": [ - "chain = VectorDBQAWithSourcesChain.from_chain_type(OpenAI(temperature=0), chain_type=\"map_reduce\", vectorstore=docsearch)" + "chain = RetrievalQAWithSourcesChain.from_chain_type(OpenAI(temperature=0), chain_type=\"map_reduce\", retriever=docsearch.as_retriever())" ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 8, "id": "58bd424f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "{'answer': ' The president honored Justice Stephen Breyer for his service.\\n',\n", - " 'sources': '30-pl'}" + "{'answer': ' The president said \"Justice Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.\"\\n',\n", + " 'sources': '31-pl'}" ] }, - "execution_count": 9, + "execution_count": 8, "metadata": {}, "output_type": "execute_result" } @@ -151,19 +150,19 @@ "id": "21e14eed", "metadata": {}, "source": [ - "The above way allows you to really simply change the chain_type, but it does provide a ton of flexibility over parameters to that chain type. If you want to control those parameters, you can load the chain directly (as you did in [this notebook](qa_with_sources.ipynb)) and then pass that directly to the the VectorDBQA chain with the `combine_documents_chain` parameter. For example:" + "The above way allows you to really simply change the chain_type, but it does provide a ton of flexibility over parameters to that chain type. If you want to control those parameters, you can load the chain directly (as you did in [this notebook](qa_with_sources.ipynb)) and then pass that directly to the the RetrievalQAWithSourcesChain chain with the `combine_documents_chain` parameter. For example:" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 10, "id": "af35f0c6", "metadata": {}, "outputs": [], "source": [ "from langchain.chains.qa_with_sources import load_qa_with_sources_chain\n", "qa_chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"stuff\")\n", - "qa = VectorDBQAWithSourcesChain(combine_documents_chain=qa_chain, vectorstore=docsearch)" + "qa = RetrievalQAWithSourcesChain(combine_documents_chain=qa_chain, retriever=docsearch.as_retriever())" ] }, { @@ -175,8 +174,8 @@ { "data": { "text/plain": [ - "{'answer': ' The president honored Justice Stephen Breyer for his service.\\n',\n", - " 'sources': '30-pl'}" + "{'answer': ' The president honored Justice Breyer for his service and mentioned his legacy of excellence.\\n',\n", + " 'sources': '31-pl'}" ] }, "execution_count": 11, @@ -187,6 +186,14 @@ "source": [ "qa({\"question\": \"What did the president say about Justice Breyer\"}, return_only_outputs=True)" ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3c594296", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { diff --git a/docs/modules/indexes/getting_started.ipynb b/docs/modules/indexes/getting_started.ipynb index def30575..7d8fe465 100644 --- a/docs/modules/indexes/getting_started.ipynb +++ b/docs/modules/indexes/getting_started.ipynb @@ -1,12 +1,56 @@ { "cells": [ + { + "cell_type": "markdown", + "id": "fcc8bb1c", + "metadata": {}, + "source": [ + "# Getting Started\n", + "\n", + "LangChain primary focuses on constructing indexes with the goal of using them as a Retriever. In order to best understand what this means, it's worth highlighting what the base Retriever interface is. The `BaseRetriever` class in LangChain is as follows:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "b09ac324", + "metadata": {}, + "outputs": [], + "source": [ + "from abc import ABC, abstractmethod\n", + "from typing import List\n", + "from langchain.schema import Document\n", + "\n", + "class BaseRetriever(ABC):\n", + " @abstractmethod\n", + " def get_relevant_documents(self, query: str) -> List[Document]:\n", + " \"\"\"Get texts relevant for a query.\n", + "\n", + " Args:\n", + " query: string to find relevant tests for\n", + "\n", + " Returns:\n", + " List of relevant documents\n", + " \"\"\"" + ] + }, + { + "cell_type": "markdown", + "id": "e19d4adb", + "metadata": {}, + "source": [ + "It's that simple! The `get_relevant_documents` method can be implemented however you see fit.\n", + "\n", + "Of course, we also help construct what we think useful Retrievers are. The main type of Retriever that we focus on is a Vectorstore retriever. We will focus on that for the rest of this guide.\n", + "\n", + "In order to understand what a vectorstore retriever is, it's important to understand what a Vectorstore is. So let's look at that." + ] + }, { "cell_type": "markdown", "id": "2244801b", "metadata": {}, "source": [ - "# Getting Started\n", - "\n", "By default, LangChain uses [Chroma](../../ecosystem/chroma.md) as the vectorstore to index and search embeddings. To walk through this tutorial, we'll first need to install `chromadb`.\n", "\n", "```\n", @@ -16,11 +60,12 @@ "This example showcases question answering over documents.\n", "We have chosen this as the example for getting started because it nicely combines a lot of different elements (Text splitters, embeddings, vectorstores) and then also shows how to use them in a chain.\n", "\n", - "Question answering over documents consists of three steps:\n", + "Question answering over documents consists of four steps:\n", "\n", "1. Create an index\n", - "2. Create a question answering chain\n", - "3. Ask questions!\n", + "2. Create a Retriever from that index\n", + "3. Create a question answering chain\n", + "4. Ask questions!\n", "\n", "Each of the steps has multiple sub steps and potential configurations. In this notebook we will primarily focus on (1). We will start by showing the one-liner for doing so, but then break down what is actually going on.\n", "\n", @@ -29,12 +74,12 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 3, "id": "8d369452", "metadata": {}, "outputs": [], "source": [ - "from langchain.chains import VectorDBQA\n", + "from langchain.chains import RetrievalQA\n", "from langchain.llms import OpenAI" ] }, @@ -48,7 +93,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 4, "id": "33958a86", "metadata": {}, "outputs": [], @@ -69,7 +114,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 5, "id": "403fc231", "metadata": {}, "outputs": [], @@ -79,7 +124,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 6, "id": "57a8a199", "metadata": {}, "outputs": [ @@ -106,7 +151,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 7, "id": "23d0d234", "metadata": {}, "outputs": [ @@ -116,7 +161,7 @@ "\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\"" ] }, - "execution_count": 5, + "execution_count": 7, "metadata": {}, "output_type": "execute_result" } @@ -128,7 +173,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 8, "id": "ae46b239", "metadata": {}, "outputs": [ @@ -140,7 +185,7 @@ " 'sources': '../state_of_the_union.txt'}" ] }, - "execution_count": 6, + "execution_count": 8, "metadata": {}, "output_type": "execute_result" } @@ -160,17 +205,17 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 9, "id": "b04f3c10", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "" + "" ] }, - "execution_count": 7, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } @@ -179,6 +224,35 @@ "index.vectorstore" ] }, + { + "cell_type": "markdown", + "id": "297ccfa4", + "metadata": {}, + "source": [ + "If we then want to access the VectorstoreRetriever, we can do that with:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "b8fef77d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "VectorStoreRetriever(vectorstore=, search_kwargs={})" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "index.vectorstore.as_retriever()" + ] + }, { "cell_type": "markdown", "id": "2cb6d2eb", @@ -201,7 +275,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 11, "id": "54270abc", "metadata": {}, "outputs": [], @@ -219,7 +293,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 12, "id": "afecb8cf", "metadata": {}, "outputs": [], @@ -239,7 +313,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 13, "id": "9eaaa735", "metadata": {}, "outputs": [], @@ -258,7 +332,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 14, "id": "5c7049db", "metadata": {}, "outputs": [ @@ -276,38 +350,55 @@ "db = Chroma.from_documents(texts, embeddings)" ] }, + { + "cell_type": "markdown", + "id": "f0ef85a6", + "metadata": {}, + "source": [ + "So that's creating the index. Then, we expose this index in a retriever interface." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "13495c77", + "metadata": {}, + "outputs": [], + "source": [ + "retriever = db.as_retriever()" + ] + }, { "cell_type": "markdown", "id": "30c4e5c6", "metadata": {}, "source": [ - "So that's creating the index.\n", "Then, as before, we create a chain and use it to answer questions!" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 16, "id": "3018f865", "metadata": {}, "outputs": [], "source": [ - "qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", vectorstore=db)" + "qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", retriever=retriever)" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 17, "id": "032a47f8", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "\" The President said that Ketanji Brown Jackson is one of the nation's top legal minds and a consensus builder, with a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. She is a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers.\"" + "\" The President said that Judge Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He said she is a consensus builder and has received a broad range of support from organizations such as the Fraternal Order of Police and former judges appointed by Democrats and Republicans.\"" ] }, - "execution_count": 13, + "execution_count": 17, "metadata": {}, "output_type": "execute_result" } @@ -372,7 +463,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.9" + "version": "3.9.1" }, "vscode": { "interpreter": { diff --git a/docs/modules/indexes/how_to_guides.rst b/docs/modules/indexes/how_to_guides.rst index bd81adbc..e9eb56aa 100644 --- a/docs/modules/indexes/how_to_guides.rst +++ b/docs/modules/indexes/how_to_guides.rst @@ -72,9 +72,11 @@ Retrievers The retriever interface is a generic interface that makes it easy to combine documents with -language models. This interface exposes a `get_relevant_texts` method which takes in a query +language models. This interface exposes a `get_relevant_documents` method which takes in a query (a string) and returns a list of documents. +`Vectorstore Retriever <./retriever_examples/vectorstore-retriever.html>`_: A walkthrough of how to use a VectorStore as a Retriever. + `ChatGPT Plugin Retriever <./retriever_examples/chatgpt-plugin-retriever.html>`_: A walkthrough of how to use the ChatGPT Plugin Retriever within the LangChain framework. diff --git a/docs/modules/indexes/retriever_examples/chatgpt-plugin-retriever.ipynb b/docs/modules/indexes/retriever_examples/chatgpt-plugin-retriever.ipynb index ffcd1669..9b324b15 100644 --- a/docs/modules/indexes/retriever_examples/chatgpt-plugin-retriever.ipynb +++ b/docs/modules/indexes/retriever_examples/chatgpt-plugin-retriever.ipynb @@ -52,7 +52,7 @@ } ], "source": [ - "retriever.get_relevant_texts(\"alice's phone number\")" + "retriever.get_relevant_documents(\"alice's phone number\")" ] }, { diff --git a/docs/modules/indexes/retriever_examples/vectorstore-retriever.ipynb b/docs/modules/indexes/retriever_examples/vectorstore-retriever.ipynb new file mode 100644 index 00000000..ca03103e --- /dev/null +++ b/docs/modules/indexes/retriever_examples/vectorstore-retriever.ipynb @@ -0,0 +1,93 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "fc0db1bc", + "metadata": {}, + "source": [ + "# VectorStore Retriever\n", + "\n", + "The index - and therefor the retriever - that LangChain has the most support for is a VectorStoreRetriever. As the name suggests, this retriever is backed heavily by a VectorStore.\n", + "\n", + "Once you construct a VectorStore, its very easy to construct a retriever. Let's walk through an example." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "5831703b", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.document_loaders import TextLoader\n", + "loader = TextLoader('../../state_of_the_union.txt')" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "9fbcc58f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Running Chroma using direct local API.\n", + "Using DuckDB in-memory for database. Data will be transient.\n" + ] + } + ], + "source": [ + "from langchain.text_splitter import CharacterTextSplitter\n", + "from langchain.vectorstores import Chroma\n", + "from langchain.embeddings import OpenAIEmbeddings\n", + "\n", + "documents = loader.load()\n", + "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n", + "texts = text_splitter.split_documents(documents)\n", + "embeddings = OpenAIEmbeddings()\n", + "db = Chroma.from_documents(texts, embeddings)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "0cbfb1af", + "metadata": {}, + "outputs": [], + "source": [ + "retriever = db.as_retriever()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fc12700b", + "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/docs/use_cases/evaluation.rst b/docs/use_cases/evaluation.rst index effc10bd..49c53b55 100644 --- a/docs/use_cases/evaluation.rst +++ b/docs/use_cases/evaluation.rst @@ -83,7 +83,7 @@ In addition, we also have some more generic resources for evaluation. `Question Answering <./evaluation/question_answering.html>`_: An overview of LLMs aimed at evaluating question answering systems in general. -`Data Augmented Question Answering <./evaluation/data_augmented_question_answering.html>`_: An end-to-end example of evaluating a question answering system focused on a specific document (a VectorDBQAChain to be precise). This example highlights how to use LLMs to come up with question/answer examples to evaluate over, and then highlights how to use LLMs to evaluate performance on those generated examples. +`Data Augmented Question Answering <./evaluation/data_augmented_question_answering.html>`_: An end-to-end example of evaluating a question answering system focused on a specific document (a RetrievalQAChain to be precise). This example highlights how to use LLMs to come up with question/answer examples to evaluate over, and then highlights how to use LLMs to evaluate performance on those generated examples. `Hugging Face Datasets <./evaluation/huggingface_datasets.html>`_: Covers an example of loading and using a dataset from Hugging Face for evaluation. diff --git a/docs/use_cases/evaluation/agent_vectordb_sota_pg.ipynb b/docs/use_cases/evaluation/agent_vectordb_sota_pg.ipynb index 954dc775..45861e99 100644 --- a/docs/use_cases/evaluation/agent_vectordb_sota_pg.ipynb +++ b/docs/use_cases/evaluation/agent_vectordb_sota_pg.ipynb @@ -14,7 +14,7 @@ }, { "cell_type": "code", - "execution_count": 47, + "execution_count": 1, "id": "7b57a50f", "metadata": {}, "outputs": [], @@ -35,7 +35,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 2, "id": "5b2d5e98", "metadata": {}, "outputs": [ @@ -49,7 +49,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "a7abbc20615d4c58b75a055a790d7212", + "model_id": "4c389519842e4b65afc33006a531dcbc", "version_major": 2, "version_minor": 0 }, @@ -68,7 +68,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 3, "id": "61375342", "metadata": {}, "outputs": [ @@ -81,7 +81,7 @@ " {'tool': None, 'tool_input': 'What is the purpose of the NATO Alliance?'}]}" ] }, - "execution_count": 16, + "execution_count": 3, "metadata": {}, "output_type": "execute_result" } @@ -92,7 +92,7 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 4, "id": "02500304", "metadata": {}, "outputs": [ @@ -105,7 +105,7 @@ " {'tool': None, 'tool_input': 'What is the purpose of YC?'}]}" ] }, - "execution_count": 22, + "execution_count": 4, "metadata": {}, "output_type": "execute_result" } @@ -125,7 +125,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 5, "id": "c18680b5", "metadata": {}, "outputs": [], @@ -136,7 +136,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 6, "id": "7f0de2b3", "metadata": {}, "outputs": [], @@ -146,7 +146,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 7, "id": "ef84ff99", "metadata": {}, "outputs": [ @@ -173,23 +173,23 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 8, "id": "8843cb0c", "metadata": {}, "outputs": [], "source": [ - "from langchain.chains import VectorDBQA\n", + "from langchain.chains import RetrievalQA\n", "from langchain.llms import OpenAI" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 9, "id": "573719a0", "metadata": {}, "outputs": [], "source": [ - "chain_sota = VectorDBQA.from_chain_type(llm=OpenAI(temperature=0), chain_type=\"stuff\", vectorstore=vectorstore_sota, input_key=\"question\")" + "chain_sota = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), chain_type=\"stuff\", retriever=vectorstore_sota, input_key=\"question\")\n" ] }, { @@ -202,7 +202,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 10, "id": "c2dbb014", "metadata": {}, "outputs": [], @@ -212,7 +212,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 11, "id": "98d16f08", "metadata": {}, "outputs": [ @@ -231,12 +231,12 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 12, "id": "ec0aab02", "metadata": {}, "outputs": [], "source": [ - "chain_pg = VectorDBQA.from_chain_type(llm=OpenAI(temperature=0), chain_type=\"stuff\", vectorstore=vectorstore_pg, input_key=\"question\")\n" + "chain_pg = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), chain_type=\"stuff\", retriever=vectorstore_pg, input_key=\"question\")\n" ] }, { @@ -249,7 +249,7 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 13, "id": "ade1aafa", "metadata": {}, "outputs": [], @@ -271,7 +271,7 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": 14, "id": "104853f8", "metadata": {}, "outputs": [], @@ -291,7 +291,7 @@ }, { "cell_type": "code", - "execution_count": 48, + "execution_count": 15, "id": "4664e79f", "metadata": {}, "outputs": [ @@ -301,7 +301,7 @@ "'The purpose of the NATO Alliance is to promote peace and security in the North Atlantic region by providing a collective defense against potential threats.'" ] }, - "execution_count": 48, + "execution_count": 15, "metadata": {}, "output_type": "execute_result" } @@ -321,8 +321,8 @@ }, { "cell_type": "code", - "execution_count": 35, - "id": "24b4c66e", + "execution_count": null, + "id": "799f6c17", "metadata": {}, "outputs": [], "source": [ @@ -349,23 +349,10 @@ }, { "cell_type": "code", - "execution_count": 36, + "execution_count": null, "id": "1d583f03", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'input': 'What is the purpose of the NATO Alliance?',\n", - " 'answer': 'The purpose of the NATO Alliance is to secure peace and stability in Europe after World War 2.',\n", - " 'output': 'The purpose of the NATO Alliance is to promote peace and security in the North Atlantic region by providing a collective defense against potential threats.'}" - ] - }, - "execution_count": 36, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "predictions[0]" ] @@ -380,7 +367,7 @@ }, { "cell_type": "code", - "execution_count": 37, + "execution_count": null, "id": "d0a9341d", "metadata": {}, "outputs": [], diff --git a/docs/use_cases/evaluation/data_augmented_question_answering.ipynb b/docs/use_cases/evaluation/data_augmented_question_answering.ipynb index 6d841e42..7c2b41ff 100644 --- a/docs/use_cases/evaluation/data_augmented_question_answering.ipynb +++ b/docs/use_cases/evaluation/data_augmented_question_answering.ipynb @@ -23,7 +23,8 @@ "from langchain.embeddings.openai import OpenAIEmbeddings\n", "from langchain.vectorstores import Chroma\n", "from langchain.text_splitter import CharacterTextSplitter\n", - "from langchain import OpenAI, VectorDBQA" + "from langchain.llms import OpenAI\n", + "from langchain.chains import RetrievalQA" ] }, { @@ -50,7 +51,7 @@ "\n", "embeddings = OpenAIEmbeddings()\n", "docsearch = Chroma.from_documents(texts, embeddings)\n", - "qa = VectorDBQA.from_llm(llm=OpenAI(), vectorstore=docsearch)" + "qa = RetrievalQA.from_llm(llm=OpenAI(), retriever=docsearch.as_retriever())" ] }, { @@ -434,7 +435,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.9" + "version": "3.9.1" } }, "nbformat": 4, diff --git a/docs/use_cases/evaluation/qa_benchmarking_pg.ipynb b/docs/use_cases/evaluation/qa_benchmarking_pg.ipynb index 7491c6ec..0ea12e74 100644 --- a/docs/use_cases/evaluation/qa_benchmarking_pg.ipynb +++ b/docs/use_cases/evaluation/qa_benchmarking_pg.ipynb @@ -14,7 +14,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 1, "id": "3bd13ab7", "metadata": {}, "outputs": [], @@ -35,7 +35,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 2, "id": "5b2d5e98", "metadata": {}, "outputs": [ @@ -49,7 +49,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "63f434a42cba4739919333c75324acc9", + "model_id": "9264acfe710b4faabf060f0fcf4f7308", "version_major": 2, "version_minor": 0 }, @@ -77,7 +77,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 3, "id": "c18680b5", "metadata": {}, "outputs": [], @@ -88,7 +88,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 4, "id": "7f0de2b3", "metadata": {}, "outputs": [], @@ -98,7 +98,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 5, "id": "ef84ff99", "metadata": {}, "outputs": [ @@ -125,23 +125,23 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 6, "id": "8843cb0c", "metadata": {}, "outputs": [], "source": [ - "from langchain.chains import VectorDBQA\n", + "from langchain.chains import RetrievalQA\n", "from langchain.llms import OpenAI" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 7, "id": "573719a0", "metadata": {}, "outputs": [], "source": [ - "chain = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", vectorstore=vectorstore, input_key=\"question\")" + "chain = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"stuff\", retriever=vectorstore.as_retriever(), input_key=\"question\")" ] }, { diff --git a/docs/use_cases/evaluation/qa_benchmarking_sota.ipynb b/docs/use_cases/evaluation/qa_benchmarking_sota.ipynb index 11666405..078f3433 100644 --- a/docs/use_cases/evaluation/qa_benchmarking_sota.ipynb +++ b/docs/use_cases/evaluation/qa_benchmarking_sota.ipynb @@ -14,7 +14,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 1, "id": "f127fb04", "metadata": {}, "outputs": [], @@ -35,73 +35,17 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 2, "id": "5b2d5e98", "metadata": {}, "outputs": [ { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "5d66c27b9b4744989843142f08f5c1b4", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Downloading readme: 0%| | 0.00/21.0 [00:00 List[Document]: - return self.retriever.get_relevant_texts(question) + return self.retriever.get_relevant_documents(question) @classmethod def from_llm( @@ -155,6 +156,14 @@ class ChatVectorDBChain(BaseConversationalRetrievalChain, BaseModel): def _chain_type(self) -> str: return "chat-vector-db" + @root_validator() + def raise_deprecation(cls, values: Dict) -> Dict: + warnings.warn( + "`ChatVectorDBChain` is deprecated - " + "please use `from langchain.chains import ConversationalRetrievalChain`" + ) + return values + def _get_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]: vectordbkwargs = inputs.get("vectordbkwargs", {}) full_kwargs = {**self.search_kwargs, **vectordbkwargs} diff --git a/langchain/chains/qa_with_sources/retrieval.py b/langchain/chains/qa_with_sources/retrieval.py index 1f50b28a..c9e90722 100644 --- a/langchain/chains/qa_with_sources/retrieval.py +++ b/langchain/chains/qa_with_sources/retrieval.py @@ -42,5 +42,5 @@ class RetrievalQAWithSourcesChain(BaseQAWithSourcesChain, BaseModel): def _get_docs(self, inputs: Dict[str, Any]) -> List[Document]: question = inputs[self.question_key] - docs = self.retriever.get_relevant_texts(question) + docs = self.retriever.get_relevant_documents(question) return self._reduce_tokens_below_limit(docs) diff --git a/langchain/chains/qa_with_sources/vector_db.py b/langchain/chains/qa_with_sources/vector_db.py index 8a567dfa..5f95d8c1 100644 --- a/langchain/chains/qa_with_sources/vector_db.py +++ b/langchain/chains/qa_with_sources/vector_db.py @@ -1,8 +1,9 @@ """Question-answering with sources over a vector database.""" +import warnings from typing import Any, Dict, List -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, root_validator from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.qa_with_sources.base import BaseQAWithSourcesChain @@ -51,6 +52,14 @@ class VectorDBQAWithSourcesChain(BaseQAWithSourcesChain, BaseModel): ) return self._reduce_tokens_below_limit(docs) + @root_validator() + def raise_deprecation(cls, values: Dict) -> Dict: + warnings.warn( + "`VectorDBQAWithSourcesChain` is deprecated - " + "please use `from langchain.chains import RetrievalQAWithSourcesChain`" + ) + return values + @property def _chain_type(self) -> str: return "vector_db_qa_with_sources_chain" diff --git a/langchain/chains/retrieval_qa/base.py b/langchain/chains/retrieval_qa/base.py index c1543da8..40ad34d4 100644 --- a/langchain/chains/retrieval_qa/base.py +++ b/langchain/chains/retrieval_qa/base.py @@ -1,6 +1,7 @@ """Chain for question-answering against a vector database.""" from __future__ import annotations +import warnings from abc import abstractmethod from typing import Any, Dict, List, Optional @@ -131,7 +132,7 @@ class RetrievalQA(BaseRetrievalQA, BaseModel): retriever: BaseRetriever = Field(exclude=True) def _get_docs(self, question: str) -> List[Document]: - return self.retriever.get_relevant_texts(question) + return self.retriever.get_relevant_documents(question) class VectorDBQA(BaseRetrievalQA, BaseModel): @@ -146,6 +147,14 @@ class VectorDBQA(BaseRetrievalQA, BaseModel): search_kwargs: Dict[str, Any] = Field(default_factory=dict) """Extra search args.""" + @root_validator() + def raise_deprecation(cls, values: Dict) -> Dict: + warnings.warn( + "`VectorDBQA` is deprecated - " + "please use `from langchain.chains import RetrievalQA`" + ) + return values + @root_validator() def validate_search_type(cls, values: Dict) -> Dict: """Validate search type.""" diff --git a/langchain/retrievers/chatgpt_plugin_retriever.py b/langchain/retrievers/chatgpt_plugin_retriever.py index 11205895..610a79a2 100644 --- a/langchain/retrievers/chatgpt_plugin_retriever.py +++ b/langchain/retrievers/chatgpt_plugin_retriever.py @@ -10,7 +10,7 @@ class ChatGPTPluginRetriever(BaseRetriever, BaseModel): url: str bearer_token: str - def get_relevant_texts(self, query: str) -> List[Document]: + def get_relevant_documents(self, query: str) -> List[Document]: response = requests.post( f"{self.url}/query", json={"queries": [{"query": query}]}, diff --git a/langchain/schema.py b/langchain/schema.py index 087b81e0..eb7d4ff3 100644 --- a/langchain/schema.py +++ b/langchain/schema.py @@ -277,11 +277,11 @@ class Document(BaseModel): class BaseRetriever(ABC): @abstractmethod - def get_relevant_texts(self, query: str) -> List[Document]: - """Get texts relevant for a query. + def get_relevant_documents(self, query: str) -> List[Document]: + """Get documents relevant for a query. Args: - query: string to find relevant tests for + query: string to find relevant documents for Returns: List of relevant documents diff --git a/langchain/vectorstores/base.py b/langchain/vectorstores/base.py index 60f4d1e0..9e80b3d5 100644 --- a/langchain/vectorstores/base.py +++ b/langchain/vectorstores/base.py @@ -2,9 +2,9 @@ from __future__ import annotations from abc import ABC, abstractmethod -from typing import Any, Iterable, List, Optional +from typing import Any, Dict, Iterable, List, Optional -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, root_validator from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings @@ -132,6 +132,7 @@ class VectorStore(ABC): class VectorStoreRetriever(BaseRetriever, BaseModel): vectorstore: VectorStore + search_type: str = "similarity" search_kwargs: dict = Field(default_factory=dict) class Config: @@ -139,5 +140,22 @@ class VectorStoreRetriever(BaseRetriever, BaseModel): arbitrary_types_allowed = True - def get_relevant_texts(self, query: str) -> List[Document]: - return self.vectorstore.similarity_search(query, **self.search_kwargs) + @root_validator() + def validate_search_type(cls, values: Dict) -> Dict: + """Validate search type.""" + if "search_type" in values: + search_type = values["search_type"] + if search_type not in ("similarity", "mmr"): + raise ValueError(f"search_type of {search_type} not allowed.") + return values + + def get_relevant_documents(self, query: str) -> List[Document]: + if self.search_type == "similarity": + docs = self.vectorstore.similarity_search(query, **self.search_kwargs) + elif self.search_type == "mmr": + docs = self.vectorstore.max_marginal_relevance_search( + query, **self.search_kwargs + ) + else: + raise ValueError(f"search_type of {self.search_type} not allowed.") + return docs