{ "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\" : \"<>\"}\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\" : \"<>\"}\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 }