Skip to content

Commit 8ab09c1

Browse files
hwchase17fpinghamlesscomfortable
authored
Return source documents option in VectorDBQA (#585) (#592)
Co-authored-by: lesscomfortable <[email protected]> Co-authored-by: Francisco Ingham <[email protected]> Co-authored-by: lesscomfortable <[email protected]>
1 parent 4c6c5f0 commit 8ab09c1

File tree

2 files changed

+120
-12
lines changed

2 files changed

+120
-12
lines changed

docs/modules/chains/combine_docs_examples/vector_db_qa.ipynb

Lines changed: 90 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
},
2626
{
2727
"cell_type": "code",
28-
"execution_count": 3,
28+
"execution_count": 2,
2929
"id": "5c7049db",
3030
"metadata": {},
3131
"outputs": [],
@@ -41,7 +41,7 @@
4141
},
4242
{
4343
"cell_type": "code",
44-
"execution_count": 4,
44+
"execution_count": 3,
4545
"id": "3018f865",
4646
"metadata": {},
4747
"outputs": [],
@@ -51,17 +51,17 @@
5151
},
5252
{
5353
"cell_type": "code",
54-
"execution_count": 5,
54+
"execution_count": 4,
5555
"id": "032a47f8",
5656
"metadata": {},
5757
"outputs": [
5858
{
5959
"data": {
6060
"text/plain": [
61-
"\" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, and that she will continue Justice Breyer's legacy of excellence.\""
61+
"' The president said that Ketanji Brown Jackson is one of the nations top legal minds and that she will continue Justice Breyers legacy of excellence.'"
6262
]
6363
},
64-
"execution_count": 5,
64+
"execution_count": 4,
6565
"metadata": {},
6666
"output_type": "execute_result"
6767
}
@@ -70,11 +70,94 @@
7070
"query = \"What did the president say about Ketanji Brown Jackson\"\n",
7171
"qa.run(query)"
7272
]
73+
},
74+
{
75+
"cell_type": "markdown",
76+
"id": "0b8c37f7",
77+
"metadata": {},
78+
"source": [
79+
"## Return Source Documents\n",
80+
"Additionally, we can return the source documents used to answer the question by specifying an optional paramter when constructing the chain."
81+
]
82+
},
83+
{
84+
"cell_type": "code",
85+
"execution_count": 5,
86+
"id": "af093aba",
87+
"metadata": {},
88+
"outputs": [],
89+
"source": [
90+
"qa = VectorDBQA.from_llm(llm=OpenAI(), vectorstore=docsearch, return_source_documents=True)"
91+
]
92+
},
93+
{
94+
"cell_type": "code",
95+
"execution_count": 8,
96+
"id": "eac11321",
97+
"metadata": {},
98+
"outputs": [],
99+
"source": [
100+
"query = \"What did the president say about Ketanji Brown Jackson\"\n",
101+
"result = qa({\"query\": query})"
102+
]
103+
},
104+
{
105+
"cell_type": "code",
106+
"execution_count": 10,
107+
"id": "7d75945a",
108+
"metadata": {},
109+
"outputs": [
110+
{
111+
"data": {
112+
"text/plain": [
113+
"\" 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.\""
114+
]
115+
},
116+
"execution_count": 10,
117+
"metadata": {},
118+
"output_type": "execute_result"
119+
}
120+
],
121+
"source": [
122+
"result[\"result\"]"
123+
]
124+
},
125+
{
126+
"cell_type": "code",
127+
"execution_count": 11,
128+
"id": "35b4f31f",
129+
"metadata": {},
130+
"outputs": [
131+
{
132+
"data": {
133+
"text/plain": [
134+
"[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",
135+
" 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",
136+
" 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",
137+
" 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)]"
138+
]
139+
},
140+
"execution_count": 11,
141+
"metadata": {},
142+
"output_type": "execute_result"
143+
}
144+
],
145+
"source": [
146+
"result[\"source_documents\"]"
147+
]
148+
},
149+
{
150+
"cell_type": "code",
151+
"execution_count": null,
152+
"id": "8b403637",
153+
"metadata": {},
154+
"outputs": [],
155+
"source": []
73156
}
74157
],
75158
"metadata": {
76159
"kernelspec": {
77-
"display_name": "Python 3.9.0 64-bit ('llm-env')",
160+
"display_name": "Python 3 (ipykernel)",
78161
"language": "python",
79162
"name": "python3"
80163
},
@@ -88,7 +171,7 @@
88171
"name": "python",
89172
"nbconvert_exporter": "python",
90173
"pygments_lexer": "ipython3",
91-
"version": "3.9.0"
174+
"version": "3.10.9"
92175
},
93176
"vscode": {
94177
"interpreter": {

langchain/chains/vector_db_qa/base.py

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ class VectorDBQA(Chain, BaseModel):
3636
"""Chain to use to combine the documents."""
3737
input_key: str = "query" #: :meta private:
3838
output_key: str = "result" #: :meta private:
39+
return_source_documents: bool = False
40+
"""Return the source documents."""
3941

4042
class Config:
4143
"""Configuration for this pydantic object."""
@@ -45,19 +47,22 @@ class Config:
4547

4648
@property
4749
def input_keys(self) -> List[str]:
48-
"""Return the singular input key.
50+
"""Return the input keys.
4951
5052
:meta private:
5153
"""
5254
return [self.input_key]
5355

5456
@property
5557
def output_keys(self) -> List[str]:
56-
"""Return the singular output key.
58+
"""Return the output keys.
5759
5860
:meta private:
5961
"""
60-
return [self.output_key]
62+
_output_keys = [self.output_key]
63+
if self.return_source_documents:
64+
_output_keys = _output_keys + ["source_documents"]
65+
return _output_keys
6166

6267
# TODO: deprecate this
6368
@root_validator(pre=True)
@@ -96,10 +101,30 @@ def from_llm(
96101
document_variable_name="context",
97102
document_prompt=document_prompt,
98103
)
104+
99105
return cls(combine_documents_chain=combine_documents_chain, **kwargs)
100106

101-
def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
107+
def _call(
108+
self,
109+
inputs: Dict[str, str],
110+
) -> Dict[str, Any]:
111+
"""Run similarity search and llm on input query.
112+
113+
If inputs contains 'return_source_documents' as 'True', returns
114+
the retrieved documents as well under the key 'source_documents'.
115+
116+
Example:
117+
.. code-block:: python
118+
119+
res = vectordbqa({'query': 'This is my query', 'return_source_documents': True})
120+
answer, docs = res['result'], res['source_documents']
121+
"""
102122
question = inputs[self.input_key]
123+
103124
docs = self.vectorstore.similarity_search(question, k=self.k)
104125
answer, _ = self.combine_documents_chain.combine_docs(docs, question=question)
105-
return {self.output_key: answer}
126+
127+
if self.return_source_documents:
128+
return {self.output_key: answer, "source_documents": docs}
129+
else:
130+
return {self.output_key: answer}

0 commit comments

Comments
 (0)