{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e78b7bb1",
   "metadata": {},
   "source": [
    "# Data Augmented Question Answering\n",
    "\n",
    "This notebook uses some generic prompts/language models to evaluate an question answering system that uses other sources of data besides what is in the model. For example, this can be used to evaluate a question answering system over your proprietary data.\n",
    "\n",
    "## Setup\n",
    "Let's set up an example with our favorite example - the state of the union address."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ab4a6931",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.vectorstores import Chroma\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.chains import RetrievalQA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4fdc211d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running Chroma using direct local API.\n",
      "Using DuckDB in-memory for database. Data will be transient.\n"
     ]
    }
   ],
   "source": [
    "from langchain.document_loaders import TextLoader\n",
    "\n",
    "loader = TextLoader(\"../../modules/state_of_the_union.txt\")\n",
    "documents = loader.load()\n",
    "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
    "texts = text_splitter.split_documents(documents)\n",
    "\n",
    "embeddings = OpenAIEmbeddings()\n",
    "docsearch = Chroma.from_documents(texts, embeddings)\n",
    "qa = RetrievalQA.from_llm(llm=OpenAI(), retriever=docsearch.as_retriever())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30fd72f2",
   "metadata": {},
   "source": [
    "## Examples\n",
    "Now we need some examples to evaluate. We can do this in two ways:\n",
    "\n",
    "1. Hard code some examples ourselves\n",
    "2. Generate examples automatically, using a language model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3459b001",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Hard-coded examples\n",
    "examples = [\n",
    "    {\n",
    "        \"query\": \"What did the president say about Ketanji Brown Jackson\",\n",
    "        \"answer\": \"He praised her legal ability and said he nominated her for the supreme court.\",\n",
    "    },\n",
    "    {\"query\": \"What did the president say about Michael Jackson\", \"answer\": \"Nothing\"},\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b9c3fa75",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generated examples\n",
    "from langchain.evaluation.qa import QAGenerateChain\n",
    "\n",
    "example_gen_chain = QAGenerateChain.from_llm(OpenAI())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c24543a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "new_examples = example_gen_chain.apply_and_parse([{\"doc\": t} for t in texts[:5]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a2d27560",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'query': 'According to the document, what did Vladimir Putin miscalculate?',\n",
       "  'answer': 'He miscalculated that he could roll into Ukraine and the world would roll over.'},\n",
       " {'query': 'Who is the Ukrainian Ambassador to the United States?',\n",
       "  'answer': 'The Ukrainian Ambassador to the United States is here tonight.'},\n",
       " {'query': 'How many countries were part of the coalition formed to confront Putin?',\n",
       "  'answer': '27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.'},\n",
       " {'query': 'What action is the U.S. Department of Justice taking to target Russian oligarchs?',\n",
       "  'answer': 'The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.'},\n",
       " {'query': 'How much direct assistance is the United States providing to Ukraine?',\n",
       "  'answer': 'The United States is providing more than $1 Billion in direct assistance to Ukraine.'}]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "558da6f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Combine examples\n",
    "examples += new_examples"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "443dc34e",
   "metadata": {},
   "source": [
    "## Evaluate\n",
    "Now that we have examples, we can use the question answering evaluator to evaluate our question answering chain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "782169a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.evaluation.qa import QAEvalChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "1bb77416",
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions = qa.apply(examples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "bcd0ad7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(temperature=0)\n",
    "eval_chain = QAEvalChain.from_llm(llm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2e6af79a",
   "metadata": {},
   "outputs": [],
   "source": [
    "graded_outputs = eval_chain.evaluate(examples, predictions)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "32fac2dc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Example 0:\n",
      "Question: What did the president say about Ketanji Brown Jackson\n",
      "Real Answer: He praised her legal ability and said he nominated her for the supreme court.\n",
      "Predicted Answer:  The president said that she is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by both Democrats and Republicans.\n",
      "Predicted Grade:  CORRECT\n",
      "\n",
      "Example 1:\n",
      "Question: What did the president say about Michael Jackson\n",
      "Real Answer: Nothing\n",
      "Predicted Answer:  The president did not mention Michael Jackson in this speech.\n",
      "Predicted Grade:  CORRECT\n",
      "\n",
      "Example 2:\n",
      "Question: According to the document, what did Vladimir Putin miscalculate?\n",
      "Real Answer: He miscalculated that he could roll into Ukraine and the world would roll over.\n",
      "Predicted Answer:  Putin miscalculated that the world would roll over when he rolled into Ukraine.\n",
      "Predicted Grade:  CORRECT\n",
      "\n",
      "Example 3:\n",
      "Question: Who is the Ukrainian Ambassador to the United States?\n",
      "Real Answer: The Ukrainian Ambassador to the United States is here tonight.\n",
      "Predicted Answer:  I don't know.\n",
      "Predicted Grade:  INCORRECT\n",
      "\n",
      "Example 4:\n",
      "Question: How many countries were part of the coalition formed to confront Putin?\n",
      "Real Answer: 27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.\n",
      "Predicted Answer:  The coalition included freedom-loving nations from Europe and the Americas to Asia and Africa, 27 members of the European Union including France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.\n",
      "Predicted Grade:  INCORRECT\n",
      "\n",
      "Example 5:\n",
      "Question: What action is the U.S. Department of Justice taking to target Russian oligarchs?\n",
      "Real Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.\n",
      "Predicted Answer:  The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and to find and seize their yachts, luxury apartments, and private jets.\n",
      "Predicted Grade:  INCORRECT\n",
      "\n",
      "Example 6:\n",
      "Question: How much direct assistance is the United States providing to Ukraine?\n",
      "Real Answer: The United States is providing more than $1 Billion in direct assistance to Ukraine.\n",
      "Predicted Answer:  The United States is providing more than $1 billion in direct assistance to Ukraine.\n",
      "Predicted Grade:  CORRECT\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for i, eg in enumerate(examples):\n",
    "    print(f\"Example {i}:\")\n",
    "    print(\"Question: \" + predictions[i][\"query\"])\n",
    "    print(\"Real Answer: \" + predictions[i][\"answer\"])\n",
    "    print(\"Predicted Answer: \" + predictions[i][\"result\"])\n",
    "    print(\"Predicted Grade: \" + graded_outputs[i][\"text\"])\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50a9e845",
   "metadata": {},
   "source": [
    "## Evaluate with Other Metrics\n",
    "\n",
    "In addition to predicting whether the answer is correct or incorrect using a language model, we can also use other metrics to get a more nuanced view on the quality of the answers. To do so, we can use the [Critique](https://docs.inspiredco.ai/critique/) library, which allows for simple calculation of various metrics over generated text.\n",
    "\n",
    "First you can get an API key from the [Inspired Cognition Dashboard](https://dashboard.inspiredco.ai) and do some setup:\n",
    "\n",
    "```bash\n",
    "export INSPIREDCO_API_KEY=\"...\"\n",
    "pip install inspiredco\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "bd0b01dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspiredco.critique\n",
    "import os\n",
    "\n",
    "critique = inspiredco.critique.Critique(api_key=os.environ[\"INSPIREDCO_API_KEY\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f52629e",
   "metadata": {},
   "source": [
    "Then run the following code to set up the configuration and calculate the [ROUGE](https://docs.inspiredco.ai/critique/metric_rouge.html), [chrf](https://docs.inspiredco.ai/critique/metric_chrf.html), [BERTScore](https://docs.inspiredco.ai/critique/metric_bert_score.html), and [UniEval](https://docs.inspiredco.ai/critique/metric_uni_eval.html) (you can choose [other metrics](https://docs.inspiredco.ai/critique/metrics.html) too):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "84a0ba21",
   "metadata": {},
   "outputs": [],
   "source": [
    "metrics = {\n",
    "    \"rouge\": {\n",
    "        \"metric\": \"rouge\",\n",
    "        \"config\": {\"variety\": \"rouge_l\"},\n",
    "    },\n",
    "    \"chrf\": {\n",
    "        \"metric\": \"chrf\",\n",
    "        \"config\": {},\n",
    "    },\n",
    "    \"bert_score\": {\n",
    "        \"metric\": \"bert_score\",\n",
    "        \"config\": {\"model\": \"bert-base-uncased\"},\n",
    "    },\n",
    "    \"uni_eval\": {\n",
    "        \"metric\": \"uni_eval\",\n",
    "        \"config\": {\"task\": \"summarization\", \"evaluation_aspect\": \"relevance\"},\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "3b9a4056",
   "metadata": {},
   "outputs": [],
   "source": [
    "critique_data = [\n",
    "    {\"target\": pred[\"result\"], \"references\": [pred[\"answer\"]]} for pred in predictions\n",
    "]\n",
    "eval_results = {\n",
    "    k: critique.evaluate(dataset=critique_data, metric=v[\"metric\"], config=v[\"config\"])\n",
    "    for k, v in metrics.items()\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f0ae799",
   "metadata": {},
   "source": [
    "Finally, we can print out the results. We can see that overall the scores are higher when the output is semantically correct, and also when the output closely matches with the gold-standard answer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "b51edcf4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Example 0:\n",
      "Question: What did the president say about Ketanji Brown Jackson\n",
      "Real Answer: He praised her legal ability and said he nominated her for the supreme court.\n",
      "Predicted Answer:  The president said that she is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by both Democrats and Republicans.\n",
      "Predicted Scores: rouge=0.0941, chrf=0.2001, bert_score=0.5219, uni_eval=0.9043\n",
      "\n",
      "Example 1:\n",
      "Question: What did the president say about Michael Jackson\n",
      "Real Answer: Nothing\n",
      "Predicted Answer:  The president did not mention Michael Jackson in this speech.\n",
      "Predicted Scores: rouge=0.0000, chrf=0.1087, bert_score=0.3486, uni_eval=0.7802\n",
      "\n",
      "Example 2:\n",
      "Question: According to the document, what did Vladimir Putin miscalculate?\n",
      "Real Answer: He miscalculated that he could roll into Ukraine and the world would roll over.\n",
      "Predicted Answer:  Putin miscalculated that the world would roll over when he rolled into Ukraine.\n",
      "Predicted Scores: rouge=0.5185, chrf=0.6955, bert_score=0.8421, uni_eval=0.9578\n",
      "\n",
      "Example 3:\n",
      "Question: Who is the Ukrainian Ambassador to the United States?\n",
      "Real Answer: The Ukrainian Ambassador to the United States is here tonight.\n",
      "Predicted Answer:  I don't know.\n",
      "Predicted Scores: rouge=0.0000, chrf=0.0375, bert_score=0.3159, uni_eval=0.7493\n",
      "\n",
      "Example 4:\n",
      "Question: How many countries were part of the coalition formed to confront Putin?\n",
      "Real Answer: 27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.\n",
      "Predicted Answer:  The coalition included freedom-loving nations from Europe and the Americas to Asia and Africa, 27 members of the European Union including France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.\n",
      "Predicted Scores: rouge=0.7419, chrf=0.8602, bert_score=0.8388, uni_eval=0.0669\n",
      "\n",
      "Example 5:\n",
      "Question: What action is the U.S. Department of Justice taking to target Russian oligarchs?\n",
      "Real Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.\n",
      "Predicted Answer:  The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and to find and seize their yachts, luxury apartments, and private jets.\n",
      "Predicted Scores: rouge=0.9412, chrf=0.8687, bert_score=0.9607, uni_eval=0.9718\n",
      "\n",
      "Example 6:\n",
      "Question: How much direct assistance is the United States providing to Ukraine?\n",
      "Real Answer: The United States is providing more than $1 Billion in direct assistance to Ukraine.\n",
      "Predicted Answer:  The United States is providing more than $1 billion in direct assistance to Ukraine.\n",
      "Predicted Scores: rouge=1.0000, chrf=0.9483, bert_score=1.0000, uni_eval=0.9734\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for i, eg in enumerate(examples):\n",
    "    score_string = \", \".join(\n",
    "        [f\"{k}={v['examples'][i]['value']:.4f}\" for k, v in eval_results.items()]\n",
    "    )\n",
    "    print(f\"Example {i}:\")\n",
    "    print(\"Question: \" + predictions[i][\"query\"])\n",
    "    print(\"Real Answer: \" + predictions[i][\"answer\"])\n",
    "    print(\"Predicted Answer: \" + predictions[i][\"result\"])\n",
    "    print(\"Predicted Scores: \" + score_string)\n",
    "    print()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
