File size: 30,921 Bytes
120efdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "1a305246-59d9-453e-9903-ca462611f1eb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Product</th>\n",
       "      <th>Review</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Queen Size sheet Set</td>\n",
       "      <td>I ordered a king size set.</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Waterproof Phone Pcuch</td>\n",
       "      <td>I loved the waterproof sac</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Luxury Air Mattress</td>\n",
       "      <td>This mattress had a small hole in the top</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Pillows Insert</td>\n",
       "      <td>this is the best pillow filters on amazon</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Milk Frother Handheld\\nm</td>\n",
       "      <td>I loved this product But they only seem to I</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                    Product                                         Review\n",
       "0      Queen Size sheet Set                     I ordered a king size set.\n",
       "1    Waterproof Phone Pcuch                     I loved the waterproof sac\n",
       "2       Luxury Air Mattress      This mattress had a small hole in the top\n",
       "3            Pillows Insert      this is the best pillow filters on amazon\n",
       "4  Milk Frother Handheld\\nm   I loved this product But they only seem to I"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import openai\n",
    "import os\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv())\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv('Data.csv')\n",
    "df.head()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "8f75bedd-2b00-466a-a00f-bc7c47f2f7a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.prompts import ChatPromptTemplate\n",
    "from langchain.chains import LLMChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "edc76aa3-1d1f-41d2-93a9-8297268817ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = ChatOpenAI(temperature=0.9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "27f2d3c9-9601-4b31-8d35-bae9538ee2a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prompt template 1\n",
    "prompt = ChatPromptTemplate.from_template(\"what is the best name to describe a company that make {product}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "03ef9080-77ba-4406-a402-e4d5b889be47",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Chain 1\n",
    "chain = LLMChain(llm=llm, prompt=prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "0a172ea1-18ce-407b-bcd9-b4146c5f5610",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1. Royal Comfort Linens\\n2. Majestic Bedding Co.\\n3. Crowned Sleep Essentials\\n4. Regal Dreams Bedding\\n5. Luxurious Queen Linens\\n6. Elite Serenity Bedding\\n7. Imperial Queen Bedding\\n8. Opulence Bed Linens\\n9. Grandeur Sleep Essentials\\n10. Prestige Queen Linens'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "product = \"Queen Size Sheet Set\"\n",
    "chain.run(product)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "b0ff950c-1c09-4ba5-8661-626fb69b24ca",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n",
      "\u001b[36;1m\u001b[1;3mRoyal Comfort Linens\u001b[0m\n",
      "\u001b[33;1m\u001b[1;3mRoyal Comfort Linens is a luxurious bedding company that offers high-quality and stylish linens for a truly regal sleep experience.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Royal Comfort Linens is a luxurious bedding company that offers high-quality and stylish linens for a truly regal sleep experience.'"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.chains import SimpleSequentialChain\n",
    "# Prompt Template 2\n",
    "prompt_2 = ChatPromptTemplate.from_template(\"Write a 20 words description for the following company: {company_name}\")\n",
    "\n",
    "# chain 2\n",
    "chain_two = LLMChain(llm=llm, prompt=prompt_2)\n",
    "\n",
    "overall_simple_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True)\n",
    "overall_simple_chain.run(product)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "8ab602a8-9871-4881-b3eb-fbc1e9a90e08",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains import SequentialChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "7101b29c-cc62-48ed-925c-962c9da6c40b",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_model = 'gpt-3.5-turbo'\n",
    "llm = ChatOpenAI(temperature=0.9, model=llm_model)\n",
    "\n",
    "# prompt template 1: translate to english\n",
    "first_prompt = ChatPromptTemplate.from_template(\n",
    "    \"Translate the following review to english:\"\n",
    "    \"\\n\\n{Review}\"\n",
    ")\n",
    "# chain 1: input= Review and output= English_Review\n",
    "chain_one = LLMChain(llm=llm, prompt=first_prompt, \n",
    "                     output_key=\"English_Review\"\n",
    "                    )\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "cd8f164e-e91e-4fa5-a27a-40714aacdc32",
   "metadata": {},
   "outputs": [],
   "source": [
    "second_prompt = ChatPromptTemplate.from_template(\n",
    "    \"Can you summarize the following review in 1 sentence:\"\n",
    "    \"\\n\\n{English_Review}\"\n",
    ")\n",
    "# chain 2: input= English_Review and output= summary\n",
    "chain_two = LLMChain(llm=llm, prompt=second_prompt, \n",
    "                     output_key=\"summary\"\n",
    "                    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "6a77ec8a-d5da-4889-9803-1676a03d046b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# prompt template 3: translate to english\n",
    "third_prompt = ChatPromptTemplate.from_template(\n",
    "    \"What language is the following review:\\n\\n{Review}\"\n",
    ")\n",
    "# chain 3: input= Review and output= language\n",
    "chain_three = LLMChain(llm=llm, prompt=third_prompt,\n",
    "                       output_key=\"language\"\n",
    "                      )\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "5fd5d216-74f1-4c73-9ba5-008a57398d65",
   "metadata": {},
   "outputs": [],
   "source": [
    "# prompt template 4: follow up message\n",
    "fourth_prompt = ChatPromptTemplate.from_template(\n",
    "    \"Write a follow up response to the following \"\n",
    "    \"summary in the specified language:\"\n",
    "    \"\\n\\nSummary: {summary}\\n\\nLanguage: {language}\"\n",
    ")\n",
    "# chain 4: input= summary, language and output= followup_message\n",
    "chain_four = LLMChain(llm=llm, prompt=fourth_prompt,\n",
    "                      output_key=\"followup_message\"\n",
    "                     )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "6217843a-4244-48da-8622-0f753984a8f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# overall_chain: input= Review \n",
    "# and output= English_Review,summary, followup_message\n",
    "overall_chain = SequentialChain(\n",
    "    chains=[chain_one, chain_two, chain_three, chain_four],\n",
    "    input_variables=[\"Review\"],\n",
    "    output_variables=[\"English_Review\", \"summary\",\"followup_message\"],\n",
    "    verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "2c58c69a-e943-4257-a61c-579ca6eb8f4f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new SequentialChain chain...\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'Review': ' this is the best pillow filters on amazon',\n",
       " 'English_Review': 'Este es el mejor filtro de almohadas en Amazon.',\n",
       " 'summary': 'This is the best pillow filter on Amazon.',\n",
       " 'followup_message': \"Response: Thank you for your review! We appreciate your feedback and we're glad to hear that you think our pillow filter is the best on Amazon. We strive to provide high-quality products to our customers, and your satisfaction is our top priority. If you have any further questions or need assistance, please don't hesitate to reach out.\"}"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "review = df.Review[3]\n",
    "overall_chain(review)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "c5f9c68b-020b-418a-842f-f2c32f958389",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Product</th>\n",
       "      <th>Review</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Queen Size sheet Set</td>\n",
       "      <td>I ordered a king size set.</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Waterproof Phone Pcuch</td>\n",
       "      <td>I loved the waterproof sac</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Luxury Air Mattress</td>\n",
       "      <td>This mattress had a small hole in the top</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Pillows Insert</td>\n",
       "      <td>this is the best pillow filters on amazon</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Milk Frother Handheld\\nm</td>\n",
       "      <td>I loved this product But they only seem to I</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                    Product                                         Review\n",
       "0      Queen Size sheet Set                     I ordered a king size set.\n",
       "1    Waterproof Phone Pcuch                     I loved the waterproof sac\n",
       "2       Luxury Air Mattress      This mattress had a small hole in the top\n",
       "3            Pillows Insert      this is the best pillow filters on amazon\n",
       "4  Milk Frother Handheld\\nm   I loved this product But they only seem to I"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "27355bcf-2787-470d-a41a-ea5b5565a68a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0        Queen Size sheet Set\n",
       "1      Waterproof Phone Pcuch\n",
       "2         Luxury Air Mattress\n",
       "3              Pillows Insert\n",
       "4    Milk Frother Handheld\\nm\n",
       "Name: Product, dtype: object"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['Product']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "8de4ae55-2cab-43fd-a2e9-542157919cbb",
   "metadata": {},
   "outputs": [],
   "source": [
    "physics_template = \"\"\"You are a very smart physics professor. \\\n",
    "You are great at answering questions about physics in a concise\\\n",
    "and easy to understand manner. \\\n",
    "When you don't know the answer to a question you admit\\\n",
    "that you don't know.\n",
    "\n",
    "Here is a question:\n",
    "{input}\"\"\"\n",
    "\n",
    "\n",
    "math_template = \"\"\"You are a very good mathematician. \\\n",
    "You are great at answering math questions. \\\n",
    "You are so good because you are able to break down \\\n",
    "hard problems into their component parts, \n",
    "answer the component parts, and then put them together\\\n",
    "to answer the broader question.\n",
    "\n",
    "Here is a question:\n",
    "{input}\"\"\"\n",
    "\n",
    "history_template = \"\"\"You are a very good historian. \\\n",
    "You have an excellent knowledge of and understanding of people,\\\n",
    "events and contexts from a range of historical periods. \\\n",
    "You have the ability to think, reflect, debate, discuss and \\\n",
    "evaluate the past. You have a respect for historical evidence\\\n",
    "and the ability to make use of it to support your explanations \\\n",
    "and judgements.\n",
    "\n",
    "Here is a question:\n",
    "{input}\"\"\"\n",
    "\n",
    "\n",
    "computerscience_template = \"\"\" You are a successful computer scientist.\\\n",
    "You have a passion for creativity, collaboration,\\\n",
    "forward-thinking, confidence, strong problem-solving capabilities,\\\n",
    "understanding of theories and algorithms, and excellent communication \\\n",
    "skills. You are great at answering coding questions. \\\n",
    "You are so good because you know how to solve a problem by \\\n",
    "describing the solution in imperative steps \\\n",
    "that a machine can easily interpret and you know how to \\\n",
    "choose a solution that has a good balance between \\\n",
    "time complexity and space complexity. \n",
    "\n",
    "Here is a question:\n",
    "{input}\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "ec18c579-c130-490f-ad56-a2acd4f8bd60",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_infos = [\n",
    "    {\n",
    "        \"name\": \"physics\", \n",
    "        \"description\": \"Good for answering questions about physics\", \n",
    "        \"prompt_template\": physics_template\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"math\", \n",
    "        \"description\": \"Good for answering math questions\", \n",
    "        \"prompt_template\": math_template\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"History\", \n",
    "        \"description\": \"Good for answering history questions\", \n",
    "        \"prompt_template\": history_template\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"computer science\", \n",
    "        \"description\": \"Good for answering computer science questions\", \n",
    "        \"prompt_template\": computerscience_template\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "b38acbf5-d22c-4951-b2e0-c2beed545474",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains.router import MultiPromptChain\n",
    "from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "llm = ChatOpenAI(temperature=0, model=llm_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "eecb95b3-38ed-4433-a918-8febfe1945d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "destination_chains = {}\n",
    "for p_info in prompt_infos:\n",
    "    name = p_info[\"name\"]\n",
    "    prompt_template = p_info[\"prompt_template\"]\n",
    "    prompt = ChatPromptTemplate.from_template(template=prompt_template)\n",
    "    chain = LLMChain(llm=llm, prompt=prompt)\n",
    "    destination_chains[name] = chain  \n",
    "    \n",
    "destinations = [f\"{p['name']}: {p['description']}\" for p in prompt_infos]\n",
    "destinations_str = \"\\n\".join(destinations)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "228a3439-008d-47cd-ac10-fca1eccba51c",
   "metadata": {},
   "outputs": [],
   "source": [
    "default_prompt = ChatPromptTemplate.from_template(\"{input}\")\n",
    "default_chain = LLMChain(llm=llm, prompt=default_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "8b393708-04d1-40ab-a8ed-a1862d00b326",
   "metadata": {},
   "outputs": [],
   "source": [
    "MULTI_PROMPT_ROUTER_TEMPLATE = \"\"\"Given a raw text input to a \\\n",
    "language model select the model prompt best suited for the input. \\\n",
    "You will be given the names of the available prompts and a \\\n",
    "description of what the prompt is best suited for. \\\n",
    "You may also revise the original input if you think that revising\\\n",
    "it will ultimately lead to a better response from the language model.\n",
    "\n",
    "<< FORMATTING >>\n",
    "Return a markdown code snippet with a JSON object formatted to look like:\n",
    "```json\n",
    "{{{{\n",
    "    \"destination\": string \\ name of the prompt to use or \"DEFAULT\"\n",
    "    \"next_inputs\": string \\ a potentially modified version of the original input\n",
    "}}}}\n",
    "```\n",
    "\n",
    "REMEMBER: \"destination\" MUST be one of the candidate prompt \\\n",
    "names specified below OR it can be \"DEFAULT\" if the input is not\\\n",
    "well suited for any of the candidate prompts.\n",
    "REMEMBER: \"next_inputs\" can just be the original input \\\n",
    "if you don't think any modifications are needed.\n",
    "\n",
    "<< CANDIDATE PROMPTS >>\n",
    "{destinations}\n",
    "\n",
    "<< INPUT >>\n",
    "{{input}}\n",
    "\n",
    "<< OUTPUT (remember to include the ```json)>>\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "2f40b20c-89ed-4217-9176-60a9ab5d45d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(\n",
    "    destinations=destinations_str\n",
    ")\n",
    "router_prompt = PromptTemplate(\n",
    "    template=router_template,\n",
    "    input_variables=[\"input\"],\n",
    "    output_parser=RouterOutputParser(),\n",
    ")\n",
    "\n",
    "router_chain = LLMRouterChain.from_llm(llm, router_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "f89d7a92-3696-4fb9-890a-36f5bd6d3752",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = MultiPromptChain(router_chain=router_chain, \n",
    "                         destination_chains=destination_chains, \n",
    "                         default_chain=default_chain, verbose=True\n",
    "                        )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "449208c8-2b58-4770-bb45-ae3c0778b432",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/sushantgo/Downloads/conda/lib/python3.11/site-packages/langchain/chains/llm.py:280: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "physics: {'input': 'What is black body radiation?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Black body radiation refers to the electromagnetic radiation emitted by an object that absorbs all incident radiation and reflects or transmits none. It is called \"black body\" because it absorbs all wavelengths of light, appearing black at room temperature. \\n\\nAccording to Planck\\'s law, black body radiation is characterized by a continuous spectrum of wavelengths and intensities, which depend on the temperature of the object. As the temperature increases, the peak intensity of the radiation shifts to shorter wavelengths, resulting in a change in color from red to orange, yellow, white, and eventually blue at very high temperatures.\\n\\nBlack body radiation is a fundamental concept in physics and has various applications, including understanding the behavior of stars, explaining the cosmic microwave background radiation, and developing technologies like incandescent light bulbs and thermal imaging devices.'"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.run(\"What is black body radiation?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "5c204f5e-5d20-4061-b08c-ad61999d3107",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "math: {'input': 'what is 2 + 2'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"Thank you for your kind words! As a mathematician, I am happy to help with any math questions, no matter how simple or complex they may be.\\n\\nNow, let's solve the problem at hand. The question is asking for the sum of 2 and 2. To find the answer, we can simply add the two numbers together:\\n\\n2 + 2 = 4\\n\\nTherefore, the sum of 2 and 2 is 4.\""
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.run(\"what is 2 + 2\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "60de9868-1821-414e-9564-3847c62dbef9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "biology: {'input': 'Why does every cell in our body contain DNA?'}"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "Received invalid destination chain name 'biology'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[59], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mchain\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mWhy does every cell in our body contain DNA?\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m~/Downloads/conda/lib/python3.11/site-packages/langchain/chains/base.py:487\u001b[0m, in \u001b[0;36mChain.run\u001b[0;34m(self, callbacks, tags, metadata, *args, **kwargs)\u001b[0m\n\u001b[1;32m    485\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(args) \u001b[38;5;241m!=\u001b[39m \u001b[38;5;241m1\u001b[39m:\n\u001b[1;32m    486\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m`run` supports only one positional argument.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 487\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43margs\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcallbacks\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmetadata\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmetadata\u001b[49m\u001b[43m)\u001b[49m[\n\u001b[1;32m    488\u001b[0m         _output_key\n\u001b[1;32m    489\u001b[0m     ]\n\u001b[1;32m    491\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m kwargs \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m args:\n\u001b[1;32m    492\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m(kwargs, callbacks\u001b[38;5;241m=\u001b[39mcallbacks, tags\u001b[38;5;241m=\u001b[39mtags, metadata\u001b[38;5;241m=\u001b[39mmetadata)[\n\u001b[1;32m    493\u001b[0m         _output_key\n\u001b[1;32m    494\u001b[0m     ]\n",
      "File \u001b[0;32m~/Downloads/conda/lib/python3.11/site-packages/langchain/chains/base.py:292\u001b[0m, in \u001b[0;36mChain.__call__\u001b[0;34m(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)\u001b[0m\n\u001b[1;32m    290\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m    291\u001b[0m     run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n\u001b[0;32m--> 292\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m e\n\u001b[1;32m    293\u001b[0m run_manager\u001b[38;5;241m.\u001b[39mon_chain_end(outputs)\n\u001b[1;32m    294\u001b[0m final_outputs: Dict[\u001b[38;5;28mstr\u001b[39m, Any] \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mprep_outputs(\n\u001b[1;32m    295\u001b[0m     inputs, outputs, return_only_outputs\n\u001b[1;32m    296\u001b[0m )\n",
      "File \u001b[0;32m~/Downloads/conda/lib/python3.11/site-packages/langchain/chains/base.py:286\u001b[0m, in \u001b[0;36mChain.__call__\u001b[0;34m(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)\u001b[0m\n\u001b[1;32m    279\u001b[0m run_manager \u001b[38;5;241m=\u001b[39m callback_manager\u001b[38;5;241m.\u001b[39mon_chain_start(\n\u001b[1;32m    280\u001b[0m     dumpd(\u001b[38;5;28mself\u001b[39m),\n\u001b[1;32m    281\u001b[0m     inputs,\n\u001b[1;32m    282\u001b[0m     name\u001b[38;5;241m=\u001b[39mrun_name,\n\u001b[1;32m    283\u001b[0m )\n\u001b[1;32m    284\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m    285\u001b[0m     outputs \u001b[38;5;241m=\u001b[39m (\n\u001b[0;32m--> 286\u001b[0m         \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_call\u001b[49m\u001b[43m(\u001b[49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    287\u001b[0m         \u001b[38;5;28;01mif\u001b[39;00m new_arg_supported\n\u001b[1;32m    288\u001b[0m         \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_call(inputs)\n\u001b[1;32m    289\u001b[0m     )\n\u001b[1;32m    290\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m    291\u001b[0m     run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n",
      "File \u001b[0;32m~/Downloads/conda/lib/python3.11/site-packages/langchain/chains/router/base.py:105\u001b[0m, in \u001b[0;36mMultiRouteChain._call\u001b[0;34m(self, inputs, run_manager)\u001b[0m\n\u001b[1;32m    103\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdefault_chain(route\u001b[38;5;241m.\u001b[39mnext_inputs, callbacks\u001b[38;5;241m=\u001b[39mcallbacks)\n\u001b[1;32m    104\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m--> 105\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[1;32m    106\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mReceived invalid destination chain name \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mroute\u001b[38;5;241m.\u001b[39mdestination\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    107\u001b[0m     )\n",
      "\u001b[0;31mValueError\u001b[0m: Received invalid destination chain name 'biology'"
     ]
    }
   ],
   "source": [
    "chain.run(\"Why does every cell in our body contain DNA?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9cbed99-9f90-4065-9b8f-a12de403c15a",
   "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.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}