File size: 10,657 Bytes
a2a9a44
 
 
 
 
 
 
 
 
 
 
84f8c13
a2a9a44
 
 
 
 
 
3e7bb9e
a2a9a44
 
 
 
84f8c13
a2a9a44
 
 
 
 
 
 
 
 
 
84f8c13
a2a9a44
 
 
 
 
 
 
 
 
 
 
 
 
84f8c13
a2a9a44
 
 
 
 
 
 
 
84f8c13
a2a9a44
 
 
 
84f8c13
a2a9a44
 
 
84f8c13
a2a9a44
 
 
84f8c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2a9a44
 
 
 
 
84f8c13
a2a9a44
84f8c13
a2a9a44
84f8c13
 
 
 
a2a9a44
 
 
 
84f8c13
 
 
a2a9a44
 
 
3e7bb9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2a9a44
 
84f8c13
a2a9a44
84f8c13
a2a9a44
 
 
 
84f8c13
 
 
 
 
a2a9a44
84f8c13
a2a9a44
 
 
 
84f8c13
a2a9a44
 
 
84f8c13
 
 
 
a2a9a44
 
 
 
84f8c13
a2a9a44
 
 
84f8c13
a2a9a44
 
 
 
84f8c13
a2a9a44
84f8c13
a2a9a44
 
 
 
 
 
84f8c13
a2a9a44
84f8c13
a2a9a44
 
 
 
 
 
84f8c13
a2a9a44
 
 
 
 
 
 
 
 
 
 
 
e0aadb4
a2a9a44
 
 
 
 
 
84f8c13
a2a9a44
 
 
 
 
 
e0aadb4
a2a9a44
 
 
 
 
 
 
 
 
 
e0aadb4
a2a9a44
 
 
84f8c13
 
e0aadb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84f8c13
 
 
e0aadb4
 
 
 
 
 
a2a9a44
 
 
 
e0aadb4
a2a9a44
 
 
e0aadb4
 
 
 
 
 
a2a9a44
 
 
 
e0aadb4
a2a9a44
e0aadb4
a2a9a44
 
 
 
 
 
e0aadb4
a2a9a44
e0aadb4
a2a9a44
 
 
 
 
 
 
 
 
 
e0aadb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2a9a44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84f8c13
a2a9a44
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Create AI-Tutor vector database"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# Set the \"OPENAI_API_KEY\" in the Python environment. Will be used by OpenAI client later.\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"sk-...\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "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=\"./ai-tutor-db\")\n",
    "chroma_collection = chroma_client.create_collection(\"ai-tutor-db\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "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": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from llama_index.core.schema import TextNode\n",
    "\n",
    "\n",
    "def load_jsonl_create_nodes(filepath):\n",
    "    nodes = []  # List to hold the created node objects\n",
    "    with open(filepath, \"r\") as file:\n",
    "        for line in file:\n",
    "            # Load each line as a JSON object\n",
    "            json_obj = json.loads(line)\n",
    "            # Extract required information\n",
    "            title = json_obj.get(\"title\")\n",
    "            url = json_obj.get(\"url\")\n",
    "            content = json_obj.get(\"content\")\n",
    "            source = json_obj.get(\"source\")\n",
    "            # Create a TextNode object and append to the list\n",
    "            node = TextNode(\n",
    "                text=content,\n",
    "                metadata={\"title\": title, \"url\": url, \"source\": source},\n",
    "                excluded_embed_metadata_keys=[\"title\", \"url\", \"source\"],\n",
    "                excluded_llm_metadata_keys=[\"title\", \"url\", \"source\"],\n",
    "            )\n",
    "            nodes.append(node)\n",
    "    return nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "filepath = \"../data/ai-tutor-csv-files/combined_data_lines.jsonl\"\n",
    "nodes = load_jsonl_create_nodes(filepath)\n",
    "\n",
    "print(f\"Loaded {len(nodes)} nodes/chunks from the JSONL file\\n \")\n",
    "\n",
    "node = nodes[0]\n",
    "print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")\n",
    "\n",
    "print(\"\\n\")\n",
    "\n",
    "node = nodes[-10000]\n",
    "print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Create the pipeline to apply the transformation on each chunk,\n",
    "# # and store the transformed text in the chroma vector store.\n",
    "# pipeline = IngestionPipeline(\n",
    "#     transformations=[\n",
    "#         text_splitter,\n",
    "#         QuestionsAnsweredExtractor(questions=3, llm=llm),\n",
    "#         SummaryExtractor(summaries=[\"prev\", \"self\"], llm=llm),\n",
    "#         KeywordExtractor(keywords=10, llm=llm),\n",
    "#         OpenAIEmbedding(),\n",
    "#     ],\n",
    "#     vector_store=vector_store\n",
    "# )\n",
    "\n",
    "# nodes = pipeline.run(documents=documents, show_progress=True);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.embeddings.openai import OpenAIEmbedding\n",
    "from llama_index.core import VectorStoreIndex\n",
    "\n",
    "# embeds = OpenAIEmbedding(model=\"text-embedding-3-small\", mode=\"similarity\")\n",
    "# embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"similarity\")\n",
    "embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
    "# embeds = OpenAIEmbedding(model=\"text-embedding-ada-002\", mode=\"similarity\")\n",
    "\n",
    "# Build index / generate embeddings using OpenAI.\n",
    "index = VectorStoreIndex(nodes=nodes, show_progress=True, use_async=True, storage_context=storage_context, embed_model=embeds, insert_batch_size=3000,)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.openai import OpenAI\n",
    "\n",
    "llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo-0125\", max_tokens=None)\n",
    "query_engine = index.as_query_engine(llm=llm, similarity_top_k=5, embed_model=embeds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = query_engine.query(\"What is the LLama model?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res.response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for src in res.source_nodes:\n",
    "  print(\"Node ID\\t\", src.node_id)\n",
    "  print(\"Title\\t\", src.metadata['title'])\n",
    "  print(\"Text\\t\", src.text)\n",
    "  print(\"Score\\t\", src.score)\n",
    "  print(\"Metadata\\t\", src.metadata) \n",
    "  print(\"-_\"*20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load DB from disk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import chromadb\n",
    "from llama_index.vector_stores.chroma import ChromaVectorStore\n",
    "# Create your index\n",
    "db2 = chromadb.PersistentClient(path=\"./ai-tutor-db\")\n",
    "chroma_collection = db2.get_or_create_collection(\"ai-tutor-db\")\n",
    "vector_store = ChromaVectorStore(chroma_collection=chroma_collection)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create your index\n",
    "from llama_index.core import VectorStoreIndex\n",
    "index = VectorStoreIndex.from_vector_store(vector_store=vector_store)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.embeddings.openai import OpenAIEmbedding\n",
    "from llama_index.llms.openai import OpenAI\n",
    "from llama_index.core.vector_stores import (\n",
    "    ExactMatchFilter,\n",
    "    MetadataFilters,\n",
    "    MetadataFilter,\n",
    "    FilterOperator,\n",
    "    FilterCondition,\n",
    ")\n",
    "\n",
    "\n",
    "filters = MetadataFilters(\n",
    "    filters=[\n",
    "        MetadataFilter(key=\"source\", value=\"lanchain_course\"),\n",
    "        MetadataFilter(key=\"source\", value=\"langchain_docs\"),\n",
    "    ],\n",
    "    condition=FilterCondition.OR,\n",
    ")\n",
    "\n",
    "llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo-0125\", max_tokens=None)\n",
    "embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
    "# query_engine = index.as_query_engine(\n",
    "#     llm=llm, similarity_top_k=5, embed_model=embeds, verbose=True, streaming=True, filters=filters\n",
    "# )\n",
    "query_engine = index.as_query_engine(\n",
    "    llm=llm, similarity_top_k=5, embed_model=embeds, verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = query_engine.query(\"What is the LLama model?\")\n",
    "\n",
    "# history = \"\"   \n",
    "# for token in res.response_gen:\n",
    "#     history += token\n",
    "#     print(history)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res.response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for src in res.source_nodes:\n",
    "  print(\"Node ID\\t\", src.node_id)\n",
    "  print(\"Source\\t\", src.metadata['source'])\n",
    "  print(\"Title\\t\", src.metadata['title'])\n",
    "  print(\"Text\\t\", src.text)\n",
    "  print(\"Score\\t\", src.score)\n",
    "  print(\"-_\"*20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import Markdown, display\n",
    "# define prompt viewing function\n",
    "def display_prompt_dict(prompts_dict):\n",
    "    for k, p in prompts_dict.items():\n",
    "        text_md = f\"**Prompt Key**: {k}<br>\" f\"**Text:** <br>\"\n",
    "        display(Markdown(text_md))\n",
    "        print(p.get_template())\n",
    "        display(Markdown(\"<br><br>\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompts_dict = query_engine.get_prompts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "display_prompt_dict(prompts_dict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env",
   "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
}