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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
{
 "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",
    "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",
    "    {\n",
    "        \"query\": \"What did the president say about Michael Jackson\",\n",
    "        \"answer\": \"Nothing\"\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b9c3fa75",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generated examples\n",
    "from langchain.evaluation.qa import QAGenerateChain\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",
    "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([f\"{k}={v['examples'][i]['value']:.4f}\" for k, v in eval_results.items()])\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
}