File size: 27,445 Bytes
acc4ffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
{
 "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](../combine_docs.md)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "726f4996",
   "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": 1,
   "id": "17fcbc0f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores import Chroma\n",
    "from langchain.docstore.document import Document\n",
    "from langchain.prompts import PromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "291f0117",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.document_loaders import TextLoader\n",
    "loader = TextLoader('../../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()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "fd9666a9",
   "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_documents(texts, embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d1eaf6e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What did the president say about Justice Breyer\"\n",
    "docs = docsearch.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a16e3453",
   "metadata": {},
   "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": 19,
   "id": "fd9e6190",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' The president said that he was honoring Justice Breyer for his service to the country and that he was a Constitutional scholar, Army veteran, and retiring Justice of the United States Supreme Court.'"
      ]
     },
     "execution_count": 19,
     "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f78787a0",
   "metadata": {},
   "source": [
    "## The `stuff` Chain\n",
    "\n",
    "This sections shows results of using the `stuff` Chain to do question answering."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "180fd4c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"stuff\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "77fdf1aa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': ' The president said that he was honoring Justice Breyer for his service to the country and that he was a Constitutional scholar, Army veteran, and retiring Justice of the United States Supreme Court.'}"
      ]
     },
     "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": "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": 7,
   "id": "5558c9e0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera come giudice della Corte Suprema degli Stati Uniti.'}"
      ]
     },
     "execution_count": 7,
     "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)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91522e29",
   "metadata": {},
   "source": [
    "## The `map_reduce` Chain\n",
    "\n",
    "This sections shows results of using the `map_reduce` Chain to do question answering."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b0060f51",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_reduce\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "fbdb9137",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'output_text': ' The president said, \"Justice Breyer, thank you for your service.\"'}"
      ]
     },
     "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": "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": 10,
   "id": "452c8680",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_map_steps=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "90b47a75",
   "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 said, \"Justice Breyer, thank you for your service.\"'}"
      ]
     },
     "execution_count": 11,
     "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": 13,
   "id": "af03a578",
   "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",
       "  '\\nNessun testo pertinente.',\n",
       "  \"\\nCome ho detto l'anno scorso, soprattutto ai nostri giovani americani transgender, avrò sempre il tuo sostegno come tuo Presidente, in modo che tu possa essere te stesso e raggiungere il tuo potenziale donato da Dio.\",\n",
       "  '\\nNella mia amministrazione, i guardiani sono stati accolti di nuovo. Stiamo andando dietro ai criminali che hanno rubato miliardi di dollari di aiuti di emergenza destinati alle piccole imprese e a milioni di americani. E stasera, annuncio che il Dipartimento di Giustizia nominerà un procuratore capo per la frode pandemica.'],\n",
       " 'output_text': ' Non conosco la risposta alla tua domanda su cosa abbia detto il Presidente riguardo al Giustizia Breyer.'}"
      ]
     },
     "execution_count": 13,
     "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)"
   ]
  },
  {
   "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",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ea50ad0",
   "metadata": {},
   "source": [
    "## The `refine` Chain\n",
    "\n",
    "This sections shows results of using the `refine` Chain to do question answering."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "fb167057",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"refine\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "d8b5286e",
   "metadata": {},
   "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 commitment to protecting the rights of LGBTQ+ Americans and his support for the bipartisan Equality Act. He also mentioned his plan to lower costs to give families a fair shot, lower the deficit, and go after criminals who stole pandemic relief funds. He also announced that the Justice Department will name a chief prosecutor for pandemic fraud.'}"
      ]
     },
     "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": "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": 14,
   "id": "a5c64200",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"refine\", return_refine_steps=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "817546ac",
   "metadata": {},
   "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",
       "  '\\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 commitment to protecting the rights of LGBTQ+ Americans and his support for the bipartisan Equality Act.',\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 commitment to protecting the rights of LGBTQ+ Americans and his support for the bipartisan Equality Act. He also mentioned his plan to lower costs to give families a fair shot, lower the deficit, and go after criminals who stole pandemic relief funds. He also announced that the Justice Department will name a chief prosecutor for pandemic fraud.'],\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 commitment to protecting the rights of LGBTQ+ Americans and his support for the bipartisan Equality Act. He also mentioned his plan to lower costs to give families a fair shot, lower the deficit, and go after criminals who stole pandemic relief funds. He also announced that the Justice Department will name a chief prosecutor for pandemic fraud.'}"
      ]
     },
     "execution_count": 15,
     "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": 14,
   "id": "6664bda7",
   "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. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito.',\n",
       "  \"\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani.\",\n",
       "  \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Ha inoltre sottolineato che la nomina di Justice Breyer è un passo importante verso l'uguaglianza per tutti gli americani, in partic\",\n",
       "  \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Ha inoltre sottolineato che la nomina di Justice Breyer è un passo importante verso l'uguaglianza per tutti gli americani, in partic\"],\n",
       " 'output_text': \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Ha inoltre sottolineato che la nomina di Justice Breyer è un passo importante verso l'uguaglianza per tutti gli americani, in partic\"}"
      ]
     },
     "execution_count": 14,
     "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": 16,
   "id": "e2bfe203",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_rerank\", return_intermediate_steps=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "5c28880c",
   "metadata": {},
   "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": 18,
   "id": "80ac2db3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' The president thanked Justice Breyer for his service and honored him for dedicating his life to serving the country. '"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results[\"output_text\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "b428fcb9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'answer': ' The president thanked Justice Breyer for his service and honored him for dedicating his life to serving the country. ',\n",
       "  'score': '100'},\n",
       " {'answer': \" The president said that Justice Breyer is 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 since she's been nominated, she's received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans, and that she is a consensus builder.\",\n",
       "  'score': '100'},\n",
       " {'answer': ' The president did not mention Justice Breyer in this context.',\n",
       "  'score': '0'},\n",
       " {'answer': ' The president did not mention Justice Breyer in the given context. ',\n",
       "  'score': '0'}]"
      ]
     },
     "execution_count": 19,
     "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": 16,
   "id": "41b83cd8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'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": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "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",
    "\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": []
  }
 ],
 "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
}