Omar Solano commited on
Commit
8fd1fd8
β€’
1 Parent(s): 6aaede5

experiment with new ai-tutor-db

Browse files
data/scraping/huggingface_docs/parse_hf_html.py CHANGED
@@ -147,10 +147,13 @@ def save_to_jsonl(data, output_file):
147
 
148
 
149
  def main():
150
- # html_dir = "huggingface_docs" # Directory where HTML files are saved
151
- html_dir = "transformers_docs_v4.42.0" # Directory where HTML files are saved
152
- base_url = "https://huggingface.co/docs/transformers/"
153
- output_file = "hf_transformers_v4_42_0.jsonl"
 
 
 
154
 
155
  all_sections = parse_saved_html_files(html_dir, base_url)
156
  save_to_jsonl(all_sections, output_file)
 
147
 
148
 
149
  def main():
150
+ # html_dir = "transformers_docs_v4.42.0" # Directory where HTML files are saved
151
+ # base_url = "https://huggingface.co/docs/transformers/"
152
+
153
+ html_dir = "peft_docs_v0.11.0" # Directory where HTML files are saved
154
+ base_url = "https://huggingface.co/docs/peft/"
155
+
156
+ output_file = "hf_peft_v0_11_0.jsonl"
157
 
158
  all_sections = parse_saved_html_files(html_dir, base_url)
159
  save_to_jsonl(all_sections, output_file)
data/scraping/huggingface_docs/scrape_hf_docs_from_web.py CHANGED
@@ -70,6 +70,7 @@ class DocsSpider(scrapy.Spider):
70
  f.write(response.body)
71
 
72
  self.pages.append({"url": response.url, "html": response.body})
 
73
  self.progress_bar.update(1)
74
 
75
  for href in response.css("a::attr(href)").getall():
 
70
  f.write(response.body)
71
 
72
  self.pages.append({"url": response.url, "html": response.body})
73
+ # if self.progress_bar:
74
  self.progress_bar.update(1)
75
 
76
  for href in response.css("a::attr(href)").getall():
scripts/create_db.ipynb CHANGED
@@ -4,7 +4,7 @@
4
  "cell_type": "markdown",
5
  "metadata": {},
6
  "source": [
7
- "# Create AI-Tutor vector database"
8
  ]
9
  },
10
  {
@@ -13,7 +13,6 @@
13
  "metadata": {},
14
  "outputs": [],
15
  "source": [
16
- "import os\n",
17
  "from dotenv import load_dotenv\n",
18
  "\n",
19
  "load_dotenv(\"../.env\")"
@@ -30,18 +29,76 @@
30
  "nest_asyncio.apply()"
31
  ]
32
  },
 
 
 
 
 
 
 
33
  {
34
  "cell_type": "code",
35
  "execution_count": null,
36
  "metadata": {},
37
  "outputs": [],
38
  "source": [
39
- "import chromadb\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  "\n",
41
- "# create client and a new collection\n",
42
- "# chromadb.EphemeralClient saves data in-memory.\n",
43
- "chroma_client = chromadb.PersistentClient(path=\"./ai-tutor-db\")\n",
44
- "chroma_collection = chroma_client.create_collection(\"ai-tutor-db\")"
45
  ]
46
  },
47
  {
@@ -50,13 +107,124 @@
50
  "metadata": {},
51
  "outputs": [],
52
  "source": [
53
- "from llama_index.vector_stores.chroma import ChromaVectorStore\n",
54
- "from llama_index.core import StorageContext\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  "\n",
56
- "vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
 
 
 
 
 
 
 
 
57
  "\n",
58
- "# Define a storage context object using the created vector store.\n",
59
- "storage_context = StorageContext.from_defaults(vector_store=vector_store)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  ]
61
  },
62
  {
@@ -65,29 +233,47 @@
65
  "metadata": {},
66
  "outputs": [],
67
  "source": [
 
 
68
  "import json\n",
69
- "from llama_index.core.schema import TextNode\n",
70
  "\n",
71
- "def load_jsonl_create_nodes(filepath):\n",
72
- " nodes = [] # List to hold the created node objects\n",
73
- " with open(filepath, \"r\") as file:\n",
74
- " for line in file:\n",
75
- " # Load each line as a JSON object\n",
76
- " json_obj = json.loads(line)\n",
77
- " # Extract required information\n",
78
- " title = json_obj.get(\"title\")\n",
79
- " url = json_obj.get(\"url\")\n",
80
- " content = json_obj.get(\"content\")\n",
81
- " source = json_obj.get(\"source\")\n",
82
- " # Create a TextNode object and append to the list\n",
83
- " node = TextNode(\n",
84
- " text=content,\n",
85
- " metadata={\"title\": title, \"url\": url, \"source\": source},\n",
86
- " excluded_embed_metadata_keys=[\"title\", \"url\", \"source\"],\n",
87
- " excluded_llm_metadata_keys=[\"title\", \"url\", \"source\"],\n",
 
 
 
 
 
 
 
 
 
 
 
88
  " )\n",
89
- " nodes.append(node)\n",
90
- " return nodes"
 
 
 
 
 
 
91
  ]
92
  },
93
  {
@@ -96,18 +282,265 @@
96
  "metadata": {},
97
  "outputs": [],
98
  "source": [
99
- "filepath = \"../combined_data.jsonl\"\n",
100
- "nodes = load_jsonl_create_nodes(filepath)\n",
101
  "\n",
102
- "print(f\"Loaded {len(nodes)} nodes/chunks from the JSONL file\\n \")\n",
 
 
 
103
  "\n",
104
- "node = nodes[0]\n",
105
- "print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")\n",
106
  "\n",
107
- "print(\"\\n\")\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  "\n",
109
- "node = nodes[-10000]\n",
110
- "print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  ]
112
  },
113
  {
@@ -138,16 +571,23 @@
138
  "metadata": {},
139
  "outputs": [],
140
  "source": [
141
- "from llama_index.embeddings.openai import OpenAIEmbedding\n",
142
- "from llama_index.core import VectorStoreIndex\n",
143
  "\n",
144
- "# embeds = OpenAIEmbedding(model=\"text-embedding-3-small\", mode=\"similarity\")\n",
145
- "# embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"similarity\")\n",
146
- "embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
147
- "# embeds = OpenAIEmbedding(model=\"text-embedding-ada-002\", mode=\"similarity\")\n",
148
  "\n",
149
- "# Build index / generate embeddings using OpenAI.\n",
150
- "index = VectorStoreIndex(nodes=nodes, show_progress=True, use_async=True, storage_context=storage_context, embed_model=embeds, insert_batch_size=3000,)"
 
 
 
 
 
 
 
151
  ]
152
  },
153
  {
@@ -156,10 +596,10 @@
156
  "metadata": {},
157
  "outputs": [],
158
  "source": [
159
- "from llama_index.llms.openai import OpenAI\n",
160
  "\n",
161
- "llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo\", max_tokens=None)\n",
162
- "query_engine = index.as_query_engine(llm=llm, similarity_top_k=5, embed_model=embeds)"
163
  ]
164
  },
165
  {
@@ -168,7 +608,7 @@
168
  "metadata": {},
169
  "outputs": [],
170
  "source": [
171
- "res = query_engine.query(\"What is the LLaMa model?\")"
172
  ]
173
  },
174
  {
@@ -177,7 +617,7 @@
177
  "metadata": {},
178
  "outputs": [],
179
  "source": [
180
- "res.response"
181
  ]
182
  },
183
  {
@@ -186,196 +626,128 @@
186
  "metadata": {},
187
  "outputs": [],
188
  "source": [
189
- "for src in res.source_nodes:\n",
190
- " print(\"Node ID\\t\", src.node_id)\n",
191
- " print(\"Title\\t\", src.metadata['title'])\n",
192
- " print(\"Text\\t\", src.text)\n",
193
- " print(\"Score\\t\", src.score)\n",
194
- " print(\"Metadata\\t\", src.metadata) \n",
195
- " print(\"-_\"*20)"
196
  ]
197
  },
198
  {
199
  "cell_type": "markdown",
200
  "metadata": {},
201
  "source": [
202
- "# Load DB from disk"
203
  ]
204
  },
205
  {
206
  "cell_type": "code",
207
- "execution_count": 1,
208
  "metadata": {},
209
- "outputs": [
210
- {
211
- "name": "stderr",
212
- "output_type": "stream",
213
- "text": [
214
- "INFO:chromadb.telemetry.product.posthog:Anonymized telemetry enabled. See https://docs.trychroma.com/telemetry for more information.\n",
215
- "INFO:chromadb.api.segment:Collection ai-tutor-db is not created.\n"
216
- ]
217
- }
218
- ],
219
  "source": [
220
- "import logging\n",
221
  "\n",
222
- "logger = logging.getLogger(__name__)\n",
223
- "logging.basicConfig(level=logging.INFO)\n",
224
  "\n",
225
  "\n",
226
- "import chromadb\n",
227
- "from llama_index.vector_stores.chroma import ChromaVectorStore\n",
228
- "# Create your index\n",
229
- "db2 = chromadb.PersistentClient(path=\"./ai-tutor-db\")\n",
230
- "chroma_collection = db2.get_or_create_collection(\"ai-tutor-db\")\n",
231
- "vector_store = ChromaVectorStore(chroma_collection=chroma_collection)"
 
232
  ]
233
  },
234
  {
235
  "cell_type": "code",
236
- "execution_count": 2,
237
  "metadata": {},
238
  "outputs": [],
239
  "source": [
240
- "# Create your index\n",
241
- "from llama_index.core import VectorStoreIndex\n",
242
- "index = VectorStoreIndex.from_vector_store(vector_store=vector_store)"
 
243
  ]
244
  },
245
  {
246
  "cell_type": "code",
247
- "execution_count": 3,
248
  "metadata": {},
249
  "outputs": [],
250
  "source": [
251
- "from llama_index.embeddings.openai import OpenAIEmbedding\n",
252
- "from llama_index.llms.openai import OpenAI\n",
253
- "from llama_index.core.vector_stores import (\n",
254
- " ExactMatchFilter,\n",
255
- " MetadataFilters,\n",
256
- " MetadataFilter,\n",
257
- " FilterOperator,\n",
258
- " FilterCondition,\n",
259
- ")\n",
260
  "\n",
261
- "filters = MetadataFilters(\n",
262
- " filters=[\n",
263
- " MetadataFilter(key=\"source\", value=\"lanchain_course\"),\n",
264
- " MetadataFilter(key=\"source\", value=\"langchain_docs\"),\n",
265
- " ],\n",
266
- " condition=FilterCondition.OR,\n",
267
- ")\n",
268
  "\n",
269
- "llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo\", max_tokens=None)\n",
270
- "embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
 
 
 
271
  "# query_engine = index.as_query_engine(\n",
272
- "# llm=llm, similarity_top_k=5, embed_model=embeds, verbose=True, streaming=True, filters=filters\n",
273
- "# )\n",
274
- "query_engine = index.as_query_engine(\n",
275
- " llm=llm, similarity_top_k=5, embed_model=embeds, verbose=True,\n",
276
- ")"
277
  ]
278
  },
279
  {
280
  "cell_type": "code",
281
- "execution_count": 4,
282
- "metadata": {},
283
- "outputs": [
284
- {
285
- "name": "stderr",
286
- "output_type": "stream",
287
- "text": [
288
- "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
289
- "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n"
290
- ]
291
- }
292
- ],
293
- "source": [
294
- "res = query_engine.query(\"What is the LLama model?\")\n",
295
- "\n",
296
- "# history = \"\" \n",
297
- "# for token in res.response_gen:\n",
298
- "# history += token\n",
299
- "# print(history)"
300
  ]
301
  },
302
  {
303
  "cell_type": "code",
304
- "execution_count": 5,
305
  "metadata": {},
306
- "outputs": [
307
- {
308
- "data": {
309
- "text/plain": [
310
- "'The LLama model is a family of large language models (LLMs) released by Meta AI, with different model sizes ranging from 7 billion to 65 billion parameters in the first version. The developers reported that the 13 billion parameter model outperformed larger models like GPT-3 and was competitive with state-of-the-art models like PaLM and Chinchilla. The model weights were released to the research community under a noncommercial license, but they were leaked to the public shortly after.'"
311
- ]
312
- },
313
- "execution_count": 5,
314
- "metadata": {},
315
- "output_type": "execute_result"
316
- }
317
- ],
318
  "source": [
319
- "res.response"
320
  ]
321
  },
322
  {
323
  "cell_type": "code",
324
- "execution_count": 6,
325
  "metadata": {},
326
- "outputs": [
327
- {
328
- "name": "stdout",
329
- "output_type": "stream",
330
- "text": [
331
- "Node ID\t 6f8c13d8-1458-444c-857b-c1dc11d7f134\n",
332
- "Source\t wikipedia\n",
333
- "Title\t LLaMA\n",
334
- "Text\t LLaMA LLaMA (Large Language Model Meta AI) is a family of large language models (LLMs), released by Meta AI starting in February 2023. For the first version of LLaMa, four model sizes were trained: 7, 13, 33 and 65 billion parameters. LLaMA's developers reported that the 13B parameter model's performance on most NLP benchmarks exceeded that of the much larger GPT-3 (with 175B parameters) and that the largest model was competitive with state of the art models such as PaLM and Chinchilla. Whereas the most powerful LLMs have generally been accessible only through limited APIs (if at all), Meta released LLaMA's model weights to the research community under a noncommercial license. Within a week of LLaMA's release, its weights were leaked to the public on 4chan via BitTorrent. In July 2023, Meta released several models as Llama 2, using 7, 13 and 70 billion parameters.\n",
335
- "Score\t 0.5133216393307418\n",
336
- "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
337
- "Node ID\t 7226ba39-fd90-4790-879f-9f6af7b4ac6d\n",
338
- "Source\t towards_ai\n",
339
- "Title\t Fine-Tuning a Llama-2 7B Model for Python Code Generation\n",
340
- "Text\t New Llama-2 model In mid-July, Meta released its new family of pre-trained and finetuned models called Llama-2, with an open source and commercial character to facilitate its use and expansion. The base model was released with a chat version and sizes 7B, 13B, and 70B. Together with the models, the corresponding papers were published describing their characteristics and relevant points of the learning process, which provide very interesting information on the subject. For pre-training, 40% more tokens were used, reaching 2T, the context length was doubled and the grouped-query attention (GQA) technique was applied to speed up inference on the heavier 70B model. On the standard transformer architecture, RMSNorm normalization, SwiGLU activation, and rotatory positional embedding are used, the context length reaches 4096 tokens, and an Adam optimizer is applied with a cosine learning rate schedule, a weight decay of 0.1 and gradient clipping. \n",
341
- "Score\t 0.49851718223076963\n",
342
- "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
343
- "Node ID\t a654d9c1-fa81-4ad8-b16a-06a49f145636\n",
344
- "Source\t hf_transformers\n",
345
- "Title\t Overview\n",
346
- "Text\t The Open-Llama model was proposed in Open-Llama project by community developer s-JoL.\n",
347
- "The model is mainly based on LLaMA with some modifications, incorporating memory-efficient attention from Xformers, stable embedding from Bloom, and shared input-output embedding from PaLM.\n",
348
- "And the model is pre-trained on both Chinese and English, which gives it better performance on Chinese language tasks.\n",
349
- "This model was contributed by s-JoL.\n",
350
- "The original code can be found Open-Llama.\n",
351
- "Checkpoint and usage can be found at s-JoL/Open-Llama-V1.\n",
352
- "Score\t 0.4888355341806359\n",
353
- "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
354
- "Node ID\t 846101f6-d9c5-4356-b569-c4383fe9b481\n",
355
- "Source\t towards_ai\n",
356
- "Title\t Meta's Llama 2: Revolutionizing Open Source Language Models for Commercial Use\n",
357
- "Text\t II. Llama 2 Model Flavors Llama 2 is available in four different model sizes: 7 billion, 13 billion, 34 billion, and 70 billion parameters. While 7B, 13B, and 70B have already been released, the 34B model is still awaited. The pretrained variant, trained on a whopping 2 trillion tokens, boasts a context window of 4096 tokens, twice the size of its predecessor Llama 1. Meta also released a Llama 2 fine-tuned model for chat applications that was trained on over 1 million human annotations. Such extensive training comes at a cost, with the 70B model taking a staggering 1720320 GPU hours to train. The context window's length determines the amount of content the model can process at once, making Llama 2 a powerful language model in terms of scale and efficiency. \n",
358
- "Score\t 0.4818213806198265\n",
359
- "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
360
- "Node ID\t bfffeff1-76d5-4ad4-9988-38be59ad9562\n",
361
- "Source\t hf_transformers\n",
362
- "Title\t Overview\n",
363
- "Text\t d 34B parameters each. All models are trained on sequences of 16k tokens and show improvements on inputs with up to 100k tokens. 7B and 13B Code Llama and Code Llama - Instruct variants support infilling based on surrounding content. Code Llama reaches state-of-the-art performance among open models on several code benchmarks, with scores of up to 53% and 55% on HumanEval and MBPP, respectively. Notably, Code Llama - Python 7B outperforms Llama 2 70B on HumanEval and MBPP, and all our models outperform every other publicly available model on MultiPL-E. We release Code Llama under a permissive license that allows for both research and commercial use.\n",
364
- "Check out all Code Llama models here and the officially released ones in the codellama org.\n",
365
- "The Llama2 family models, on which Code Llama is based, were trained using bfloat16, but the original inference uses float16. Let’s look at the different precisions: float32: PyTorch convention on model initialization is to load models in float32, no\n",
366
- "Score\t 0.4799444818466049\n",
367
- "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n"
368
- ]
369
- }
370
- ],
371
  "source": [
372
- "for src in res.source_nodes:\n",
373
- " print(\"Node ID\\t\", src.node_id)\n",
374
- " print(\"Source\\t\", src.metadata['source'])\n",
375
- " print(\"Title\\t\", src.metadata['title'])\n",
376
- " print(\"Text\\t\", src.text)\n",
377
- " print(\"Score\\t\", src.score)\n",
378
- " print(\"-_\"*20)"
379
  ]
380
  },
381
  {
@@ -384,14 +756,16 @@
384
  "metadata": {},
385
  "outputs": [],
386
  "source": [
387
- "from IPython.display import Markdown, display\n",
388
- "# define prompt viewing function\n",
389
- "def display_prompt_dict(prompts_dict):\n",
390
- " for k, p in prompts_dict.items():\n",
391
- " text_md = f\"**Prompt Key**: {k}<br>\" f\"**Text:** <br>\"\n",
392
- " display(Markdown(text_md))\n",
393
- " print(p.get_template())\n",
394
- " display(Markdown(\"<br><br>\"))"
 
 
395
  ]
396
  },
397
  {
@@ -400,7 +774,7 @@
400
  "metadata": {},
401
  "outputs": [],
402
  "source": [
403
- "prompts_dict = query_engine.get_prompts()"
404
  ]
405
  },
406
  {
@@ -409,7 +783,7 @@
409
  "metadata": {},
410
  "outputs": [],
411
  "source": [
412
- "display_prompt_dict(prompts_dict)"
413
  ]
414
  },
415
  {
@@ -450,7 +824,7 @@
450
  "name": "python",
451
  "nbconvert_exporter": "python",
452
  "pygments_lexer": "ipython3",
453
- "version": "3.11.8"
454
  }
455
  },
456
  "nbformat": 4,
 
4
  "cell_type": "markdown",
5
  "metadata": {},
6
  "source": [
7
+ "# Create AI-Tutor vector database\n"
8
  ]
9
  },
10
  {
 
13
  "metadata": {},
14
  "outputs": [],
15
  "source": [
 
16
  "from dotenv import load_dotenv\n",
17
  "\n",
18
  "load_dotenv(\"../.env\")"
 
29
  "nest_asyncio.apply()"
30
  ]
31
  },
32
+ {
33
+ "cell_type": "markdown",
34
+ "metadata": {},
35
+ "source": [
36
+ "### Clean data\n"
37
+ ]
38
+ },
39
  {
40
  "cell_type": "code",
41
  "execution_count": null,
42
  "metadata": {},
43
  "outputs": [],
44
  "source": [
45
+ "import json\n",
46
+ "import tiktoken\n",
47
+ "from collections import OrderedDict\n",
48
+ "\n",
49
+ "\n",
50
+ "def num_tokens_from_string(string: str, encoding_name: str) -> int:\n",
51
+ " \"\"\"Returns the number of tokens in a text string.\"\"\"\n",
52
+ " encoding = tiktoken.get_encoding(encoding_name)\n",
53
+ " num_tokens = len(\n",
54
+ " encoding.encode(\n",
55
+ " string, disallowed_special=(encoding.special_tokens_set - {\"<|endoftext|>\"})\n",
56
+ " )\n",
57
+ " )\n",
58
+ " return num_tokens\n",
59
+ "\n",
60
+ "\n",
61
+ "def clean_jsonl_file(input_filepath, output_filepath):\n",
62
+ " cleaned_data = []\n",
63
+ "\n",
64
+ " with open(input_filepath, \"r\") as file:\n",
65
+ " for line in file:\n",
66
+ " json_obj = json.loads(line)\n",
67
+ " content = json_obj.get(\"content\", \"\")\n",
68
+ " token_count = num_tokens_from_string(content, \"cl100k_base\")\n",
69
+ "\n",
70
+ " # Check conditions for keeping the line\n",
71
+ " if token_count > 7 and not (\n",
72
+ " token_count == 92 and json_obj.get(\"name\") == \"Transformers\"\n",
73
+ " ):\n",
74
+ " # Create a new OrderedDict with 'tokens' as the first key\n",
75
+ " new_obj = OrderedDict([(\"tokens\", token_count)])\n",
76
+ " # Add the rest of the key-value pairs from the original object\n",
77
+ " new_obj.update(json_obj)\n",
78
+ " cleaned_data.append(new_obj)\n",
79
+ "\n",
80
+ " with open(output_filepath, \"w\") as file:\n",
81
+ " for item in cleaned_data:\n",
82
+ " json.dump(item, file)\n",
83
+ " file.write(\"\\n\")\n",
84
+ "\n",
85
+ " print(f\"Original number of lines: {sum(1 for _ in open(input_filepath))}\")\n",
86
+ " print(f\"Cleaned number of lines: {len(cleaned_data)}\")\n",
87
+ "\n",
88
+ "\n",
89
+ "# Usage\n",
90
+ "input_filepath = \"../hf_transformers_v4_42_0.jsonl\"\n",
91
+ "output_filepath = \"../hf_transformers_v4_42_0_cleaned.jsonl\"\n",
92
+ "clean_jsonl_file(input_filepath, output_filepath)"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "markdown",
97
+ "metadata": {},
98
+ "source": [
99
+ "### Merges lines by 'URL' and creates a new file with the merged data.\n",
100
  "\n",
101
+ "Fixes the 'name'\n"
 
 
 
102
  ]
103
  },
104
  {
 
107
  "metadata": {},
108
  "outputs": [],
109
  "source": [
110
+ "import json\n",
111
+ "from collections import defaultdict\n",
112
+ "import tiktoken\n",
113
+ "\n",
114
+ "\n",
115
+ "def num_tokens_from_string(string: str, encoding_name: str) -> int:\n",
116
+ " \"\"\"Returns the number of tokens in a text string.\"\"\"\n",
117
+ " encoding = tiktoken.get_encoding(encoding_name)\n",
118
+ " num_tokens = len(\n",
119
+ " encoding.encode(\n",
120
+ " string, disallowed_special=(encoding.special_tokens_set - {\"<|endoftext|>\"})\n",
121
+ " )\n",
122
+ " )\n",
123
+ " return num_tokens\n",
124
+ "\n",
125
+ "\n",
126
+ "def should_not_merge(url):\n",
127
+ " \"\"\"Check if the URL contains any of the exclusion patterns.\"\"\"\n",
128
+ " exclusion_patterns = [\"model_doc\", \"internal\", \"main_classes\"]\n",
129
+ " return any(pattern in url for pattern in exclusion_patterns)\n",
130
+ "\n",
131
+ "\n",
132
+ "def merge_jsonl(input_file, output_file):\n",
133
+ " # Dictionary to store merged data\n",
134
+ " merged_data = defaultdict(list)\n",
135
+ "\n",
136
+ " # Read and process the input file\n",
137
+ " with open(input_file, \"r\") as f:\n",
138
+ " for line in f:\n",
139
+ " data = json.loads(line)\n",
140
+ " url = data[\"url\"]\n",
141
+ " merged_data[url].append(data)\n",
142
+ "\n",
143
+ " # Write the merged data to the output file\n",
144
+ " with open(output_file, \"w\") as f:\n",
145
+ " for url, entries in merged_data.items():\n",
146
+ " if len(entries) == 1 or should_not_merge(url):\n",
147
+ " # If there's only one entry or it shouldn't be merged, write all entries as is\n",
148
+ " for entry in entries:\n",
149
+ " entry[\"retrieve_doc\"] = False\n",
150
+ " json.dump(entry, f)\n",
151
+ " f.write(\"\\n\")\n",
152
+ " else:\n",
153
+ " # Merge the entries\n",
154
+ " merged_entry = entries[0].copy()\n",
155
+ " merged_entry[\"content\"] = \"\\n\\n\".join(\n",
156
+ " entry[\"content\"] for entry in entries\n",
157
+ " )\n",
158
+ " merged_entry[\"tokens\"] = num_tokens_from_string(\n",
159
+ " merged_entry[\"content\"], \"cl100k_base\"\n",
160
+ " )\n",
161
+ " merged_entry[\"retrieve_doc\"] = True\n",
162
+ " json.dump(merged_entry, f)\n",
163
+ " f.write(\"\\n\")\n",
164
+ "\n",
165
+ "\n",
166
+ "# Usage\n",
167
+ "input_file = \"../hf_transformers_v4_42_0_cleaned.jsonl\"\n",
168
+ "output_file = \"../hf_transformers_v4_42_0_merged.jsonl\"\n",
169
+ "merge_jsonl(input_file, output_file)"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "markdown",
174
+ "metadata": {},
175
+ "source": [
176
+ "### Count tokens of lines in merged file\n"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "execution_count": null,
182
+ "metadata": {},
183
+ "outputs": [],
184
+ "source": [
185
+ "# import json\n",
186
+ "# import tiktoken\n",
187
+ "\n",
188
  "\n",
189
+ "# def num_tokens_from_string(string: str, encoding_name: str) -> int:\n",
190
+ "# \"\"\"Returns the number of tokens in a text string.\"\"\"\n",
191
+ "# encoding = tiktoken.get_encoding(encoding_name)\n",
192
+ "# num_tokens = len(\n",
193
+ "# encoding.encode(\n",
194
+ "# string, disallowed_special=(encoding.special_tokens_set - {\"<|endoftext|>\"})\n",
195
+ "# )\n",
196
+ "# )\n",
197
+ "# return num_tokens\n",
198
  "\n",
199
+ "\n",
200
+ "# def count_tokens(input_file):\n",
201
+ "\n",
202
+ "# # Read and process the input file\n",
203
+ "# with open(input_file, \"r\") as f:\n",
204
+ "# for i, line in enumerate(f):\n",
205
+ "# data = json.loads(line)\n",
206
+ "# content = data[\"content\"]\n",
207
+ "# nb_tokens = num_tokens_from_string(content, \"cl100k_base\")\n",
208
+ "# # print(i + 1, data[\"url\"], nb_tokens)\n",
209
+ "# if nb_tokens > 2000:\n",
210
+ "# print(i + 1, data[\"url\"], data[\"name\"], nb_tokens)\n",
211
+ "# # if nb_tokens < 8:\n",
212
+ "# # print(nb_tokens)\n",
213
+ "# # print(data[\"url\"])\n",
214
+ "# # print(data[\"content\"])\n",
215
+ "\n",
216
+ "\n",
217
+ "# # Usage\n",
218
+ "# input_file = \"../hf_transformers_v4_42_0_merged.jsonl\"\n",
219
+ "# # input_file = \"../hf_transformers_v4_42_0.jsonl\"\n",
220
+ "# count_tokens(input_file)"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "metadata": {},
226
+ "source": [
227
+ "### Create a set of llama-index Documents\n"
228
  ]
229
  },
230
  {
 
233
  "metadata": {},
234
  "outputs": [],
235
  "source": [
236
+ "from llama_index.core import Document\n",
237
+ "from llama_index.core.schema import MetadataMode\n",
238
  "import json\n",
 
239
  "\n",
240
+ "\n",
241
+ "def create_docs(input_file):\n",
242
+ " with open(input_file, \"r\") as f:\n",
243
+ " documents = []\n",
244
+ " for i, line in enumerate(f):\n",
245
+ " data = json.loads(line)\n",
246
+ " documents.append(\n",
247
+ " Document(\n",
248
+ " text=data[\"content\"],\n",
249
+ " metadata={\n",
250
+ " \"url\": data[\"url\"],\n",
251
+ " \"title\": data[\"name\"],\n",
252
+ " \"tokens\": data[\"tokens\"],\n",
253
+ " \"retrieve_doc\": data[\"retrieve_doc\"],\n",
254
+ " },\n",
255
+ " excluded_llm_metadata_keys=[\n",
256
+ " \"url\",\n",
257
+ " \"title\",\n",
258
+ " \"tokens\",\n",
259
+ " \"retrieve_doc\",\n",
260
+ " ],\n",
261
+ " excluded_embed_metadata_keys=[\n",
262
+ " \"url\",\n",
263
+ " \"title\",\n",
264
+ " \"tokens\",\n",
265
+ " \"retrieve_doc\",\n",
266
+ " ],\n",
267
+ " )\n",
268
  " )\n",
269
+ " return documents\n",
270
+ "\n",
271
+ "\n",
272
+ "documents = create_docs(\"../hf_transformers_v4_42_0_merged.jsonl\")\n",
273
+ "print(documents[0])\n",
274
+ "print(documents[0].metadata)\n",
275
+ "\n",
276
+ "document_dict = {doc.doc_id: doc for doc in documents}"
277
  ]
278
  },
279
  {
 
282
  "metadata": {},
283
  "outputs": [],
284
  "source": [
285
+ "# import chromadb\n",
 
286
  "\n",
287
+ "# # create client and a new collection\n",
288
+ "# # chromadb.EphemeralClient saves data in-memory.\n",
289
+ "# chroma_client = chromadb.PersistentClient(path=\"./ai-tutor-dataset\")\n",
290
+ "# chroma_collection = chroma_client.create_collection(\"ai-tutor-dataset\")\n",
291
  "\n",
292
+ "# from llama_index.vector_stores.chroma import ChromaVectorStore\n",
293
+ "# from llama_index.core import StorageContext\n",
294
  "\n",
295
+ "# # Define a storage context object using the created vector database.\n",
296
+ "# vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
297
+ "# storage_context = StorageContext.from_defaults(vector_store=vector_store)"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "execution_count": null,
303
+ "metadata": {},
304
+ "outputs": [],
305
+ "source": [
306
+ "from llama_index.core import VectorStoreIndex\n",
307
+ "from llama_index.core.node_parser import SentenceSplitter\n",
308
+ "from llama_index.embeddings.openai import OpenAIEmbedding\n",
309
  "\n",
310
+ "# Build index / generate embeddings using OpenAI embedding model\n",
311
+ "index = VectorStoreIndex.from_documents(\n",
312
+ " documents,\n",
313
+ " # embed_model=OpenAIEmbedding(model=\"text-embedding-3-small\"),\n",
314
+ " embed_model=OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"similarity\"),\n",
315
+ " transformations=[SentenceSplitter(chunk_size=800, chunk_overlap=400)],\n",
316
+ " show_progress=True,\n",
317
+ " use_async=True,\n",
318
+ " # storage_context=storage_context,\n",
319
+ ")"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "execution_count": null,
325
+ "metadata": {},
326
+ "outputs": [],
327
+ "source": [
328
+ "# from llama_index.llms.openai import OpenAI\n",
329
+ "\n",
330
+ "# llm = OpenAI(temperature=1, model=\"gpt-3.5-turbo\", max_tokens=None)\n",
331
+ "# query_engine = index.as_query_engine(\n",
332
+ "# llm=llm,\n",
333
+ "# similarity_top_k=5,\n",
334
+ "# embed_model=OpenAIEmbedding(model=\"text-embedding-3-small\"),\n",
335
+ "# use_async=True,\n",
336
+ "# )\n",
337
+ "retriever = index.as_retriever(\n",
338
+ " similarity_top_k=10,\n",
339
+ " use_async=True,\n",
340
+ " embed_model=OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"similarity\"),\n",
341
+ " # embed_model=OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\"),\n",
342
+ ")"
343
+ ]
344
+ },
345
+ {
346
+ "cell_type": "code",
347
+ "execution_count": null,
348
+ "metadata": {},
349
+ "outputs": [],
350
+ "source": [
351
+ "from llama_index.core.data_structs import Node\n",
352
+ "from llama_index.core.schema import NodeWithScore\n",
353
+ "\n",
354
+ "# res = query_engine.query(\"What is the LLaMa model?\")\n",
355
+ "# res.response\n",
356
+ "\n",
357
+ "# query = \"fine-tune a pretrained model\"\n",
358
+ "# query = \"fine-tune an llm\"\n",
359
+ "query = \"how to fine-tune an llm?\"\n",
360
+ "\n",
361
+ "nodes_context = []\n",
362
+ "nodes = retriever.retrieve(query)\n",
363
+ "\n",
364
+ "\n",
365
+ "# # Filter nodes with the same ref_doc_id\n",
366
+ "# def filter_nodes_by_unique_doc_id(nodes):\n",
367
+ "# unique_nodes = {}\n",
368
+ "# for node in nodes:\n",
369
+ "# doc_id = node.node.ref_doc_id\n",
370
+ "# if doc_id is not None and doc_id not in unique_nodes:\n",
371
+ "# unique_nodes[doc_id] = node\n",
372
+ "# return list(unique_nodes.values())\n",
373
+ "\n",
374
+ "\n",
375
+ "# nodes = filter_nodes_by_unique_doc_id(nodes)\n",
376
+ "\n",
377
+ "for node in nodes:\n",
378
+ " print(\"Node ID\\t\", node.node_id)\n",
379
+ " print(\"Title\\t\", node.metadata[\"title\"])\n",
380
+ " print(\"Text\\t\", node.text)\n",
381
+ " print(\"Score\\t\", node.score)\n",
382
+ " print(\"Metadata\\t\", node.metadata)\n",
383
+ " print(\"-_\" * 20)\n",
384
+ " if node.metadata[\"retrieve_doc\"] == True:\n",
385
+ " print(\"This node will be replaced by the document\")\n",
386
+ " doc = document_dict[node.node.ref_doc_id]\n",
387
+ " # print(doc.text)\n",
388
+ " new_node = (\n",
389
+ " NodeWithScore(\n",
390
+ " node=Node(text=doc.text, metadata=node.metadata), score=node.score\n",
391
+ " ),\n",
392
+ " )\n",
393
+ " nodes_context.append(new_node)\n",
394
+ " else:\n",
395
+ " nodes_context.append(node)"
396
+ ]
397
+ },
398
+ {
399
+ "cell_type": "code",
400
+ "execution_count": null,
401
+ "metadata": {},
402
+ "outputs": [],
403
+ "source": [
404
+ "# from llama_index.core.schema import TextNode\n",
405
+ "\n",
406
+ "# for src in res.source_nodes:\n",
407
+ "# print(src.node.ref_doc_id)\n",
408
+ "# # print(src.node.get_metadata_str())\n",
409
+ "# print(\"Node ID\\t\", src.node_id)\n",
410
+ "# print(\"Title\\t\", src.metadata[\"title\"])\n",
411
+ "# print(\"Text\\t\", src.text)\n",
412
+ "# print(\"Score\\t\", src.score)\n",
413
+ "# print(\"Metadata\\t\", src.metadata)\n",
414
+ "# print(\"-_\" * 20)\n",
415
+ "# break"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "code",
420
+ "execution_count": null,
421
+ "metadata": {},
422
+ "outputs": [],
423
+ "source": [
424
+ "from llama_index.core.data_structs import Node\n",
425
+ "from llama_index.core.schema import NodeWithScore\n",
426
+ "from llama_index.core import get_response_synthesizer\n",
427
+ "from llama_index.llms.gemini import Gemini\n",
428
+ "from llama_index.llms.openai import OpenAI\n",
429
+ "\n",
430
+ "from tutor_prompts import (\n",
431
+ " TEXT_QA_TEMPLATE,\n",
432
+ ")\n",
433
+ "\n",
434
+ "\n",
435
+ "# llm = Gemini(model=\"models/gemini-1.5-flash\", temperature=1, max_tokens=None)\n",
436
+ "# llm = Gemini(model=\"models/gemini-1.5-pro\", temperature=1, max_tokens=None)\n",
437
+ "# llm = OpenAI(temperature=1, model=\"gpt-3.5-turbo\", max_tokens=None)\n",
438
+ "llm = OpenAI(temperature=1, model=\"gpt-4o\", max_tokens=None)\n",
439
+ "\n",
440
+ "response_synthesizer = get_response_synthesizer(\n",
441
+ " llm=llm, response_mode=\"simple_summarize\", text_qa_template=TEXT_QA_TEMPLATE\n",
442
+ ")\n",
443
+ "\n",
444
+ "response = response_synthesizer.synthesize(\n",
445
+ " query,\n",
446
+ " nodes=nodes,\n",
447
+ " # nodes=[\n",
448
+ " # NodeWithScore(\n",
449
+ " # node=Node(text=\"LLama2 model has a total of 2B parameters.\"), score=1.0\n",
450
+ " # ),\n",
451
+ " # ],\n",
452
+ " # text_chunks=[\"text1\", \"text2\", \"text3\"],\n",
453
+ ")\n",
454
+ "print(response.response)\n",
455
+ "# for src in response.source_nodes:\n",
456
+ "# print(src.node.ref_doc_id)\n",
457
+ "# print(\"Node ID\\t\", src.node_id)\n",
458
+ "# print(\"Title\\t\", src.metadata[\"title\"])\n",
459
+ "# print(\"Text\\t\", src.text)\n",
460
+ "# print(\"Score\\t\", src.score)\n",
461
+ "# print(\"Metadata\\t\", src.metadata)\n",
462
+ "# print(\"-_\" * 20)"
463
+ ]
464
+ },
465
+ {
466
+ "cell_type": "code",
467
+ "execution_count": null,
468
+ "metadata": {},
469
+ "outputs": [],
470
+ "source": [
471
+ "# import chromadb\n",
472
+ "\n",
473
+ "# # create client and a new collection\n",
474
+ "# # chromadb.EphemeralClient saves data in-memory.\n",
475
+ "# chroma_client = chromadb.PersistentClient(path=\"./ai-tutor-db\")\n",
476
+ "# chroma_collection = chroma_client.create_collection(\"ai-tutor-db\")"
477
+ ]
478
+ },
479
+ {
480
+ "cell_type": "code",
481
+ "execution_count": null,
482
+ "metadata": {},
483
+ "outputs": [],
484
+ "source": [
485
+ "# from llama_index.vector_stores.chroma import ChromaVectorStore\n",
486
+ "# from llama_index.core import StorageContext\n",
487
+ "\n",
488
+ "# vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
489
+ "\n",
490
+ "# # Define a storage context object using the created vector store.\n",
491
+ "# storage_context = StorageContext.from_defaults(vector_store=vector_store)"
492
+ ]
493
+ },
494
+ {
495
+ "cell_type": "code",
496
+ "execution_count": null,
497
+ "metadata": {},
498
+ "outputs": [],
499
+ "source": [
500
+ "# import json\n",
501
+ "# from llama_index.core.schema import TextNode\n",
502
+ "\n",
503
+ "\n",
504
+ "# def load_jsonl_create_nodes(filepath):\n",
505
+ "# nodes = [] # List to hold the created node objects\n",
506
+ "# with open(filepath, \"r\") as file:\n",
507
+ "# for line in file:\n",
508
+ "# # Load each line as a JSON object\n",
509
+ "# json_obj = json.loads(line)\n",
510
+ "# # Extract required information\n",
511
+ "# title = json_obj.get(\"title\")\n",
512
+ "# url = json_obj.get(\"url\")\n",
513
+ "# content = json_obj.get(\"content\")\n",
514
+ "# source = json_obj.get(\"source\")\n",
515
+ "# # Create a TextNode object and append to the list\n",
516
+ "# node = TextNode(\n",
517
+ "# text=content,\n",
518
+ "# metadata={\"title\": title, \"url\": url, \"source\": source},\n",
519
+ "# excluded_embed_metadata_keys=[\"title\", \"url\", \"source\"],\n",
520
+ "# excluded_llm_metadata_keys=[\"title\", \"url\", \"source\"],\n",
521
+ "# )\n",
522
+ "# nodes.append(node)\n",
523
+ "# return nodes"
524
+ ]
525
+ },
526
+ {
527
+ "cell_type": "code",
528
+ "execution_count": null,
529
+ "metadata": {},
530
+ "outputs": [],
531
+ "source": [
532
+ "# filepath = \"../combined_data.jsonl\"\n",
533
+ "# nodes = load_jsonl_create_nodes(filepath)\n",
534
+ "\n",
535
+ "# print(f\"Loaded {len(nodes)} nodes/chunks from the JSONL file\\n \")\n",
536
+ "\n",
537
+ "# node = nodes[0]\n",
538
+ "# print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")\n",
539
+ "\n",
540
+ "# print(\"\\n\")\n",
541
+ "\n",
542
+ "# node = nodes[-10000]\n",
543
+ "# print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")"
544
  ]
545
  },
546
  {
 
571
  "metadata": {},
572
  "outputs": [],
573
  "source": [
574
+ "# from llama_index.embeddings.openai import OpenAIEmbedding\n",
575
+ "# from llama_index.core import VectorStoreIndex\n",
576
  "\n",
577
+ "# # embeds = OpenAIEmbedding(model=\"text-embedding-3-small\", mode=\"similarity\")\n",
578
+ "# # embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"similarity\")\n",
579
+ "# embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
580
+ "# # embeds = OpenAIEmbedding(model=\"text-embedding-ada-002\", mode=\"similarity\")\n",
581
  "\n",
582
+ "# # Build index / generate embeddings using OpenAI.\n",
583
+ "# index = VectorStoreIndex(\n",
584
+ "# nodes=nodes,\n",
585
+ "# show_progress=True,\n",
586
+ "# use_async=True,\n",
587
+ "# storage_context=storage_context,\n",
588
+ "# embed_model=embeds,\n",
589
+ "# insert_batch_size=3000,\n",
590
+ "# )"
591
  ]
592
  },
593
  {
 
596
  "metadata": {},
597
  "outputs": [],
598
  "source": [
599
+ "# from llama_index.llms.openai import OpenAI\n",
600
  "\n",
601
+ "# llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo\", max_tokens=None)\n",
602
+ "# query_engine = index.as_query_engine(llm=llm, similarity_top_k=5, embed_model=embeds)"
603
  ]
604
  },
605
  {
 
608
  "metadata": {},
609
  "outputs": [],
610
  "source": [
611
+ "# res = query_engine.query(\"What is the LLaMa model?\")"
612
  ]
613
  },
614
  {
 
617
  "metadata": {},
618
  "outputs": [],
619
  "source": [
620
+ "# res.response"
621
  ]
622
  },
623
  {
 
626
  "metadata": {},
627
  "outputs": [],
628
  "source": [
629
+ "# for src in res.source_nodes:\n",
630
+ "# print(\"Node ID\\t\", src.node_id)\n",
631
+ "# print(\"Title\\t\", src.metadata[\"title\"])\n",
632
+ "# print(\"Text\\t\", src.text)\n",
633
+ "# print(\"Score\\t\", src.score)\n",
634
+ "# print(\"Metadata\\t\", src.metadata)\n",
635
+ "# print(\"-_\" * 20)"
636
  ]
637
  },
638
  {
639
  "cell_type": "markdown",
640
  "metadata": {},
641
  "source": [
642
+ "# Load DB from disk\n"
643
  ]
644
  },
645
  {
646
  "cell_type": "code",
647
+ "execution_count": null,
648
  "metadata": {},
649
+ "outputs": [],
 
 
 
 
 
 
 
 
 
650
  "source": [
651
+ "# import logging\n",
652
  "\n",
653
+ "# logger = logging.getLogger(__name__)\n",
654
+ "# logging.basicConfig(level=logging.INFO)\n",
655
  "\n",
656
  "\n",
657
+ "# import chromadb\n",
658
+ "# from llama_index.vector_stores.chroma import ChromaVectorStore\n",
659
+ "\n",
660
+ "# # Create your index\n",
661
+ "# db2 = chromadb.PersistentClient(path=\"./ai-tutor-db\")\n",
662
+ "# chroma_collection = db2.get_or_create_collection(\"ai-tutor-db\")\n",
663
+ "# vector_store = ChromaVectorStore(chroma_collection=chroma_collection)"
664
  ]
665
  },
666
  {
667
  "cell_type": "code",
668
+ "execution_count": null,
669
  "metadata": {},
670
  "outputs": [],
671
  "source": [
672
+ "# # Create your index\n",
673
+ "# from llama_index.core import VectorStoreIndex\n",
674
+ "\n",
675
+ "# index = VectorStoreIndex.from_vector_store(vector_store=vector_store)"
676
  ]
677
  },
678
  {
679
  "cell_type": "code",
680
+ "execution_count": null,
681
  "metadata": {},
682
  "outputs": [],
683
  "source": [
684
+ "# from llama_index.embeddings.openai import OpenAIEmbedding\n",
685
+ "# from llama_index.llms.openai import OpenAI\n",
686
+ "# from llama_index.core.vector_stores import (\n",
687
+ "# ExactMatchFilter,\n",
688
+ "# MetadataFilters,\n",
689
+ "# MetadataFilter,\n",
690
+ "# FilterOperator,\n",
691
+ "# FilterCondition,\n",
692
+ "# )\n",
693
  "\n",
694
+ "# filters = MetadataFilters(\n",
695
+ "# filters=[\n",
696
+ "# MetadataFilter(key=\"source\", value=\"lanchain_course\"),\n",
697
+ "# MetadataFilter(key=\"source\", value=\"langchain_docs\"),\n",
698
+ "# ],\n",
699
+ "# condition=FilterCondition.OR,\n",
700
+ "# )\n",
701
  "\n",
702
+ "# llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo\", max_tokens=None)\n",
703
+ "# embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
704
+ "# # query_engine = index.as_query_engine(\n",
705
+ "# # llm=llm, similarity_top_k=5, embed_model=embeds, verbose=True, streaming=True, filters=filters\n",
706
+ "# # )\n",
707
  "# query_engine = index.as_query_engine(\n",
708
+ "# llm=llm,\n",
709
+ "# similarity_top_k=5,\n",
710
+ "# embed_model=embeds,\n",
711
+ "# verbose=True,\n",
712
+ "# )"
713
  ]
714
  },
715
  {
716
  "cell_type": "code",
717
+ "execution_count": null,
718
+ "metadata": {},
719
+ "outputs": [],
720
+ "source": [
721
+ "# res = query_engine.query(\"What is the LLama model?\")\n",
722
+ "\n",
723
+ "# # history = \"\"\n",
724
+ "# # for token in res.response_gen:\n",
725
+ "# # history += token\n",
726
+ "# # print(history)"
 
 
 
 
 
 
 
 
 
727
  ]
728
  },
729
  {
730
  "cell_type": "code",
731
+ "execution_count": null,
732
  "metadata": {},
733
+ "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
734
  "source": [
735
+ "# res.response"
736
  ]
737
  },
738
  {
739
  "cell_type": "code",
740
+ "execution_count": null,
741
  "metadata": {},
742
+ "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743
  "source": [
744
+ "# for src in res.source_nodes:\n",
745
+ "# print(\"Node ID\\t\", src.node_id)\n",
746
+ "# print(\"Source\\t\", src.metadata[\"source\"])\n",
747
+ "# print(\"Title\\t\", src.metadata[\"title\"])\n",
748
+ "# print(\"Text\\t\", src.text)\n",
749
+ "# print(\"Score\\t\", src.score)\n",
750
+ "# print(\"-_\" * 20)"
751
  ]
752
  },
753
  {
 
756
  "metadata": {},
757
  "outputs": [],
758
  "source": [
759
+ "# from IPython.display import Markdown, display\n",
760
+ "\n",
761
+ "\n",
762
+ "# # define prompt viewing function\n",
763
+ "# def display_prompt_dict(prompts_dict):\n",
764
+ "# for k, p in prompts_dict.items():\n",
765
+ "# text_md = f\"**Prompt Key**: {k}<br>\" f\"**Text:** <br>\"\n",
766
+ "# display(Markdown(text_md))\n",
767
+ "# print(p.get_template())\n",
768
+ "# display(Markdown(\"<br><br>\"))"
769
  ]
770
  },
771
  {
 
774
  "metadata": {},
775
  "outputs": [],
776
  "source": [
777
+ "# prompts_dict = query_engine.get_prompts()"
778
  ]
779
  },
780
  {
 
783
  "metadata": {},
784
  "outputs": [],
785
  "source": [
786
+ "# display_prompt_dict(prompts_dict)"
787
  ]
788
  },
789
  {
 
824
  "name": "python",
825
  "nbconvert_exporter": "python",
826
  "pygments_lexer": "ipython3",
827
+ "version": "3.12.3"
828
  }
829
  },
830
  "nbformat": 4,