File size: 22,296 Bytes
15d3a03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Langchain Processing of Meta 10K 2023\n",
    "\n",
    "- Google Doc with [instructions](https://docs.google.com/forms/d/e/1FAIpQLSfRHORtHFiPUGCiYNt2NfapWtgUQWbv5V75kUPwUAkx20r9Eg/viewform)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()\n",
    "\n",
    "import logging\n",
    "import sys\n",
    "import os\n",
    "from dotenv import find_dotenv, load_dotenv\n",
    "\n",
    "load_dotenv(find_dotenv())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "DEFAULT_QUESTION1 = \"What was the total value of 'Cash and cash equivalents' as of December 31, 2023?\"\n",
    "DEFAULT_QUESTION2 = \"Who are Meta's 'Directors' (i.e., members of the Board of Directors)?\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.  Loading Document"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "147"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_community.document_loaders import PyMuPDFLoader\n",
    "loader = PyMuPDFLoader(\n",
    "    \"../data/meta-10k-2023.pdf\",\n",
    ")\n",
    "\n",
    "# from langchain_community.document_loaders import UnstructuredPDFLoader\n",
    "# loader = UnstructuredPDFLoader(\n",
    "#     file_path=\"../data/meta-10k-2023.pdf\",\n",
    "#     mode=\"elements\"\n",
    "# )\n",
    "\n",
    "documents = loader.load()\n",
    "len(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'source': '../data/meta-10k-2023.pdf',\n",
       " 'file_path': '../data/meta-10k-2023.pdf',\n",
       " 'page': 0,\n",
       " 'total_pages': 147,\n",
       " 'format': 'PDF 1.4',\n",
       " 'title': '0001326801-24-000012',\n",
       " 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group',\n",
       " 'subject': 'Form 10-K filed on 2024-02-02 for the period ending 2023-12-31',\n",
       " 'keywords': '0001326801-24-000012; ; 10-K',\n",
       " 'creator': 'EDGAR Filing HTML Converter',\n",
       " 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0',\n",
       " 'creationDate': \"D:20240202060356-05'00'\",\n",
       " 'modDate': \"D:20240202060413-05'00'\",\n",
       " 'trapped': '',\n",
       " 'encryption': 'Standard V2 R3 128-bit RC4'}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "documents[0].metadata"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.  Transforming Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "621"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter(\n",
    "    chunk_size = 1024,\n",
    "    chunk_overlap = 64\n",
    ")\n",
    "\n",
    "docs = text_splitter.split_documents(documents)\n",
    "len(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.  Embedding & Vector Storage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "chat_model = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0.0)\n",
    "\n",
    "# from llama_index.llms.ollama import Ollama\n",
    "# chat_model = Ollama(model=\"llama3\", request_timeout=30.0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import OpenAIEmbeddings\n",
    "embeddings = OpenAIEmbeddings(\n",
    "    model=\"text-embedding-3-small\"\n",
    ")\n",
    "\n",
    "# from langchain_voyageai import VoyageAIEmbeddings\n",
    "# EMBEDDING_MODEL = \"voyage-2\"  # Alternative: \"voyage-lite-02-instruct\"\n",
    "# embeddings = VoyageAIEmbeddings(model=EMBEDDING_MODEL, batch_size=12)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.vectorstores import Qdrant\n",
    "\n",
    "qdrant_vectorstore = Qdrant.from_documents(\n",
    "    docs,\n",
    "    embeddings,\n",
    "    path=\"../data\",\n",
    "    # location=\":memory:\",\n",
    "    collection_name=\"meta10k\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "qdrant_retriever = qdrant_vectorstore.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.retrievers.multi_query import MultiQueryRetriever\n",
    "\n",
    "mquery_retriever = MultiQueryRetriever.from_llm(\n",
    "    retriever=qdrant_retriever, llm=chat_model\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. LCEL\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "RAG_PROMPT = \"\"\"\n",
    "CONTEXT:\n",
    "{context}\n",
    "\n",
    "QUERY:\n",
    "{question}\n",
    "\n",
    "You should only respond to user's query if the context is related to the query.  If not, please reply \"I don't know\".\n",
    "\"\"\"\n",
    "\n",
    "rag_prompt = ChatPromptTemplate.from_template(RAG_PROMPT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from operator import itemgetter\n",
    "from langchain.schema.output_parser import StrOutputParser\n",
    "from langchain.schema.runnable import RunnablePassthrough\n",
    "\n",
    "retrieval_augmented_qa_chain = (\n",
    "    # INVOKE CHAIN WITH: {\"question\" : \"<<SOME USER QUESTION>>\"}\n",
    "    # \"question\" : populated by getting the value of the \"question\" key\n",
    "    # \"context\"  : populated by getting the value of the \"question\" key and chaining it into the base_retriever\n",
    "    {\"context\": itemgetter(\"question\") | mquery_retriever, \"question\": itemgetter(\"question\")}\n",
    "    # \"context\"  : is assigned to a RunnablePassthrough object (will not be called or considered in the next step)\n",
    "    #              by getting the value of the \"context\" key from the previous step\n",
    "    | RunnablePassthrough.assign(context=itemgetter(\"context\"))\n",
    "    # \"response\" : the \"context\" and \"question\" values are used to format our prompt object and then piped\n",
    "    #              into the LLM and stored in a key called \"response\"\n",
    "    # \"context\"  : populated by getting the value of the \"context\" key from the previous step\n",
    "    | {\"response\": rag_prompt | chat_model, \"context\": itemgetter(\"context\")}\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Testing with basic RAG"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The total value of 'Cash and cash equivalents' as of December 31, 2023, was $65.40 billion.\n"
     ]
    }
   ],
   "source": [
    "response1 = retrieval_augmented_qa_chain.invoke({\"question\": DEFAULT_QUESTION1})\n",
    "print(response1[\"response\"].content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Directors of Meta Platforms, Inc. mentioned in the document are:\n",
      "- Robert M. Kimmitt\n",
      "- Sheryl K. Sandberg\n",
      "- Tracey T. Travis\n",
      "- Tony Xu\n"
     ]
    }
   ],
   "source": [
    "response2 = retrieval_augmented_qa_chain.invoke({\"question\": DEFAULT_QUESTION2})\n",
    "print(response2[\"response\"].content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Directors mentioned in the context are Robert M. Kimmitt, Sheryl K. Sandberg, Tracey T. Travis, Tony Xu, Mark Zuckerberg, Susan Li, Aaron Anderson, Peggy Alford, Marc L. Andreessen, Andrew W. Houston, Nancy Killefer.\n"
     ]
    }
   ],
   "source": [
    "response2 = retrieval_augmented_qa_chain.invoke(\n",
    "    {\"question\":  \"Who are the 'Directors' (i.e., members of the Board of Directors)?\"})\n",
    "print(response2[\"response\"].content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Semantic Chunking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_experimental.text_splitter import SemanticChunker\n",
    "\n",
    "semantic_chunker = SemanticChunker(\n",
    "    OpenAIEmbeddings(model=\"text-embedding-3-large\"), \n",
    "    breakpoint_threshold_type=\"percentile\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "147"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='UNITED STATES\\nSECURITIES AND EXCHANGE COMMISSION\\nWashington, D.C.\\xa020549\\n__________________________\\nFORM 10-K\\n__________________________\\n(Mark One)\\n☒\\xa0\\xa0\\xa0\\xa0ANNUAL REPORT PURSUANT TO SECTION 13 OR 15(d)\\xa0OF THE SECURITIES EXCHANGE ACT OF 1934\\nFor the fiscal year ended December\\xa031, 2023\\nor\\n☐\\xa0\\xa0\\xa0\\xa0TRANSITION REPORT PURSUANT TO SECTION 13 OR 15(d)\\xa0OF THE SECURITIES EXCHANGE ACT OF 1934\\nFor the transition period from\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0to\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\\nCommission File Number:\\xa0001-35551\\n__________________________\\nMeta Platforms, Inc.\\n(Exact name of registrant as specified in its charter)\\n__________________________\\nDelaware\\n20-1665019\\n(State or other jurisdiction of incorporation or organization)\\n(I.R.S. Employer Identification Number)\\n1 Meta Way, Menlo Park, California 94025\\n(Address of principal executive offices and Zip Code)\\n(650)\\xa0543-4800\\n(Registrant\\'s telephone number, including area code)\\n__________________________\\nSecurities registered pursuant to Section 12(b) of the Act:\\nTitle of each class\\nTrading symbol(s)\\nName of each exchange on which registered\\nClass A Common Stock, $0.000006 par value\\nMETA\\nThe Nasdaq Stock Market LLC\\nSecurities registered pursuant to Section 12(g) of the Act: None\\nIndicate by check mark if the registrant is a well-known seasoned issuer, as defined in Rule 405 of the Securities Act.\\xa0\\xa0\\xa0\\xa0Yes\\xa0\\xa0☒\\xa0\\xa0No\\xa0\\xa0 ☐\\nIndicate by check mark if the registrant is not required to file reports pursuant to Section 13 or Section 15(d) of the Act.\\xa0\\xa0\\xa0\\xa0Yes \\xa0☐\\xa0No\\xa0 ☒\\nIndicate by check mark whether the registrant\\xa0(1)\\xa0has filed all reports required to be filed by Section\\xa013 or 15(d) of the Securities Exchange Act of 1934 (Exchange Act) during the preceding\\n12\\xa0months (or for such shorter period that the registrant was required to file such reports), and\\xa0(2)\\xa0has been subject to such filing requirements for the past 90\\xa0days.\\xa0\\xa0\\xa0\\xa0Yes\\xa0\\xa0☒\\xa0\\xa0\\xa0\\xa0No\\xa0\\xa0☐\\nIndicate by check mark whether the registrant has submitted electronically every Interactive Data File required to be submitted pursuant to Rule 405 of Regulation S-T (§\\xa0232.405 of this chapter)\\nduring the preceding 12 months (or for such shorter period that the registrant was required to submit such files).\\xa0\\xa0\\xa0\\xa0Yes\\xa0\\xa0☒\\xa0\\xa0\\xa0\\xa0No\\xa0\\xa0☐\\nIndicate by check mark whether the registrant is a large accelerated filer, an accelerated filer, a non-accelerated filer, a smaller reporting company, or an emerging growth company. See the definitions\\nof \"large accelerated filer,\" \"accelerated filer,\" \"smaller reporting company,\" and \"emerging growth company\" in Rule 12b-2 of the Exchange Act.\\nLarge accelerated filer\\n☒\\nAccelerated\\xa0filer\\n☐\\nNon-accelerated filer\\n☐\\nSmaller\\xa0reporting\\xa0company\\n☐\\nEmerging growth company\\n☐\\nIf an emerging growth company, indicate by check mark if the registrant has elected not to use the extended transition period for complying with any new or revised financial accounting standards\\nprovided pursuant to Section 13(a) of the Exchange Act. ☐\\nIndicate by check mark whether the registrant has filed a report on and attestation to its management\\'s assessment of the effectiveness of its internal control over financial reporting under Section\\n404(b) of the Sarbanes-Oxley Act (15 U.S.C. 7262(b)) by the registered public accounting firm that prepared or issued its audit report. ☒\\nIf securities are registered pursuant to Section 12(b) of the Act, indicate by check mark whether the financial statements of the registrant included in the filing reflect the correction of an error to\\npreviously issued financial statements. ☐\\nIndicate by check mark whether any of those error corrections are restatements that required a recovery analysis of incentive-based compensation received by any of the registrant’s executive officers\\nduring the relevant recovery period pursuant to §240.10D-1(b). ☐\\nIndicate by check mark whether the registrant is a shell company (as defined in Rule 12b-2 of the Exchange Act).\\xa0\\xa0\\xa0\\xa0Yes\\xa0\\xa0☐\\xa0\\xa0\\xa0\\xa0No\\xa0\\xa0 ☒\\nThe aggregate market value of the voting and non-voting stock held by non-affiliates of the registrant as of June\\xa030, 2023, the last business day of the registrant\\'s most recently completed second fiscal\\nquarter, was $637\\xa0billion based upon the closing price reported for such date on the Nasdaq Global Select Market. On January\\xa026, 2024, the registrant had 2,200,048,907 shares of Class\\xa0A common\\nstock and 349,356,199 shares of Class B common stock outstanding.\\n', metadata={'source': '../data/meta-10k-2023.pdf', 'file_path': '../data/meta-10k-2023.pdf', 'page': 0, 'total_pages': 147, 'format': 'PDF 1.4', 'title': '0001326801-24-000012', 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group', 'subject': 'Form 10-K filed on 2024-02-02 for the period ending 2023-12-31', 'keywords': '0001326801-24-000012; ; 10-K', 'creator': 'EDGAR Filing HTML Converter', 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', 'creationDate': \"D:20240202060356-05'00'\", 'modDate': \"D:20240202060413-05'00'\", 'trapped': '', 'encryption': 'Standard V2 R3 128-bit RC4'})"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "documents[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "semantic_chunks = semantic_chunker.create_documents([d.page_content for d in documents])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "346"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(semantic_chunks)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating a RAG Pipeline using Semantic Chunks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "semantic_chunk_vectorstore = Qdrant.from_documents(\n",
    "    semantic_chunks,\n",
    "    embeddings,\n",
    "    path=\"../data/semantic-chunks\",\n",
    "    # location=\":memory:\",\n",
    "    collection_name=\"meta10k-semantic\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "semantic_chunk_vectorstore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "semantic_chunk_retriever = semantic_chunk_vectorstore.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.retrievers.multi_query import MultiQueryRetriever\n",
    "\n",
    "semantic_mquery_retriever = MultiQueryRetriever.from_llm(\n",
    "    retriever=semantic_chunk_retriever, \n",
    "    llm=chat_model\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "semantic_retrieval_augmented_qa_chain = (\n",
    "    # INVOKE CHAIN WITH: {\"question\" : \"<<SOME USER QUESTION>>\"}\n",
    "    # \"question\" : populated by getting the value of the \"question\" key\n",
    "    # \"context\"  : populated by getting the value of the \"question\" key and chaining it into the base_retriever\n",
    "    {\"context\": itemgetter(\"question\") | semantic_mquery_retriever, \"question\": itemgetter(\"question\")}\n",
    "    # \"context\"  : is assigned to a RunnablePassthrough object (will not be called or considered in the next step)\n",
    "    #              by getting the value of the \"context\" key from the previous step\n",
    "    | RunnablePassthrough.assign(context=itemgetter(\"context\"))\n",
    "    # \"response\" : the \"context\" and \"question\" values are used to format our prompt object and then piped\n",
    "    #              into the LLM and stored in a key called \"response\"\n",
    "    # \"context\"  : populated by getting the value of the \"context\" key from the previous step\n",
    "    | {\"response\": rag_prompt | chat_model, \"context\": itemgetter(\"context\")}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "langchain_core.runnables.base.RunnableSequence"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(semantic_retrieval_augmented_qa_chain)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Testing with Semantic Chunk RAG"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The total value of 'Cash and cash equivalents' as of December 31, 2023, was $41.862 billion.\n"
     ]
    }
   ],
   "source": [
    "semantic_response1 = semantic_retrieval_augmented_qa_chain.invoke({\"question\": DEFAULT_QUESTION1})\n",
    "print(semantic_response1[\"response\"].content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Directors of Meta, as mentioned in the provided documents, include:\n",
      "- Andrew W. Houston\n",
      "- Nancy Killefer\n",
      "- Robert M. Kimmitt\n",
      "- Sheryl K. Sandberg\n",
      "- Tracey T. Travis\n",
      "- Tony Xu\n"
     ]
    }
   ],
   "source": [
    "semantic_response2 = semantic_retrieval_augmented_qa_chain.invoke({\"question\": DEFAULT_QUESTION2})\n",
    "print(semantic_response2[\"response\"].content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The members of the Board of Directors mentioned in the provided documents are:\n",
      "- Andrew W. Houston\n",
      "- Nancy Killefer\n",
      "- Robert M. Kimmitt\n",
      "- Sheryl K. Sandberg\n",
      "- Tracey T. Travis\n",
      "- Tony Xu\n",
      "- Mark Zuckerberg\n",
      "- Susan Li\n",
      "- Aaron Anderson\n",
      "- Peggy Alford\n",
      "- Marc L. Andreessen\n"
     ]
    }
   ],
   "source": [
    "response2 = semantic_retrieval_augmented_qa_chain.invoke(\n",
    "    {\"question\":  \"Who are the 'Directors' (i.e., members of the Board of Directors)?\"})\n",
    "print(response2[\"response\"].content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llmops",
   "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.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}