{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "74148cee",
   "metadata": {},
   "source": [
    "# Question Answering with Sources\n",
    "\n",
    "This notebook walks through how to use LangChain for question answering with sources over a list of documents. It covers four different chain types: `stuff`, `map_reduce`, `refine`,`map-rerank`. For a more in depth explanation of what these chain types are, see [here](../combine_docs.md)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca2f0efc",
   "metadata": {},
   "source": [
    "## Prepare Data\n",
    "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": 4,
   "id": "78f28130",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.embeddings.cohere import CohereEmbeddings\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores.elastic_vector_search import ElasticVectorSearch\n",
    "from langchain.vectorstores import Chroma\n",
    "from langchain.docstore.document import Document\n",
    "from langchain.prompts import PromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4da195a3",
   "metadata": {},
   "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()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5ec2b55b",
   "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": [
    "docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{\"source\": str(i)} for i in range(len(texts))])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5286f58f",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What did the president say about Justice Breyer\"\n",
    "docs = docsearch.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "005a47e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains.qa_with_sources import load_qa_with_sources_chain\n",
    "from langchain.llms import OpenAI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b119026",
   "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": 9,
   "id": "3722373b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': ' The president thanked Justice Breyer for his service.\\nSOURCES: 30-pl'}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"stuff\")\n",
    "query = \"What did the president say about Justice Breyer\"\n",
    "chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdaf9268",
   "metadata": {},
   "source": [
    "If you want more control and understanding over what is happening, please see the information below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d82f899a",
   "metadata": {},
   "source": [
    "## The `stuff` Chain\n",
    "\n",
    "This sections shows results of using the `stuff` Chain to do question answering with sources."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fc1a5ed6",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"stuff\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7d766417",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': ' The president thanked Justice Breyer for his service.\\nSOURCES: 30-pl'}"
      ]
     },
     "execution_count": 7,
     "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": "e966aea8",
   "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": 7,
   "id": "426c570b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': '\\nNon so cosa abbia detto il presidente riguardo a Justice Breyer.\\nSOURCES: 30, 31, 33'}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "template = \"\"\"Given the following extracted parts of a long document and a question, create a final answer with references (\"SOURCES\"). \n",
    "If you don't know the answer, just say that you don't know. Don't try to make up an answer.\n",
    "ALWAYS return a \"SOURCES\" part in your answer.\n",
    "Respond in Italian.\n",
    "\n",
    "QUESTION: {question}\n",
    "=========\n",
    "{summaries}\n",
    "=========\n",
    "FINAL ANSWER IN ITALIAN:\"\"\"\n",
    "PROMPT = PromptTemplate(template=template, input_variables=[\"summaries\", \"question\"])\n",
    "\n",
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"stuff\", 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": "markdown",
   "id": "c5dbb304",
   "metadata": {},
   "source": [
    "## The `map_reduce` Chain\n",
    "\n",
    "This sections shows results of using the `map_reduce` Chain to do question answering with sources."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "921db0a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"map_reduce\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e417926a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': ' The president thanked Justice Breyer for his service.\\nSOURCES: 30-pl'}"
      ]
     },
     "execution_count": 9,
     "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": "ae2f6d97",
   "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": 16,
   "id": "15af265f",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_intermediate_steps=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "21b136e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intermediate_steps': [' \"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",
       "  ' None',\n",
       "  ' None',\n",
       "  ' None'],\n",
       " 'output_text': ' The president thanked Justice Breyer for his service.\\nSOURCES: 30-pl'}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d56e101a",
   "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": 8,
   "id": "47f0d517",
   "metadata": {},
   "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",
       "  ' Non pertinente.',\n",
       "  ' Non rilevante.',\n",
       "  \" Non c'è testo pertinente.\"],\n",
       " 'output_text': ' Non conosco la risposta. SOURCES: 30, 31, 33, 20.'}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "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 in 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 with references (\"SOURCES\"). \n",
    "If you don't know the answer, just say that you don't know. Don't try to make up an answer.\n",
    "ALWAYS return a \"SOURCES\" part in your answer.\n",
    "Respond in Italian.\n",
    "\n",
    "QUESTION: {question}\n",
    "=========\n",
    "{summaries}\n",
    "=========\n",
    "FINAL ANSWER IN ITALIAN:\"\"\"\n",
    "COMBINE_PROMPT = PromptTemplate(\n",
    "    template=combine_prompt_template, input_variables=[\"summaries\", \"question\"]\n",
    ")\n",
    "\n",
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_intermediate_steps=True, question_prompt=QUESTION_PROMPT, combine_prompt=COMBINE_PROMPT)\n",
    "chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d943c6c1",
   "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",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bf0e1ab",
   "metadata": {},
   "source": [
    "## The `refine` Chain\n",
    "\n",
    "This sections shows results of using the `refine` Chain to do question answering with sources."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "904835c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"refine\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f60875c6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': \"\\n\\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked him for his service and praised his career as a top litigator in private practice, a former federal public defender, and a family of public school educators and police officers. He noted Justice Breyer's reputation as a consensus builder and the broad range of support he has received from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. He also highlighted the importance of securing the border and fixing the immigration system in order to advance liberty and justice, and mentioned the new technology, joint patrols, dedicated immigration judges, and commitments to support partners in South and Central America that have been put in place. He also expressed his commitment to the LGBTQ+ community, noting the need for the bipartisan Equality Act and the importance of protecting transgender Americans from state laws targeting them. He also highlighted his commitment to bipartisanship, noting the 80 bipartisan bills he signed into law last year, and his plans to strengthen the Violence Against Women Act. Additionally, he announced that the Justice Department will name a chief prosecutor for pandemic fraud and his plan to lower the deficit by more than one trillion dollars in a\"}"
      ]
     },
     "execution_count": 13,
     "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": "ac357530",
   "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_intermediate_steps` variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "3396a773",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"refine\", return_intermediate_steps=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "be5739ef",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intermediate_steps': ['\\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service.',\n",
       "  '\\n\\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and a family of public school educators and police officers. He praised Justice Breyer for being a consensus builder and for receiving a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. He also noted that in order to advance liberty and justice, it was necessary to secure the border and fix the immigration system, and that the government was taking steps to do both. \\n\\nSource: 31',\n",
       "  '\\n\\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and a family of public school educators and police officers. He praised Justice Breyer for being a consensus builder and for receiving a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. He also noted that in order to advance liberty and justice, it was necessary to secure the border and fix the immigration system, and that the government was taking steps to do both. He also mentioned the need to pass the bipartisan Equality Act to protect LGBTQ+ Americans, and to strengthen the Violence Against Women Act that he had written three decades ago. \\n\\nSource: 31, 33',\n",
       "  '\\n\\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and a family of public school educators and police officers. He praised Justice Breyer for being a consensus builder and for receiving a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. He also noted that in order to advance liberty and justice, it was necessary to secure the border and fix the immigration system, and that the government was taking steps to do both. He also mentioned the need to pass the bipartisan Equality Act to protect LGBTQ+ Americans, and to strengthen the Violence Against Women Act that he had written three decades ago. Additionally, he mentioned his plan to lower costs to give families a fair shot, lower the deficit, and go after criminals who stole billions in relief money meant for small businesses and millions of Americans. He also announced that the Justice Department will name a chief prosecutor for pandemic fraud. \\n\\nSource: 20, 31, 33'],\n",
       " 'output_text': '\\n\\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and a family of public school educators and police officers. He praised Justice Breyer for being a consensus builder and for receiving a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. He also noted that in order to advance liberty and justice, it was necessary to secure the border and fix the immigration system, and that the government was taking steps to do both. He also mentioned the need to pass the bipartisan Equality Act to protect LGBTQ+ Americans, and to strengthen the Violence Against Women Act that he had written three decades ago. Additionally, he mentioned his plan to lower costs to give families a fair shot, lower the deficit, and go after criminals who stole billions in relief money meant for small businesses and millions of Americans. He also announced that the Justice Department will name a chief prosecutor for pandemic fraud. \\n\\nSource: 20, 31, 33'}"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf08c8a1",
   "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": "97e33bd9",
   "metadata": {},
   "outputs": [],
   "source": [
    "refine_template = (\n",
    "    \"The original question is as follows: {question}\\n\"\n",
    "    \"We have provided an existing answer, including sources: {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 (in Italian)\"\n",
    "    \"If you do update it, please update the sources as well. \"\n",
    "    \"If the context isn't useful, return the original answer.\"\n",
    ")\n",
    "refine_prompt = PromptTemplate(\n",
    "    input_variables=[\"question\", \"existing_answer\", \"context_str\"],\n",
    "    template=refine_template,\n",
    ")\n",
    "\n",
    "\n",
    "question_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 in Italian: {question}\\n\"\n",
    ")\n",
    "question_prompt = PromptTemplate(\n",
    "    input_variables=[\"context_str\", \"question\"], template=question_template\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "41565992",
   "metadata": {},
   "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 onorato la sua carriera.',\n",
       "  \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\",\n",
       "  \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\",\n",
       "  \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\"],\n",
       " 'output_text': \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\"}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"refine\", return_intermediate_steps=True, question_prompt=question_prompt, refine_prompt=refine_prompt)\n",
    "chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07ff756e",
   "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": 10,
   "id": "46b52ef9",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"map_rerank\", metadata_keys=['source'], return_intermediate_steps=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7ce2da04",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What did the president say about Justice Breyer\"\n",
    "result = chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "cbdcd3c5",
   "metadata": {},
   "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": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result[\"output_text\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "6f0b3d03",
   "metadata": {},
   "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": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result[\"intermediate_steps\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b94bfeb6",
   "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": 11,
   "id": "cb46ba3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts.base 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",
    "chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"map_rerank\", metadata_keys=['source'], return_intermediate_steps=True, prompt=PROMPT)\n",
    "query = \"What did the president say about Justice Breyer\"\n",
    "result = chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "fee7b055",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'source': 30,\n",
       " 'intermediate_steps': [{'answer': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera.',\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': ' Il presidente non ha detto nulla sulla giustizia Breyer.',\n",
       "   'score': '100'}],\n",
       " 'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera.'}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a51c987",
   "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"
  },
  "vscode": {
   "interpreter": {
    "hash": "b1677b440931f40d89ef8be7bf03acb108ce003de0ac9b18e8d43753ea2e7103"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}