mirror of
https://github.com/hwchase17/langchain.git
synced 2025-06-24 07:35:18 +00:00
Update landing page for "question answering over documents" (#7152)
Improve documentation for a central use-case, qa / chat over documents. This will be merged as an update to `index.mdx` [here](https://python.langchain.com/docs/use_cases/question_answering/). Testing w/ local Docusaurus server: ``` From `docs` directory: mkdir _dist cp -r {docs_skeleton,snippets} _dist cp -r extras/* _dist/docs_skeleton/docs cd _dist/docs_skeleton yarn install yarn start ``` --------- Co-authored-by: Bagatur <baskaryan@gmail.com>
This commit is contained in:
parent
dd648183fa
commit
28d2b213a4
BIN
docs/docs_skeleton/static/img/qa_data_load.png
Normal file
BIN
docs/docs_skeleton/static/img/qa_data_load.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 237 KiB |
BIN
docs/docs_skeleton/static/img/qa_flow.jpeg
Normal file
BIN
docs/docs_skeleton/static/img/qa_flow.jpeg
Normal file
Binary file not shown.
After Width: | Height: | Size: 173 KiB |
BIN
docs/docs_skeleton/static/img/qa_intro.png
Normal file
BIN
docs/docs_skeleton/static/img/qa_intro.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 164 KiB |
BIN
docs/docs_skeleton/static/img/summary_chains.png
Normal file
BIN
docs/docs_skeleton/static/img/summary_chains.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 118 KiB |
@ -60,7 +60,8 @@
|
|||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"collapsed": false
|
"collapsed": false
|
||||||
}
|
},
|
||||||
|
"id": "7af596b5"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
@ -150,20 +151,20 @@
|
|||||||
"text": [
|
"text": [
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\u001B[1m> Entering new GraphSparqlQAChain chain...\u001B[0m\n",
|
"\u001b[1m> Entering new GraphSparqlQAChain chain...\u001b[0m\n",
|
||||||
"Identified intent:\n",
|
"Identified intent:\n",
|
||||||
"\u001B[32;1m\u001B[1;3mSELECT\u001B[0m\n",
|
"\u001b[32;1m\u001b[1;3mSELECT\u001b[0m\n",
|
||||||
"Generated SPARQL:\n",
|
"Generated SPARQL:\n",
|
||||||
"\u001B[32;1m\u001B[1;3mPREFIX foaf: <http://xmlns.com/foaf/0.1/>\n",
|
"\u001b[32;1m\u001b[1;3mPREFIX foaf: <http://xmlns.com/foaf/0.1/>\n",
|
||||||
"SELECT ?homepage\n",
|
"SELECT ?homepage\n",
|
||||||
"WHERE {\n",
|
"WHERE {\n",
|
||||||
" ?person foaf:name \"Tim Berners-Lee\" .\n",
|
" ?person foaf:name \"Tim Berners-Lee\" .\n",
|
||||||
" ?person foaf:workplaceHomepage ?homepage .\n",
|
" ?person foaf:workplaceHomepage ?homepage .\n",
|
||||||
"}\u001B[0m\n",
|
"}\u001b[0m\n",
|
||||||
"Full Context:\n",
|
"Full Context:\n",
|
||||||
"\u001B[32;1m\u001B[1;3m[]\u001B[0m\n",
|
"\u001b[32;1m\u001b[1;3m[]\u001b[0m\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\u001B[1m> Finished chain.\u001B[0m\n"
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -207,19 +208,19 @@
|
|||||||
"text": [
|
"text": [
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\u001B[1m> Entering new GraphSparqlQAChain chain...\u001B[0m\n",
|
"\u001b[1m> Entering new GraphSparqlQAChain chain...\u001b[0m\n",
|
||||||
"Identified intent:\n",
|
"Identified intent:\n",
|
||||||
"\u001B[32;1m\u001B[1;3mUPDATE\u001B[0m\n",
|
"\u001b[32;1m\u001b[1;3mUPDATE\u001b[0m\n",
|
||||||
"Generated SPARQL:\n",
|
"Generated SPARQL:\n",
|
||||||
"\u001B[32;1m\u001B[1;3mPREFIX foaf: <http://xmlns.com/foaf/0.1/>\n",
|
"\u001b[32;1m\u001b[1;3mPREFIX foaf: <http://xmlns.com/foaf/0.1/>\n",
|
||||||
"INSERT {\n",
|
"INSERT {\n",
|
||||||
" ?person foaf:workplaceHomepage <http://www.w3.org/foo/bar/> .\n",
|
" ?person foaf:workplaceHomepage <http://www.w3.org/foo/bar/> .\n",
|
||||||
"}\n",
|
"}\n",
|
||||||
"WHERE {\n",
|
"WHERE {\n",
|
||||||
" ?person foaf:name \"Timothy Berners-Lee\" .\n",
|
" ?person foaf:name \"Timothy Berners-Lee\" .\n",
|
||||||
"}\u001B[0m\n",
|
"}\u001b[0m\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\u001B[1m> Finished chain.\u001B[0m\n"
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
File diff suppressed because one or more lines are too long
@ -54,7 +54,7 @@
|
|||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
"output_type": "stream",
|
"output_type": "stream",
|
||||||
"text": [
|
"text": [
|
||||||
"OpenAI API Key: ········\n"
|
"OpenAI API Key: \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@ -336,13 +336,13 @@
|
|||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
"output_type": "stream",
|
"output_type": "stream",
|
||||||
"text": [
|
"text": [
|
||||||
"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",
|
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you\u2019re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"Tonight, 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",
|
"Tonight, I\u2019d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer\u2014an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||||||
"\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"
|
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation\u2019s top legal minds, who will continue Justice Breyer\u2019s legacy of excellence.\n"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@ -393,13 +393,13 @@
|
|||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
"output_type": "stream",
|
"output_type": "stream",
|
||||||
"text": [
|
"text": [
|
||||||
"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",
|
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you\u2019re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"Tonight, 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",
|
"Tonight, I\u2019d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer\u2014an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||||||
"\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",
|
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation\u2019s top legal minds, who will continue Justice Breyer\u2019s legacy of excellence.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Score: 0.8153784913324512\n"
|
"Score: 0.8153784913324512\n"
|
||||||
]
|
]
|
||||||
@ -483,15 +483,15 @@
|
|||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
"output_type": "stream",
|
"output_type": "stream",
|
||||||
"text": [
|
"text": [
|
||||||
"1. 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",
|
"1. Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you\u2019re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"Tonight, 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",
|
"Tonight, I\u2019d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer\u2014an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||||||
"\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",
|
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation\u2019s top legal minds, who will continue Justice Breyer\u2019s legacy of excellence. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"2. We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n",
|
"2. We can\u2019t change how divided we\u2019ve been. But we can change how we move forward\u2014on COVID-19 and other issues we must face together. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n",
|
"I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n",
|
||||||
"\n",
|
"\n",
|
||||||
@ -501,13 +501,13 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"Officer Rivera was 22. \n",
|
"Officer Rivera was 22. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n",
|
"Both Dominican Americans who\u2019d grown up on the same streets they later chose to patrol as police officers. \n",
|
||||||
"\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",
|
"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",
|
"\n",
|
||||||
"I’ve worked on these issues a long time. \n",
|
"I\u2019ve worked on these issues a long time. \n",
|
||||||
"\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",
|
"I know what works: Investing in crime preventionand community police officers who\u2019ll walk the beat, who\u2019ll know the neighborhood, and who can restore trust and safety. \n",
|
||||||
"\n"
|
"\n"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@ -605,7 +605,7 @@
|
|||||||
{
|
{
|
||||||
"data": {
|
"data": {
|
||||||
"text/plain": [
|
"text/plain": [
|
||||||
"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.', metadata={'source': '../../../state_of_the_union.txt'})"
|
"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\u2019re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I\u2019d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer\u2014an 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\u2019s top legal minds, who will continue Justice Breyer\u2019s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'})"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"execution_count": 17,
|
"execution_count": 17,
|
||||||
@ -648,7 +648,8 @@
|
|||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"collapsed": false
|
"collapsed": false
|
||||||
}
|
},
|
||||||
|
"id": "3166ff99"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
@ -657,7 +658,8 @@
|
|||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"collapsed": false
|
"collapsed": false
|
||||||
}
|
},
|
||||||
|
"id": "79848e80"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
@ -681,7 +683,8 @@
|
|||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"collapsed": false
|
"collapsed": false
|
||||||
}
|
},
|
||||||
|
"id": "daeafd6d"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
|
@ -1,85 +1,446 @@
|
|||||||
# Question answering over documents
|
# QA and Chat over Documents
|
||||||
|
|
||||||
Question answering in this context refers to question answering over your document data.
|
Chat and Question-Answering (QA) over `data` are popular LLM use-cases.
|
||||||
For question answering over other types of data, please see other sources documentation like [SQL database Question Answering](/docs/use_cases/tabular.html) or [Interacting with APIs](/docs/use_cases/apis.html).
|
|
||||||
|
|
||||||
For question answering over many documents, you almost always want to create an index over the data.
|
`data` can include many things, including:
|
||||||
This can be used to smartly access the most relevant documents for a given question, allowing you to avoid having to pass all the documents to the LLM (saving you time and money).
|
|
||||||
|
* `Unstructured data` (e.g., PDFs)
|
||||||
|
* `Structured data` (e.g., SQL)
|
||||||
|
* `Code` (e.g., Python)
|
||||||
|
|
||||||
|
LangChain supports Chat and QA on various `data` types:
|
||||||
|
|
||||||
|
* See [here](https://python.langchain.com/docs/use_cases/code/) and [here](https://twitter.com/cristobal_dev/status/1675745314592915456?s=20) for `Code`
|
||||||
|
* See [here](https://python.langchain.com/docs/use_cases/tabular) for `Structured data`
|
||||||
|
|
||||||
|
Below we will review Chat and QA on `Unstructured data`.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
`Unstructured data` can be loaded from many sources.
|
||||||
|
|
||||||
|
Use the [LangChain integration hub](https://integrations.langchain.com/) to browse the full set of loaders.
|
||||||
|
|
||||||
|
Each loader returns data as a LangChain [`Document`](https://docs.langchain.com/docs/components/schema/document).
|
||||||
|
|
||||||
|
`Documents` are turned into a Chat or QA app following the general steps below:
|
||||||
|
|
||||||
|
* `Splitting`: [Text splitters](https://python.langchain.com/docs/modules/data_connection/document_transformers/) break `Documents` into splits of specified size
|
||||||
|
* `Storage`: Storage (e.g., often a [vectorstore](https://python.langchain.com/docs/modules/data_connection/vectorstores/)) will house [and often embed](https://www.pinecone.io/learn/vector-embeddings/) the splits
|
||||||
|
* `Retrieval`: The app retrieves splits from storage (e.g., often [with similar embeddings](https://www.pinecone.io/learn/k-nearest-neighbor/) to the input question)
|
||||||
|
* `Output`: An [LLM](https://python.langchain.com/docs/modules/model_io/models/llms/) produces an answer using a prompt that includes the question and the retrieved splits
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Quickstart
|
||||||
|
|
||||||
|
The above pipeline can be wrapped with a `VectorstoreIndexCreator`.
|
||||||
|
|
||||||
|
In particular:
|
||||||
|
|
||||||
|
* Specify a `Document` loader
|
||||||
|
* The `splitting`, `storage`, `retrieval`, and `output` generation stages are wrapped
|
||||||
|
|
||||||
|
Let's load this [blog post](https://lilianweng.github.io/posts/2023-06-23-agent/) on agents as an example `Document`.
|
||||||
|
|
||||||
|
We have a QA app in a few lines of code.
|
||||||
|
|
||||||
**Load Your Documents**
|
|
||||||
|
|
||||||
```python
|
|
||||||
from langchain.document_loaders import TextLoader
|
|
||||||
loader = TextLoader('../../modules/state_of_the_union.txt')
|
|
||||||
```
|
|
||||||
|
|
||||||
See [here](/docs/modules/data_connection/document_loaders/) for more information on how to get started with document loading.
|
|
||||||
|
|
||||||
**Create Your Index**
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
from langchain.document_loaders import WebBaseLoader
|
||||||
from langchain.indexes import VectorstoreIndexCreator
|
from langchain.indexes import VectorstoreIndexCreator
|
||||||
|
# Document loader
|
||||||
|
loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")
|
||||||
|
# Index that wraps above steps
|
||||||
index = VectorstoreIndexCreator().from_loaders([loader])
|
index = VectorstoreIndexCreator().from_loaders([loader])
|
||||||
|
# Question-answering
|
||||||
|
question = "What is Task Decomposition?"
|
||||||
|
index.query(question)
|
||||||
```
|
```
|
||||||
|
|
||||||
The best and most popular index by far at the moment is the VectorStore index.
|
|
||||||
|
|
||||||
**Query Your Index**
|
|
||||||
|
|
||||||
|
' Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. It can be done using LLM with simple prompting, task-specific instructions, or human inputs. Tree of Thoughts (Yao et al. 2023) is an example of a task decomposition technique that explores multiple reasoning possibilities at each step and generates multiple thoughts per step, creating a tree structure.'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Of course, some users do not wnat this level of abstraction.
|
||||||
|
|
||||||
|
Below, we will discuss each stage in more detail.
|
||||||
|
|
||||||
|
## 1. Loading, Splitting, Storage
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 1.1 Getting started
|
||||||
|
|
||||||
|
Specify a `Document` loader.
|
||||||
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
query = "What did the president say about Ketanji Brown Jackson"
|
# Document loader
|
||||||
index.query(query)
|
from langchain.document_loaders import WebBaseLoader
|
||||||
|
loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")
|
||||||
|
data = loader.load()
|
||||||
```
|
```
|
||||||
|
|
||||||
Alternatively, use `query_with_sources` to also get back the sources involved
|
Split the `Document` into chunks for embedding and vector storage.
|
||||||
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
query = "What did the president say about Ketanji Brown Jackson"
|
# Split
|
||||||
index.query_with_sources(query)
|
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||||
|
text_splitter = RecursiveCharacterTextSplitter(chunk_size = 500, chunk_overlap = 0)
|
||||||
|
all_splits = text_splitter.split_documents(data)
|
||||||
```
|
```
|
||||||
|
|
||||||
Again, these high level interfaces obfuscate a lot of what is going on under the hood, so please see [this notebook](/docs/modules/data_connection/) for a more thorough introduction to data modules.
|
Embed and store the splits in a vector database ([Chroma](https://python.langchain.com/docs/modules/data_connection/vectorstores/integrations/chroma)).
|
||||||
|
|
||||||
## Document Question Answering
|
|
||||||
|
|
||||||
Question answering involves fetching multiple documents, and then asking a question of them.
|
```python
|
||||||
The LLM response will contain the answer to your question, based on the content of the documents.
|
# Store
|
||||||
|
from langchain.vectorstores import Chroma
|
||||||
|
from langchain.embeddings import OpenAIEmbeddings
|
||||||
|
vectorstore = Chroma.from_documents(documents=all_splits,embedding=OpenAIEmbeddings())
|
||||||
|
```
|
||||||
|
|
||||||
|
Here are the three pieces together:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### 1.2 Going Deeper
|
||||||
|
|
||||||
|
#### 1.2.1 Integrations
|
||||||
|
|
||||||
|
`Data Loaders`
|
||||||
|
|
||||||
|
* Browse the > 120 data loader integrations [here](https://integrations.langchain.com/).
|
||||||
|
|
||||||
|
* See further documentation on loaders [here](https://python.langchain.com/docs/modules/data_connection/document_loaders/).
|
||||||
|
|
||||||
|
`Data Transformers`
|
||||||
|
|
||||||
|
* All can ingest loaded `Documents` and process them (e.g., split).
|
||||||
|
|
||||||
|
* See further documentation on transformers [here](https://python.langchain.com/docs/modules/data_connection/document_transformers/).
|
||||||
|
|
||||||
|
`Vectorstores`
|
||||||
|
|
||||||
|
* Browse the > 35 vectorstores integrations [here](https://integrations.langchain.com/).
|
||||||
|
|
||||||
|
* See further documentation on vectorstores [here](https://python.langchain.com/docs/modules/data_connection/vectorstores/).
|
||||||
|
|
||||||
|
#### 1.2.2 Retaining metadata
|
||||||
|
|
||||||
|
`Context-aware splitters` keep the location or "context" of each split in the origional `Document`:
|
||||||
|
|
||||||
|
* [Markdown files](https://python.langchain.com/docs/use_cases/question_answering/document-context-aware-QA)
|
||||||
|
* [Code (py or js)](https://python.langchain.com/docs/modules/data_connection/document_loaders/integrations/source_code)
|
||||||
|
* [Documents](https://python.langchain.com/docs/modules/data_connection/document_loaders/integrations/grobid)
|
||||||
|
|
||||||
|
## 2. Retrieval
|
||||||
|
|
||||||
|
### 2.1 Getting started
|
||||||
|
|
||||||
|
Retrieve [relevant splits](https://www.pinecone.io/learn/what-is-similarity-search/) for any question using `similarity_search`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
question = "What are the approaches to Task Decomposition?"
|
||||||
|
docs = vectorstore.similarity_search(question)
|
||||||
|
len(docs)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
4
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 2.2 Going Deeper
|
||||||
|
|
||||||
|
#### 2.2.1 Retrieval
|
||||||
|
|
||||||
|
Vectorstores are commonly used for retrieval.
|
||||||
|
|
||||||
|
But, they are not the only option.
|
||||||
|
|
||||||
|
For example, SVMs (see thread [here](https://twitter.com/karpathy/status/1647025230546886658?s=20)) can also be used.
|
||||||
|
|
||||||
|
LangChain [has many retrievers](https://python.langchain.com/docs/modules/data_connection/retrievers/) including, but not limited to, vectorstores.
|
||||||
|
|
||||||
|
All retrievers implement some common, useful methods, such as `get_relevant_documents()`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from langchain.retrievers import SVMRetriever
|
||||||
|
svm_retriever = SVMRetriever.from_documents(all_splits,OpenAIEmbeddings())
|
||||||
|
docs_svm=svm_retriever.get_relevant_documents(question)
|
||||||
|
len(docs)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
4
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### 2.2.2 Advanced retrieval
|
||||||
|
|
||||||
|
Improve on `similarity_search`:
|
||||||
|
|
||||||
|
* `MultiQueryRetriever` [generates variants of the input question](https://python.langchain.com/docs/modules/data_connection/retrievers/how_to/MultiQueryRetriever) to improve retrieval.
|
||||||
|
|
||||||
|
* `Max marginal relevance` selects for [relevance and diversity](https://www.cs.cmu.edu/~jgc/publication/The_Use_MMR_Diversity_Based_LTMIR_1998.pdf) among the retrieved documents.
|
||||||
|
|
||||||
|
* Documents can be filtered during retrieval using [`metadata` filters](https://python.langchain.com/docs/use_cases/question_answering/document-context-aware-QA).
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# MultiQueryRetriever
|
||||||
|
import logging
|
||||||
|
from langchain.chat_models import ChatOpenAI
|
||||||
|
from langchain.retrievers.multi_query import MultiQueryRetriever
|
||||||
|
logging.basicConfig()
|
||||||
|
logging.getLogger('langchain.retrievers.multi_query').setLevel(logging.INFO)
|
||||||
|
retriever_from_llm = MultiQueryRetriever.from_llm(retriever=vectorstore.as_retriever(),
|
||||||
|
llm=ChatOpenAI(temperature=0))
|
||||||
|
unique_docs = retriever_from_llm.get_relevant_documents(query=question)
|
||||||
|
len(unique_docs)
|
||||||
|
```
|
||||||
|
|
||||||
|
INFO:langchain.retrievers.multi_query:Generated queries: ['1. How can Task Decomposition be approached?', '2. What are the different methods for Task Decomposition?', '3. What are the various approaches to decomposing tasks?']
|
||||||
|
5
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 3. QA
|
||||||
|
|
||||||
|
### 3.1 Getting started
|
||||||
|
|
||||||
|
Distill the retried documents into an answer using an LLM (e.g., `gpt-3.5-turbo`) with `RetrievalQA` chain.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from langchain.chat_models import ChatOpenAI
|
||||||
|
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
|
||||||
|
from langchain.chains import RetrievalQA
|
||||||
|
qa_chain = RetrievalQA.from_chain_type(llm,retriever=vectorstore.as_retriever())
|
||||||
|
qa_chain({"query": question})
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
{'query': 'What are the approaches to Task Decomposition?',
|
||||||
|
'result': 'The approaches to task decomposition include:\n\n1. Simple prompting: This approach involves using simple prompts or questions to guide the agent in breaking down a task into smaller subgoals. For example, the agent can be prompted with "Steps for XYZ" and asked to list the subgoals for achieving XYZ.\n\n2. Task-specific instructions: In this approach, task-specific instructions are provided to the agent to guide the decomposition process. For example, if the task is to write a novel, the agent can be instructed to "Write a story outline" as a subgoal.\n\n3. Human inputs: This approach involves incorporating human inputs in the task decomposition process. Humans can provide guidance, feedback, and suggestions to help the agent break down complex tasks into manageable subgoals.\n\nThese approaches aim to enable efficient handling of complex tasks by breaking them down into smaller, more manageable parts.'}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 3.2 Going Deeper
|
||||||
|
|
||||||
|
#### 3.2.1 Integrations
|
||||||
|
|
||||||
|
`LLMs`
|
||||||
|
|
||||||
|
* Browse the > 55 model integrations [here](https://integrations.langchain.com/).
|
||||||
|
|
||||||
|
* See further documentation on vectorstores [here](https://python.langchain.com/docs/modules/model_io/models/).
|
||||||
|
|
||||||
|
#### 3.2.2 Running LLMs locally
|
||||||
|
|
||||||
|
The popularity of [PrivateGPT](https://github.com/imartinez/privateGPT) and [GPT4All](https://github.com/nomic-ai/gpt4all) underscore the importance of running LLMs locally.
|
||||||
|
|
||||||
|
LangChain has integrations with many open source LLMs that can be run locally.
|
||||||
|
|
||||||
|
Using `GPT4All` is as simple as [downloading the binary]((https://python.langchain.com/docs/modules/model_io/models/llms/integrations/gpt4all)) and then:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from langchain.llms import GPT4All
|
||||||
|
from langchain.chains import RetrievalQA
|
||||||
|
llm = GPT4All(model="/Users/rlm/Desktop/Code/gpt4all/models/nous-hermes-13b.ggmlv3.q4_0.bin",max_tokens=2048)
|
||||||
|
qa_chain = RetrievalQA.from_chain_type(llm,retriever=vectorstore.as_retriever())
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
qa_chain({"query": question})
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
{'query': 'What are the approaches to Task Decomposition?',
|
||||||
|
'result': ' There are three main approaches to task decomposition: (1) using language models like GPT-3 for simple prompting such as "Steps for XYZ.\\n1.", (2) using task-specific instructions, and (3) with human inputs.'}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### 3.2.2 Customizing the prompt
|
||||||
|
|
||||||
|
The prompt in `RetrievalQA` chain can be easily customized.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Build prompt
|
||||||
|
from langchain.prompts import PromptTemplate
|
||||||
|
template = """Use the following pieces of context to answer the question at the end.
|
||||||
|
If you don't know the answer, just say that you don't know, don't try to make up an answer.
|
||||||
|
Use three sentences maximum and keep the answer as concise as possible.
|
||||||
|
Always say "thanks for asking!" at the end of the answer.
|
||||||
|
{context}
|
||||||
|
Question: {question}
|
||||||
|
Helpful Answer:"""
|
||||||
|
QA_CHAIN_PROMPT = PromptTemplate(input_variables=["context", "question"],template=template,)
|
||||||
|
|
||||||
|
# Run chain
|
||||||
|
from langchain.chains import RetrievalQA
|
||||||
|
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
|
||||||
|
qa_chain = RetrievalQA.from_chain_type(llm,
|
||||||
|
retriever=vectorstore.as_retriever(),
|
||||||
|
chain_type_kwargs={"prompt": QA_CHAIN_PROMPT})
|
||||||
|
|
||||||
|
result = qa_chain({"query": question})
|
||||||
|
result["result"]
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
'The approaches to Task Decomposition are (1) using simple prompting by LLM, (2) using task-specific instructions, and (3) with human inputs. Thanks for asking!'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### 3.2.3 Returning source documents
|
||||||
|
|
||||||
|
The full set of retrieved documents used for answer distillation can be returned using `return_source_documents=True`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from langchain.chains import RetrievalQA
|
||||||
|
qa_chain = RetrievalQA.from_chain_type(llm,retriever=vectorstore.as_retriever(),
|
||||||
|
return_source_documents=True)
|
||||||
|
result = qa_chain({"query": question})
|
||||||
|
print(len(result['source_documents']))
|
||||||
|
result['source_documents'][0]
|
||||||
|
```
|
||||||
|
|
||||||
|
4
|
||||||
|
Document(page_content='Task decomposition can be done (1) by LLM with simple prompting like "Steps for XYZ.\\n1.", "What are the subgoals for achieving XYZ?", (2) by using task-specific instructions; e.g. "Write a story outline." for writing a novel, or (3) with human inputs.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': "LLM Powered Autonomous Agents | Lil'Log", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\nAgent System Overview In a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:', 'language': 'en'})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### 3.2.4 Citations
|
||||||
|
|
||||||
|
Answer citations can be returned using `RetrievalQAWithSourcesChain`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from langchain.chains import RetrievalQAWithSourcesChain
|
||||||
|
qa_chain = RetrievalQAWithSourcesChain.from_chain_type(llm,retriever=vectorstore.as_retriever())
|
||||||
|
result = qa_chain({"question": question})
|
||||||
|
result
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
{'question': 'What are the approaches to Task Decomposition?',
|
||||||
|
'answer': 'The approaches to Task Decomposition include (1) using LLM with simple prompting, (2) using task-specific instructions, and (3) incorporating human inputs.\n',
|
||||||
|
'sources': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### 3.2.5 Customizing how pass retrieved documents to the LLM
|
||||||
|
|
||||||
|
Retrieved documents can be fed to an LLM for answer distillation in a few different ways.
|
||||||
|
|
||||||
|
`stuff`, `refine`, `map-reduce`, and `map-rerank` chains for passing documents to an LLM prompt are well summarized [here](https://python.langchain.com/docs/modules/chains/document/).
|
||||||
|
|
||||||
|
`stuff` is commonly used because it simply "stuffs" all retrieved documents into the prompt.
|
||||||
|
|
||||||
|
The [load_qa_chain](https://python.langchain.com/docs/modules/chains/additional/question_answering.html) is an easy way to pass documents to an LLM using these various approaches (e.g., see `chain_type`).
|
||||||
|
|
||||||
The recommended way to get started using a question answering chain is:
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from langchain.chains.question_answering import load_qa_chain
|
from langchain.chains.question_answering import load_qa_chain
|
||||||
chain = load_qa_chain(llm, chain_type="stuff")
|
chain = load_qa_chain(llm, chain_type="stuff")
|
||||||
chain.run(input_documents=docs, question=query)
|
chain({"input_documents": unique_docs, "question": question},return_only_outputs=True)
|
||||||
```
|
```
|
||||||
|
|
||||||
The following resources exist:
|
|
||||||
|
|
||||||
- [Question Answering Notebook](/docs/modules/chains/additional/question_answering.html): A notebook walking through how to accomplish this task.
|
|
||||||
- [VectorDB Question Answering Notebook](/docs/modules/chains/popular/vector_db_qa.html): A notebook walking through how to do question answering over a vector database. This can often be useful for when you have a LOT of documents, and you don't want to pass them all to the LLM, but rather first want to do some semantic search over embeddings.
|
|
||||||
|
|
||||||
## Adding in sources
|
|
||||||
|
|
||||||
There is also a variant of this, where in addition to responding with the answer the language model will also cite its sources (eg which of the documents passed in it used).
|
{'output_text': 'The approaches to task decomposition include (1) using simple prompting to break down tasks into subgoals, (2) providing task-specific instructions to guide the decomposition process, and (3) incorporating human inputs for task decomposition.'}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
We can also pass the `chain_type` to `RetrievalQA`.
|
||||||
|
|
||||||
The recommended way to get started using a question answering with sources chain is:
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
|
qa_chain = RetrievalQA.from_chain_type(llm,retriever=vectorstore.as_retriever(),
|
||||||
chain = load_qa_with_sources_chain(llm, chain_type="stuff")
|
chain_type="stuff")
|
||||||
chain({"input_documents": docs, "question": query}, return_only_outputs=True)
|
result = qa_chain({"query": question})
|
||||||
```
|
```
|
||||||
|
|
||||||
## Additional Related Resources
|
In summary, the user can choose the desired level of abstraction for QA:
|
||||||
|
|
||||||
Additional related resources include:
|

|
||||||
|
|
||||||
- [Building blocks for working with Documents](/docs/modules/data_connection/): Guides on how to use several of the utilities which will prove helpful for this task, including Text Splitters (for splitting up long documents) and Embeddings & Vectorstores (useful for the above Vector DB example).
|
## 4. Chat
|
||||||
- [CombineDocuments Chains](/docs/modules/chains/document/): A conceptual overview of specific types of chains by which you can accomplish this task.
|
|
||||||
|
|
||||||
## End-to-end examples
|
### 4.1 Getting started
|
||||||
|
|
||||||
For examples to this done in an end-to-end manner, please see the following resources:
|
To keep chat history, first specify a `Memory buffer` to track the conversation inputs / outputs.
|
||||||
|
|
||||||
- [Semantic search over a group chat with Sources Notebook](/docs/use_cases/question_answering/semantic-search-over-chat.html): A notebook that semantically searches over a group chat conversation.
|
|
||||||
- [Document context aware text splitting and QA](/docs/use_cases/question_answering/document-context-aware-QA.html): A notebook that shows context aware splitting on markdown files and SelfQueryRetriever for QA using the resulting metadata.
|
```python
|
||||||
|
from langchain.memory import ConversationBufferMemory
|
||||||
|
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
The `ConversationalRetrievalChain` uses chat in the `Memory buffer`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from langchain.chains import ConversationalRetrievalChain
|
||||||
|
retriever=vectorstore.as_retriever()
|
||||||
|
chat = ConversationalRetrievalChain.from_llm(llm,retriever=retriever,memory=memory)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
result = chat({"question": "What are some of the main ideas in self-reflection?"})
|
||||||
|
result['answer']
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
"Some of the main ideas in self-reflection include:\n1. Iterative improvement: Self-reflection allows autonomous agents to improve by refining past action decisions and correcting mistakes.\n2. Trial and error: Self-reflection is crucial in real-world tasks where trial and error are inevitable.\n3. Two-shot examples: Self-reflection is created by showing pairs of failed trajectories and ideal reflections for guiding future changes in the plan.\n4. Working memory: Reflections are added to the agent's working memory, up to three, to be used as context for querying.\n5. Performance evaluation: Self-reflection involves continuously reviewing and analyzing actions, self-criticizing behavior, and reflecting on past decisions and strategies to refine approaches.\n6. Efficiency: Self-reflection encourages being smart and efficient, aiming to complete tasks in the least number of steps."
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
The `Memory buffer` has context to resolve `"it"` ("self-reflection") in the below question.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
result = chat({"question": "How does the Reflexion paper handle it?"})
|
||||||
|
result['answer']
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
"The Reflexion paper handles self-reflection by showing two-shot examples to the Learning Language Model (LLM). Each example consists of a failed trajectory and an ideal reflection that guides future changes in the agent's plan. These reflections are then added to the agent's working memory, up to a maximum of three, to be used as context for querying the LLM. This allows the agent to iteratively improve its reasoning skills by refining past action decisions and correcting previous mistakes."
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 4.2 Going deeper
|
||||||
|
|
||||||
|
The [documentation](https://python.langchain.com/docs/modules/chains/popular/chat_vector_db) on `ConversationalRetrievalChain` offers a few extensions, such as streaming and source documents.
|
||||||
|
@ -5,7 +5,7 @@ https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb"""
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
from typing import Any, List, Optional
|
from typing import Any, Iterable, List, Optional
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
@ -53,10 +53,26 @@ class SVMRetriever(BaseRetriever):
|
|||||||
index = create_index(texts, embeddings)
|
index = create_index(texts, embeddings)
|
||||||
return cls(embeddings=embeddings, index=index, texts=texts, **kwargs)
|
return cls(embeddings=embeddings, index=index, texts=texts, **kwargs)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_documents(
|
||||||
|
cls,
|
||||||
|
documents: Iterable[Document],
|
||||||
|
embeddings: Embeddings,
|
||||||
|
**kwargs: Any,
|
||||||
|
) -> SVMRetriever:
|
||||||
|
texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents))
|
||||||
|
return cls.from_texts(texts=texts, embeddings=embeddings, **kwargs)
|
||||||
|
|
||||||
def _get_relevant_documents(
|
def _get_relevant_documents(
|
||||||
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
|
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
|
||||||
) -> List[Document]:
|
) -> List[Document]:
|
||||||
|
try:
|
||||||
from sklearn import svm
|
from sklearn import svm
|
||||||
|
except ImportError:
|
||||||
|
raise ImportError(
|
||||||
|
"Could not import scikit-learn, please install with `pip install "
|
||||||
|
"scikit-learn`."
|
||||||
|
)
|
||||||
|
|
||||||
query_embeds = np.array(self.embeddings.embed_query(query))
|
query_embeds = np.array(self.embeddings.embed_query(query))
|
||||||
x = np.concatenate([query_embeds[None, ...], self.index])
|
x = np.concatenate([query_embeds[None, ...], self.index])
|
||||||
|
Loading…
Reference in New Issue
Block a user