File size: 13,365 Bytes
4b2e474
f755dcf
 
 
 
 
 
 
 
 
4b2e474
fcc14cf
f755dcf
 
 
 
 
 
 
fcc14cf
4b2e474
f755dcf
13f3498
f755dcf
 
 
 
 
13f3498
f755dcf
 
 
 
13f3498
f755dcf
 
 
 
 
 
13f3498
f755dcf
13f3498
 
 
 
 
 
 
 
 
 
 
 
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
13f3498
 
 
 
 
f755dcf
 
 
 
 
 
 
 
13f3498
 
f755dcf
13f3498
 
 
 
f755dcf
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
13f3498
 
 
 
 
f755dcf
 
 
 
 
 
 
 
13f3498
f755dcf
13f3498
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b2e474
 
 
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
 
 
13f3498
 
 
 
 
 
 
 
 
 
 
 
f755dcf
 
13f3498
 
f755dcf
13f3498
f755dcf
13f3498
 
 
 
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
 
 
 
 
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
 
f755dcf
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
5fd9ae6
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
5fd9ae6
f755dcf
 
 
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
f755dcf
 
 
 
 
 
13f3498
5fd9ae6
a4ba306
f755dcf
 
 
 
13f3498
f755dcf
 
 
 
 
 
 
13f3498
f755dcf
 
13f3498
f755dcf
 
5fd9ae6
 
13f3498
f755dcf
 
 
4b2e474
dda976b
f755dcf
 
dda976b
f755dcf
4b2e474
f755dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
13f3498
4b2e474
dda976b
f755dcf
 
dda976b
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
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/towardsai/ai-tutor-rag-system/blob/main/notebooks/04-RAG_with_VectorStore.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5BGJ3fxhOk2V"
      },
      "source": [
        "# Install Packages and Setup Variables"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QPJzr-I9XQ7l"
      },
      "outputs": [],
      "source": [
        "!pip install -q llama-index==0.10.49 llama-index-vector-stores-chroma==0.1.9 llama-index-llms-gemini==0.1.11 google-generativeai==0.5.4 langchain==0.1.17 langchain-chroma==0.1.0 langchain_openai==0.1.5 openai==1.35.3 chromadb==0.5.3"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "riuXwpSPcvWC"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from dotenv import load_dotenv\n",
        "\n",
        "load_dotenv(\".env\")\n",
        "\n",
        "# Here we look for the OPENAI_API_KEY in the environment variables\n",
        "OPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")\n",
        "if not OPENAI_API_KEY:\n",
        "    # If it's not found, you can set it manually\n",
        "    os.environ[\"OPENAI_API_KEY\"] = \"<YOUR_OPENAI_KEY>\"\n",
        "\n",
        "# Get your GOOGLE_API_KEY from https://aistudio.google.com/app/apikey\n",
        "GOOGLE_API_KEY = os.getenv(\"GOOGLE_API_KEY\")\n",
        "if not GOOGLE_API_KEY:\n",
        "    os.environ[\"GOOGLE_API_KEY\"] = \"<YOUR_GOOGLE_KEY>\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "I9JbAzFcjkpn"
      },
      "source": [
        "# Load the Dataset (CSV)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_Tif8-JoRH68"
      },
      "source": [
        "## Download"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4fQaa1LN1mXL"
      },
      "source": [
        "The dataset includes several articles from the TowardsAI blog, which provide an in-depth explanation of the LLaMA2 model. Read the dataset as a long string."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "-QTUkdfJjY4N",
        "outputId": "a88b2f8a-0c84-45a0-9b32-5088fe596612"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n",
            "                                 Dload  Upload   Total   Spent    Left  Speed\n",
            "100  169k  100  169k    0     0  1581k      0 --:--:-- --:--:-- --:--:-- 1584k\n"
          ]
        }
      ],
      "source": [
        "!curl -o ./mini-dataset.csv https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-llama-articles.csv"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zk-4alIxROo8"
      },
      "source": [
        "## Read File"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "7CYwRT6R0o0I",
        "outputId": "351f170f-9a00-4b09-ae08-b45c3c48fce5"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "171044\n"
          ]
        }
      ],
      "source": [
        "import csv\n",
        "\n",
        "text = \"\"\n",
        "\n",
        "# Load the file as a JSON\n",
        "with open(\"./mini-dataset.csv\", mode=\"r\", encoding=\"utf-8\") as file:\n",
        "    csv_reader = csv.reader(file)\n",
        "\n",
        "    for idx, row in enumerate(csv_reader):\n",
        "        if idx == 0:\n",
        "            continue\n",
        "        text += row[1]\n",
        "\n",
        "# The number of characters in the dataset.\n",
        "print(len(text))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S17g2RYOjmf2"
      },
      "source": [
        "# Chunking"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "STACTMUR1z9N",
        "outputId": "15a61eac-8774-4cdb-db8d-e2eb5b07e517"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "335\n"
          ]
        }
      ],
      "source": [
        "chunk_size = 512\n",
        "chunks = []\n",
        "\n",
        "# Split the long text into smaller manageable chunks of 512 characters.\n",
        "for i in range(0, len(text), chunk_size):\n",
        "    chunks.append(text[i : i + chunk_size])\n",
        "\n",
        "print(len(chunks))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9fOomeMGqu10"
      },
      "source": [
        "#Interface of Chroma with LlamaIndex"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "CtdsIUQ81_hT"
      },
      "outputs": [],
      "source": [
        "from llama_index.core import Document\n",
        "\n",
        "# Convert the chunks to Document objects so the LlamaIndex framework can process them.\n",
        "documents = [Document(text=t) for t in chunks]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OWaT6rL7ksp8"
      },
      "source": [
        "Save on Chroma\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "mXi56KTXk2sp"
      },
      "outputs": [],
      "source": [
        "import chromadb\n",
        "\n",
        "# create client and a new collection\n",
        "# chromadb.EphemeralClient saves data in-memory.\n",
        "chroma_client = chromadb.PersistentClient(path=\"./mini-chunked-dataset\")\n",
        "chroma_collection = chroma_client.create_collection(\"mini-chunked-dataset\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "jKXURvLtkuTS"
      },
      "outputs": [],
      "source": [
        "from llama_index.vector_stores.chroma import ChromaVectorStore\n",
        "from llama_index.core import StorageContext\n",
        "\n",
        "# Define a storage context object using the created vector database.\n",
        "vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
        "storage_context = StorageContext.from_defaults(vector_store=vector_store)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "WsD52wtrlESi"
      },
      "outputs": [
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "/Users/omar/Documents/ai_repos/ai-tutor-rag-system/env/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
            "  from .autonotebook import tqdm as notebook_tqdm\n",
            "Parsing nodes: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 335/335 [00:00<00:00, 8031.85it/s]\n",
            "Generating embeddings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 335/335 [00:03<00:00, 97.24it/s] \n"
          ]
        }
      ],
      "source": [
        "from llama_index.core import VectorStoreIndex\n",
        "from llama_index.core.node_parser import SentenceSplitter\n",
        "from llama_index.embeddings.openai import OpenAIEmbedding\n",
        "\n",
        "# Build index / generate embeddings using OpenAI embedding model\n",
        "index = VectorStoreIndex.from_documents(\n",
        "    documents,\n",
        "    embed_model=OpenAIEmbedding(model=\"text-embedding-3-small\"),\n",
        "    storage_context=storage_context,\n",
        "    show_progress=True,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8JPD8yAinVSq"
      },
      "source": [
        "Query Dataset"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "mzS13x1ZlZ5X"
      },
      "outputs": [],
      "source": [
        "# Define a query engine that is responsible for retrieving related pieces of text,\n",
        "# and using a LLM to formulate the final answer.\n",
        "\n",
        "from llama_index.llms.gemini import Gemini\n",
        "\n",
        "llm = Gemini(model=\"models/gemini-1.5-flash\", temperature=1, max_tokens=512)\n",
        "\n",
        "query_engine = index.as_query_engine(llm=llm, similarity_top_k=5)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AYsQ4uLN_Oxg",
        "outputId": "5066a06c-77ff-48a2-ee61-3abe2e9755e2"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The LLaMA2 model has four different sizes: 7 billion, 13 billion, 34 billion, and 70 billion parameters. \n",
            "\n"
          ]
        }
      ],
      "source": [
        "response = query_engine.query(\"How many parameters LLaMA2 model has?\")\n",
        "print(response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kWK571VNg-qR"
      },
      "source": [
        "#Interface of Chroma with LangChain"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "id": "SMPAniL2e4NP"
      },
      "outputs": [],
      "source": [
        "from langchain.schema.document import Document\n",
        "\n",
        "# Convert the chunks to Document objects so the LangChain framework can process them.\n",
        "documents = [Document(page_content=t) for t in chunks]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QBt8qGxArUPD"
      },
      "source": [
        "Save on Chroma"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "id": "2xas7HkuhJ8A"
      },
      "outputs": [],
      "source": [
        "from langchain_chroma import Chroma\n",
        "from langchain_openai import OpenAIEmbeddings\n",
        "\n",
        "# Add the documents to chroma DB and create Index / embeddings\n",
        "\n",
        "embeddings = OpenAIEmbeddings(model=\"text-embedding-ada-002\")\n",
        "chroma_db = Chroma.from_documents(\n",
        "    documents=documents,\n",
        "    embedding=embeddings,\n",
        "    persist_directory=\"./mini-chunked-dataset\",\n",
        "    collection_name=\"mini-chunked-dataset\",\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "P8AXJJyBrZWF"
      },
      "source": [
        "Query Dataset"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-H64YLxshM2b"
      },
      "outputs": [],
      "source": [
        "from langchain_openai import ChatOpenAI\n",
        "\n",
        "# Initializing the LLM model\n",
        "llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo\", max_tokens=512)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AxBqPNtthPaa",
        "outputId": "93c9ad64-1cd1-4f52-c51e-6f3ec5d6542d"
      },
      "outputs": [],
      "source": [
        "from langchain.chains import RetrievalQA\n",
        "\n",
        "query = \"How many parameters LLaMA2 model has?\"\n",
        "retriever = chroma_db.as_retriever(search_kwargs={\"k\": 2})\n",
        "# Define a RetrievalQA chain that is responsible for retrieving related pieces of text,\n",
        "# and using a LLM to formulate the final answer.\n",
        "chain = RetrievalQA.from_chain_type(llm=llm, chain_type=\"stuff\", retriever=retriever)\n",
        "\n",
        "response = chain(query)\n",
        "print(response[\"result\"])"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "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.12.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}