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
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f36d938c",
   "metadata": {},
   "source": [
    "# How to cache LLM calls\n",
    "This notebook covers how to cache results of individual LLM calls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "10ad9224",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.llms import OpenAI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b50f0598",
   "metadata": {},
   "source": [
    "## In Memory Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "426ff912",
   "metadata": {},
   "outputs": [],
   "source": [
    "import langchain\n",
    "from langchain.cache import InMemoryCache\n",
    "langchain.llm_cache = InMemoryCache()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f69f6283",
   "metadata": {},
   "outputs": [],
   "source": [
    "# To make the caching really obvious, lets use a slower model.\n",
    "llm = OpenAI(model_name=\"text-davinci-002\", n=2, best_of=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "64005d1f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 26.1 ms, sys: 21.5 ms, total: 47.6 ms\n",
      "Wall time: 1.68 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c8a1cb2b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 238 µs, sys: 143 µs, total: 381 µs\n",
      "Wall time: 1.76 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bf59c12",
   "metadata": {},
   "source": [
    "## SQLite Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3ff65b00",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm .langchain.db"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5f036236",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can do the same thing with a SQLite cache\n",
    "from langchain.cache import SQLiteCache\n",
    "langchain.llm_cache = SQLiteCache(database_path=\".langchain.db\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "fa18e3af",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 17 ms, sys: 9.76 ms, total: 26.7 ms\n",
      "Wall time: 825 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5bf2f6fd",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2.46 ms, sys: 1.23 ms, total: 3.7 ms\n",
      "Wall time: 2.67 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "278ad7ae",
   "metadata": {},
   "source": [
    "## Redis Cache"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5c9a4d5",
   "metadata": {},
   "source": [
    "### Standard Cache\n",
    "Use [Redis](../../../../ecosystem/redis.md) to cache prompts and responses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "39f6eb0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can do the same thing with a Redis cache\n",
    "# (make sure your local Redis instance is running first before running this example)\n",
    "from redis import Redis\n",
    "from langchain.cache import RedisCache\n",
    "\n",
    "langchain.llm_cache = RedisCache(redis_=Redis())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "28920749",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 6.88 ms, sys: 8.75 ms, total: 15.6 ms\n",
      "Wall time: 1.04 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "94bf9415",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.59 ms, sys: 610 µs, total: 2.2 ms\n",
      "Wall time: 5.58 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82be23f6",
   "metadata": {},
   "source": [
    "### Semantic Cache\n",
    "Use [Redis](../../../../ecosystem/redis.md) to cache prompts and responses and evaluate hits based on semantic similarity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "64df3099",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings import OpenAIEmbeddings\n",
    "from langchain.cache import RedisSemanticCache\n",
    "\n",
    "\n",
    "langchain.llm_cache = RedisSemanticCache(\n",
    "    redis_url=\"redis://localhost:6379\",\n",
    "    embedding=OpenAIEmbeddings()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "8e91d3ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 351 ms, sys: 156 ms, total: 507 ms\n",
      "Wall time: 3.37 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "df856948",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 6.25 ms, sys: 2.72 ms, total: 8.97 ms\n",
      "Wall time: 262 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time, while not a direct hit, the question is semantically similar to the original question,\n",
    "# so it uses the cached result!\n",
    "llm(\"Tell me one joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "684eab55",
   "metadata": {},
   "source": [
    "## GPTCache\n",
    "\n",
    "We can use [GPTCache](https://github.com/zilliztech/GPTCache) for exact match caching OR to cache results based on semantic similarity\n",
    "\n",
    "Let's first start with an example of exact match"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "14a82124",
   "metadata": {},
   "outputs": [],
   "source": [
    "from gptcache import Cache\n",
    "from gptcache.manager.factory import manager_factory\n",
    "from gptcache.processor.pre import get_prompt\n",
    "from langchain.cache import GPTCache\n",
    "\n",
    "# Avoid multiple caches using the same file, causing different llm model caches to affect each other\n",
    "\n",
    "def init_gptcache(cache_obj: Cache, llm str):\n",
    "    cache_obj.init(\n",
    "        pre_embedding_func=get_prompt,\n",
    "        data_manager=manager_factory(manager=\"map\", data_dir=f\"map_cache_{llm}\"),\n",
    "    )\n",
    "\n",
    "langchain.llm_cache = GPTCache(init_gptcache)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "9e4ecfd1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 8.6 ms, sys: 3.82 ms, total: 12.4 ms\n",
      "Wall time: 881 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c98bbe3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 286 µs, sys: 21 µs, total: 307 µs\n",
      "Wall time: 316 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "502b6076",
   "metadata": {},
   "source": [
    "Let's now show an example of similarity caching"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b3c663bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from gptcache import Cache\n",
    "from gptcache.adapter.api import init_similar_cache\n",
    "from langchain.cache import GPTCache\n",
    "\n",
    "# Avoid multiple caches using the same file, causing different llm model caches to affect each other\n",
    "\n",
    "def init_gptcache(cache_obj: Cache, llm str):\n",
    "    init_similar_cache(cache_obj=cache_obj, data_dir=f\"similar_cache_{llm}\")\n",
    "\n",
    "langchain.llm_cache = GPTCache(init_gptcache)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8c273ced",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.01 s, sys: 153 ms, total: 1.16 s\n",
      "Wall time: 2.49 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "93e21a5f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 745 ms, sys: 13.2 ms, total: 758 ms\n",
      "Wall time: 136 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# This is an exact match, so it finds it in the cache\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c4bb024b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 737 ms, sys: 7.79 ms, total: 745 ms\n",
      "Wall time: 135 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# This is not an exact match, but semantically within distance so it hits!\n",
    "llm(\"Tell me joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "934943dc",
   "metadata": {},
   "source": [
    "## SQLAlchemy Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acccff40",
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can use SQLAlchemyCache to cache with any SQL database supported by SQLAlchemy.\n",
    "\n",
    "# from langchain.cache import SQLAlchemyCache\n",
    "# from sqlalchemy import create_engine\n",
    "\n",
    "# engine = create_engine(\"postgresql://postgres:postgres@localhost:5432/postgres\")\n",
    "# langchain.llm_cache = SQLAlchemyCache(engine)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0959d640",
   "metadata": {},
   "source": [
    "### Custom SQLAlchemy Schemas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac967b39",
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can define your own declarative SQLAlchemyCache child class to customize the schema used for caching. For example, to support high-speed fulltext prompt indexing with Postgres, use:\n",
    "\n",
    "from sqlalchemy import Column, Integer, String, Computed, Index, Sequence\n",
    "from sqlalchemy import create_engine\n",
    "from sqlalchemy.ext.declarative import declarative_base\n",
    "from sqlalchemy_utils import TSVectorType\n",
    "from langchain.cache import SQLAlchemyCache\n",
    "\n",
    "Base = declarative_base()\n",
    "\n",
    "\n",
    "class FulltextLLMCache(Base):  # type: ignore\n",
    "    \"\"\"Postgres table for fulltext-indexed LLM Cache\"\"\"\n",
    "\n",
    "    __tablename__ = \"llm_cache_fulltext\"\n",
    "    id = Column(Integer, Sequence('cache_id'), primary_key=True)\n",
    "    prompt = Column(String, nullable=False)\n",
    "    llm = Column(String, nullable=False)\n",
    "    idx = Column(Integer)\n",
    "    response = Column(String)\n",
    "    prompt_tsv = Column(TSVectorType(), Computed(\"to_tsvector('english', llm || ' ' || prompt)\", persisted=True))\n",
    "    __table_args__ = (\n",
    "        Index(\"idx_fulltext_prompt_tsv\", prompt_tsv, postgresql_using=\"gin\"),\n",
    "    )\n",
    "\n",
    "engine = create_engine(\"postgresql://postgres:postgres@localhost:5432/postgres\")\n",
    "langchain.llm_cache = SQLAlchemyCache(engine, FulltextLLMCache)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c69d84d",
   "metadata": {},
   "source": [
    "## Optional Caching\n",
    "You can also turn off caching for specific LLMs should you choose. In the example below, even though global caching is enabled, we turn it off for a specific LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "6af46e2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(model_name=\"text-davinci-002\", n=2, best_of=2, cache=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "26c4fd8f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 5.8 ms, sys: 2.71 ms, total: 8.51 ms\n",
      "Wall time: 745 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "46846b20",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.91 ms, sys: 2.64 ms, total: 7.55 ms\n",
      "Wall time: 623 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nTwo guys stole a calendar. They got six months each.'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5da41b77",
   "metadata": {},
   "source": [
    "## Optional Caching in Chains\n",
    "You can also turn off caching for particular nodes in chains. Note that because of certain interfaces, its often easier to construct the chain first, and then edit the LLM afterwards.\n",
    "\n",
    "As an example, we will load a summarizer map-reduce chain. We will cache results for the map-step, but then not freeze it for the combine step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9afa3f7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(model_name=\"text-davinci-002\")\n",
    "no_cache_llm = OpenAI(model_name=\"text-davinci-002\", cache=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "98a78e8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.chains.mapreduce import MapReduceChain\n",
    "\n",
    "text_splitter = CharacterTextSplitter()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "2bfb099b",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../../../state_of_the_union.txt') as f:\n",
    "    state_of_the_union = f.read()\n",
    "texts = text_splitter.split_text(state_of_the_union)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f78b7f51",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.docstore.document import Document\n",
    "docs = [Document(page_content=t) for t in texts[:3]]\n",
    "from langchain.chains.summarize import load_summarize_chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "a2a30822",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_summarize_chain(llm, chain_type=\"map_reduce\", reduce_llm=no_cache_llm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "a545b743",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 452 ms, sys: 60.3 ms, total: 512 ms\n",
      "Wall time: 5.09 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure. In response to Russian aggression in Ukraine, the United States is joining with European allies to impose sanctions and isolate Russia. American forces are being mobilized to protect NATO countries in the event that Putin decides to keep moving west. The Ukrainians are bravely fighting back, but the next few weeks will be hard for them. Putin will pay a high price for his actions in the long run. Americans should not be alarmed, as the United States is taking action to protect its interests and allies.'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "chain.run(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ed85e9d",
   "metadata": {},
   "source": [
    "When we run it again, we see that it runs substantially faster but the final answer is different. This is due to caching at the map steps, but not at the reduce step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "39cbb282",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 11.5 ms, sys: 4.33 ms, total: 15.8 ms\n",
      "Wall time: 1.04 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure.'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "chain.run(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9df0dab8",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm .langchain.db sqlite.db"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}