langchain/docs/modules/chains/index_examples/question_answering.ipynb

755 lines
26 KiB
Plaintext
Raw Normal View History

2022-12-08 06:56:26 +00:00
{
"cells": [
{
"cell_type": "markdown",
"id": "05859721",
"metadata": {},
"source": [
"# Question Answering\n",
"\n",
"This notebook walks through how to use LangChain for question answering over a list of documents. It covers four different types of chains: `stuff`, `map_reduce`, `refine`, `map_rerank`. For a more in depth explanation of what these chain types are, see [here](https://docs.langchain.com/docs/components/chains/index_related_chains)."
2022-12-08 06:56:26 +00:00
]
},
{
"cell_type": "markdown",
"id": "726f4996",
"metadata": {},
"source": [
"## Prepare Data\n",
2022-12-08 06:56:26 +00:00
"First we prepare the data. For this example we do similarity search over a vector database, but these documents could be fetched in any manner (the point of this notebook to highlight what to do AFTER you fetch the documents)."
]
},
{
"cell_type": "code",
"execution_count": 1,
2022-12-08 06:56:26 +00:00
"id": "17fcbc0f",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [],
"source": [
"from langchain.embeddings.openai import OpenAIEmbeddings\n",
"from langchain.text_splitter import CharacterTextSplitter\n",
2023-02-13 07:02:01 +00:00
"from langchain.vectorstores import Chroma\n",
"from langchain.docstore.document import Document\n",
2023-02-27 08:31:36 +00:00
"from langchain.prompts import PromptTemplate\n",
"from langchain.indexes.vectorstore import VectorstoreIndexCreator"
2022-12-08 06:56:26 +00:00
]
},
{
"cell_type": "code",
"execution_count": 2,
2023-02-27 08:31:36 +00:00
"id": "ef9305cc",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [],
"source": [
"with open(\"../../state_of_the_union.txt\") as f:\n",
" state_of_the_union = f.read()\n",
"text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
"texts = text_splitter.split_text(state_of_the_union)\n",
"\n",
"embeddings = OpenAIEmbeddings()"
2022-12-08 06:56:26 +00:00
]
},
{
"cell_type": "code",
2023-02-27 08:31:36 +00:00
"execution_count": 3,
"id": "291f0117",
"metadata": {
"tags": []
},
2023-02-13 07:02:01 +00:00
"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"
]
}
],
2022-12-08 06:56:26 +00:00
"source": [
"docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{\"source\": str(i)} for i in range(len(texts))]).as_retriever()"
2022-12-08 06:56:26 +00:00
]
},
{
"cell_type": "code",
2023-02-27 08:31:36 +00:00
"execution_count": 4,
2022-12-08 06:56:26 +00:00
"id": "d1eaf6e6",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [],
"source": [
"query = \"What did the president say about Justice Breyer\"\n",
"docs = docsearch.get_relevant_documents(query)"
2022-12-08 06:56:26 +00:00
]
},
{
"cell_type": "code",
"execution_count": 5,
2022-12-08 06:56:26 +00:00
"id": "a16e3453",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [],
"source": [
"from langchain.chains.question_answering import load_qa_chain\n",
"from langchain.llms import OpenAI"
]
},
{
"cell_type": "markdown",
"id": "2f64b7f8",
"metadata": {},
"source": [
"## Quickstart\n",
"If you just want to get started as quickly as possible, this is the recommended way to do it:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "fd9e6190",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"' The president said that Justice Breyer has dedicated his life to serve the country and thanked him for his service.'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"stuff\")\n",
"query = \"What did the president say about Justice Breyer\"\n",
"chain.run(input_documents=docs, question=query)"
]
},
{
"cell_type": "markdown",
"id": "eea01309",
"metadata": {},
"source": [
"If you want more control and understanding over what is happening, please see the information below."
]
},
2022-12-08 06:56:26 +00:00
{
"cell_type": "markdown",
"id": "f78787a0",
"metadata": {},
"source": [
"## The `stuff` Chain\n",
2022-12-08 06:56:26 +00:00
"\n",
"This sections shows results of using the `stuff` Chain to do question answering."
]
},
{
"cell_type": "code",
"execution_count": 7,
2022-12-08 06:56:26 +00:00
"id": "180fd4c1",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"stuff\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
2022-12-08 06:56:26 +00:00
"id": "77fdf1aa",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [
{
"data": {
"text/plain": [
"{'output_text': ' The president said that Justice Breyer has dedicated his life to serve the country and thanked him for his service.'}"
2022-12-08 06:56:26 +00:00
]
},
"execution_count": 8,
2022-12-08 06:56:26 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"query = \"What did the president say about Justice Breyer\"\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "84794d4c",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "5558c9e0",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha ricevuto una vasta gamma di supporto.'}"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prompt_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.\n",
"\n",
"{context}\n",
"\n",
"Question: {question}\n",
"Answer in Italian:\"\"\"\n",
"PROMPT = PromptTemplate(\n",
" template=prompt_template, input_variables=[\"context\", \"question\"]\n",
")\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"stuff\", prompt=PROMPT)\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
2022-12-08 06:56:26 +00:00
{
"cell_type": "markdown",
"id": "91522e29",
"metadata": {},
"source": [
"## The `map_reduce` Chain\n",
2022-12-08 06:56:26 +00:00
"\n",
"This sections shows results of using the `map_reduce` Chain to do question answering."
]
},
{
"cell_type": "code",
"execution_count": 10,
2022-12-08 06:56:26 +00:00
"id": "b0060f51",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_reduce\")"
]
},
{
"cell_type": "code",
"execution_count": 11,
2022-12-08 06:56:26 +00:00
"id": "fbdb9137",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [
{
"data": {
"text/plain": [
"{'output_text': ' The president said that Justice Breyer is an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court, and thanked him for his service.'}"
2022-12-08 06:56:26 +00:00
]
},
"execution_count": 11,
2022-12-08 06:56:26 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"query = \"What did the president say about Justice Breyer\"\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "31478d32",
"metadata": {},
"source": [
"**Intermediate Steps**\n",
"\n",
"We can also return the intermediate steps for `map_reduce` chains, should we want to inspect them. This is done with the `return_map_steps` variable."
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "452c8680",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_map_steps=True)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "90b47a75",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': [' \"Tonight, Id 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",
" ' 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 shes been nominated, shes received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.',\n",
" ' None',\n",
" ' None'],\n",
" 'output_text': ' The president said that Justice Breyer is an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court, and thanked him for his service.'}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "93c51102",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "af03a578",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': [\"\\nStasera vorrei onorare qualcuno che ha dedicato la sua vita a servire questo paese: il giustizia Stephen Breyer - un veterano dell'esercito, uno studioso costituzionale e un giustizia in uscita della Corte Suprema degli Stati Uniti. Giustizia Breyer, grazie per il tuo servizio.\",\n",
" '\\nNessun testo pertinente.',\n",
" ' Non ha detto nulla riguardo a Justice Breyer.',\n",
" \" Non c'è testo pertinente.\"],\n",
" 'output_text': ' Non ha detto nulla riguardo a Justice Breyer.'}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"question_prompt_template = \"\"\"Use the following portion of a long document to see if any of the text is relevant to answer the question. \n",
"Return any relevant text translated into italian.\n",
"{context}\n",
"Question: {question}\n",
"Relevant text, if any, in Italian:\"\"\"\n",
"QUESTION_PROMPT = PromptTemplate(\n",
" template=question_prompt_template, input_variables=[\"context\", \"question\"]\n",
")\n",
"\n",
"combine_prompt_template = \"\"\"Given the following extracted parts of a long document and a question, create a final answer italian. \n",
"If you don't know the answer, just say that you don't know. Don't try to make up an answer.\n",
"\n",
"QUESTION: {question}\n",
"=========\n",
"{summaries}\n",
"=========\n",
"Answer in Italian:\"\"\"\n",
"COMBINE_PROMPT = PromptTemplate(\n",
" template=combine_prompt_template, input_variables=[\"summaries\", \"question\"]\n",
")\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_map_steps=True, question_prompt=QUESTION_PROMPT, combine_prompt=COMBINE_PROMPT)\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
2023-02-16 07:53:56 +00:00
{
"cell_type": "markdown",
"id": "6391b7ab",
"metadata": {},
"source": [
"**Batch Size**\n",
"\n",
"When using the `map_reduce` chain, one thing to keep in mind is the batch size you are using during the map step. If this is too high, it could cause rate limiting errors. You can control this by setting the batch size on the LLM used. Note that this only applies for LLMs with this parameter. Below is an example of doing so:\n",
"\n",
"```python\n",
"llm = OpenAI(batch_size=5, temperature=0)\n",
"```"
]
},
2022-12-08 06:56:26 +00:00
{
"cell_type": "markdown",
"id": "6ea50ad0",
"metadata": {},
"source": [
"## The `refine` Chain\n",
2022-12-08 06:56:26 +00:00
"\n",
"This sections shows results of using the `refine` Chain to do question answering."
]
},
{
"cell_type": "code",
"execution_count": 15,
2022-12-08 06:56:26 +00:00
"id": "fb167057",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"refine\")"
]
},
{
"cell_type": "code",
"execution_count": 16,
2022-12-08 06:56:26 +00:00
"id": "d8b5286e",
"metadata": {
"tags": []
},
2022-12-08 06:56:26 +00:00
"outputs": [
{
"data": {
"text/plain": [
"{'output_text': '\\n\\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his support of the Equality Act and his commitment to protecting the rights of LGBTQ+ Americans. He also praised Justice Breyer for his role in helping to pass the Bipartisan Infrastructure Law, which he said would be the most sweeping investment to rebuild America in history and would help the country compete for the jobs of the 21st Century.'}"
2022-12-08 06:56:26 +00:00
]
},
"execution_count": 16,
2022-12-08 06:56:26 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"query = \"What did the president say about Justice Breyer\"\n",
2022-12-08 15:59:58 +00:00
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
2022-12-08 06:56:26 +00:00
]
},
{
"cell_type": "markdown",
"id": "f95dfb2e",
"metadata": {},
"source": [
"**Intermediate Steps**\n",
"\n",
"We can also return the intermediate steps for `refine` chains, should we want to inspect them. This is done with the `return_refine_steps` variable."
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "a5c64200",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"refine\", return_refine_steps=True)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "817546ac",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': ['\\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country and his legacy of excellence.',\n",
" '\\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice.',\n",
" '\\n\\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his support of the Equality Act and his commitment to protecting the rights of LGBTQ+ Americans.',\n",
" '\\n\\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his support of the Equality Act and his commitment to protecting the rights of LGBTQ+ Americans. He also praised Justice Breyer for his role in helping to pass the Bipartisan Infrastructure Law, which is the most sweeping investment to rebuild America in history.'],\n",
" 'output_text': '\\n\\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his support of the Equality Act and his commitment to protecting the rights of LGBTQ+ Americans. He also praised Justice Breyer for his role in helping to pass the Bipartisan Infrastructure Law, which is the most sweeping investment to rebuild America in history.'}"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "4f0bcae4",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "6664bda7",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': ['\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha reso omaggio al suo servizio.',\n",
" \"\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche. Ha anche sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione.\",\n",
" \"\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche. Ha anche sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere, la risoluzione del sistema di immigrazione, la protezione degli americani LGBTQ+ e l'approvazione dell'Equality Act. Ha inoltre sottolineato l'importanza di lavorare insieme per sconfiggere l'epidemia di oppiacei.\",\n",
" \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche. Ha anche sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere, la risoluzione del sistema di immigrazione, la protezione degli americani LGBTQ+ e l'approvazione dell'Equality Act. Ha inoltre sottolineato l'importanza di lavorare insieme per sconfiggere l'epidemia di oppiacei e per investire in America, educare gli americani, far crescere la forza lavoro e costruire l'economia dal\"],\n",
" 'output_text': \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche. Ha anche sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere, la risoluzione del sistema di immigrazione, la protezione degli americani LGBTQ+ e l'approvazione dell'Equality Act. Ha inoltre sottolineato l'importanza di lavorare insieme per sconfiggere l'epidemia di oppiacei e per investire in America, educare gli americani, far crescere la forza lavoro e costruire l'economia dal\"}"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"refine_prompt_template = (\n",
" \"The original question is as follows: {question}\\n\"\n",
" \"We have provided an existing answer: {existing_answer}\\n\"\n",
" \"We have the opportunity to refine the existing answer\"\n",
" \"(only if needed) with some more context below.\\n\"\n",
" \"------------\\n\"\n",
" \"{context_str}\\n\"\n",
" \"------------\\n\"\n",
" \"Given the new context, refine the original answer to better \"\n",
" \"answer the question. \"\n",
" \"If the context isn't useful, return the original answer. Reply in Italian.\"\n",
")\n",
"refine_prompt = PromptTemplate(\n",
" input_variables=[\"question\", \"existing_answer\", \"context_str\"],\n",
" template=refine_prompt_template,\n",
")\n",
"\n",
"\n",
"initial_qa_template = (\n",
" \"Context information is below. \\n\"\n",
" \"---------------------\\n\"\n",
" \"{context_str}\"\n",
" \"\\n---------------------\\n\"\n",
" \"Given the context information and not prior knowledge, \"\n",
" \"answer the question: {question}\\nYour answer should be in Italian.\\n\"\n",
")\n",
"initial_qa_prompt = PromptTemplate(\n",
" input_variables=[\"context_str\", \"question\"], template=initial_qa_template\n",
")\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"refine\", return_refine_steps=True,\n",
" question_prompt=initial_qa_prompt, refine_prompt=refine_prompt)\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "521a77cb",
"metadata": {},
"source": [
"## The `map-rerank` Chain\n",
"\n",
"This sections shows results of using the `map-rerank` Chain to do question answering with sources."
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "e2bfe203",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_rerank\", return_intermediate_steps=True)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "5c28880c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"query = \"What did the president say about Justice Breyer\"\n",
"results = chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "80ac2db3",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"' The President thanked Justice Breyer for his service and honored him for dedicating his life to serve the country.'"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"results[\"output_text\"]"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "b428fcb9",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"[{'answer': ' The President thanked Justice Breyer for his service and honored him for dedicating his life to serve the country.',\n",
" 'score': '100'},\n",
" {'answer': ' This document does not answer the question', 'score': '0'},\n",
" {'answer': ' This document does not answer the question', 'score': '0'},\n",
" {'answer': ' This document does not answer the question', 'score': '0'}]"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"results[\"intermediate_steps\"]"
]
},
{
"cell_type": "markdown",
"id": "5e47a818",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "41b83cd8",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': [{'answer': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese.',\n",
" 'score': '100'},\n",
" {'answer': ' Il presidente non ha detto nulla sulla Giustizia Breyer.',\n",
" 'score': '100'},\n",
" {'answer': ' Non so.', 'score': '0'},\n",
" {'answer': ' Non so.', 'score': '0'}],\n",
" 'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese.'}"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2023-03-12 00:41:03 +00:00
"from langchain.output_parsers import RegexParser\n",
"\n",
"output_parser = RegexParser(\n",
" regex=r\"(.*?)\\nScore: (.*)\",\n",
" output_keys=[\"answer\", \"score\"],\n",
")\n",
"\n",
"prompt_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.\n",
"\n",
"In addition to giving an answer, also return a score of how fully it answered the user's question. This should be in the following format:\n",
"\n",
"Question: [question here]\n",
"Helpful Answer In Italian: [answer here]\n",
"Score: [score between 0 and 100]\n",
"\n",
"Begin!\n",
"\n",
"Context:\n",
"---------\n",
"{context}\n",
"---------\n",
"Question: {question}\n",
"Helpful Answer In Italian:\"\"\"\n",
"PROMPT = PromptTemplate(\n",
" template=prompt_template,\n",
" input_variables=[\"context\", \"question\"],\n",
" output_parser=output_parser,\n",
")\n",
"\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_rerank\", return_intermediate_steps=True, prompt=PROMPT)\n",
"query = \"What did the president say about Justice Breyer\"\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e0f0bbdf",
"metadata": {},
"outputs": [],
"source": []
2022-12-08 06:56:26 +00:00
}
],
"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.10.9"
},
"vscode": {
"interpreter": {
"hash": "b1677b440931f40d89ef8be7bf03acb108ce003de0ac9b18e8d43753ea2e7103"
}
2022-12-08 06:56:26 +00:00
}
},
"nbformat": 4,
"nbformat_minor": 5
}