File size: 31,872 Bytes
919910a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For text TextFileToDocument\n",
    "for pdf PyPDFToDocument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/unity/f2/asugandhi/Downloads/LLM_Playground\n",
      "\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "Input batch_size not found in component PdfFileConverter.",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[21], line 27\u001b[0m\n\u001b[1;32m     25\u001b[0m pipeline\u001b[38;5;241m.\u001b[39mconnect(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPdfFileConverter\u001b[39m\u001b[38;5;124m\"\u001b[39m,\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPdfwriter_chroma\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m     26\u001b[0m pipeline\u001b[38;5;241m.\u001b[39mconnect(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTextFileConverter\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mwriter_chroma\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m---> 27\u001b[0m \u001b[43mpipeline\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m     28\u001b[0m \u001b[43m    \u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mPdfFileConverter\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43msources\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mfile_paths\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mbatch_size\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m}\u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m     29\u001b[0m \u001b[43m    \u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mTextFileConverter\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43msources\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mfile_paths\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mbatch_size\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m}\u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m     30\u001b[0m \u001b[43m)\u001b[49m\n\u001b[1;32m     33\u001b[0m querying \u001b[38;5;241m=\u001b[39m Pipeline()\n\u001b[1;32m     34\u001b[0m reader \u001b[38;5;241m=\u001b[39m ExtractiveReader(model\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mdeepset/roberta-base-squad2-distilled\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
      "File \u001b[0;32m/conda/asugandhi/miniconda3/envs/RAGAPP/lib/python3.10/site-packages/haystack/core/pipeline/pipeline.py:688\u001b[0m, in \u001b[0;36mPipeline.run\u001b[0;34m(self, data, debug)\u001b[0m\n\u001b[1;32m    682\u001b[0m         logger\u001b[38;5;241m.\u001b[39mwarning(\n\u001b[1;32m    683\u001b[0m             \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInputs \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m were not matched to any component inputs, please check your run parameters.\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m    684\u001b[0m             \u001b[38;5;28mlist\u001b[39m(unresolved_inputs\u001b[38;5;241m.\u001b[39mkeys()),\n\u001b[1;32m    685\u001b[0m         )\n\u001b[1;32m    687\u001b[0m \u001b[38;5;66;03m# Raise if input is malformed in some way\u001b[39;00m\n\u001b[0;32m--> 688\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_validate_input\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdata\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    689\u001b[0m \u001b[38;5;66;03m# NOTE: The above NOTE and TODO are technically not true.\u001b[39;00m\n\u001b[1;32m    690\u001b[0m \u001b[38;5;66;03m# This implementation of run supports only the first format, but the second format is actually\u001b[39;00m\n\u001b[1;32m    691\u001b[0m \u001b[38;5;66;03m# never received by this method. It's handled by the `run()` method of the `Pipeline` class\u001b[39;00m\n\u001b[0;32m   (...)\u001b[0m\n\u001b[1;32m    695\u001b[0m \u001b[38;5;66;03m# deepcopying the inputs prevents the Pipeline run logic from being altered unexpectedly\u001b[39;00m\n\u001b[1;32m    696\u001b[0m \u001b[38;5;66;03m# when the same input reference is passed to multiple components.\u001b[39;00m\n\u001b[1;32m    697\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m component_name, component_inputs \u001b[38;5;129;01min\u001b[39;00m data\u001b[38;5;241m.\u001b[39mitems():\n",
      "File \u001b[0;32m/conda/asugandhi/miniconda3/envs/RAGAPP/lib/python3.10/site-packages/haystack/core/pipeline/pipeline.py:594\u001b[0m, in \u001b[0;36mPipeline._validate_input\u001b[0;34m(self, data)\u001b[0m\n\u001b[1;32m    592\u001b[0m     \u001b[38;5;28;01mfor\u001b[39;00m input_name \u001b[38;5;129;01min\u001b[39;00m component_inputs\u001b[38;5;241m.\u001b[39mkeys():\n\u001b[1;32m    593\u001b[0m         \u001b[38;5;28;01mif\u001b[39;00m input_name \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m instance\u001b[38;5;241m.\u001b[39m__haystack_input__\u001b[38;5;241m.\u001b[39m_sockets_dict:\n\u001b[0;32m--> 594\u001b[0m             \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInput \u001b[39m\u001b[38;5;132;01m{\u001b[39;00minput_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m not found in component \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcomponent_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m    596\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m component_name \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mgraph\u001b[38;5;241m.\u001b[39mnodes:\n\u001b[1;32m    597\u001b[0m     instance \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mgraph\u001b[38;5;241m.\u001b[39mnodes[component_name][\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124minstance\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n",
      "\u001b[0;31mValueError\u001b[0m: Input batch_size not found in component PdfFileConverter."
     ]
    }
   ],
   "source": [
    "import os\n",
    "from haystack import Pipeline, Document\n",
    "from haystack.components.converters import TextFileToDocument, PyPDFToDocument\n",
    "from haystack.components.writers import DocumentWriter\n",
    "from haystack.components.readers import ExtractiveReader\n",
    "from haystack_integrations.document_stores.chroma import ChromaDocumentStore\n",
    "from haystack_integrations.components.retrievers.chroma import ChromaQueryTextRetriever\n",
    "from pathlib import Path\n",
    "HERE = Path(os.getcwd())\n",
    "print(HERE)\n",
    "\n",
    "data_path = HERE / \"data\"\n",
    "file_paths = [data_path / Path(name) for name in os.listdir(\"data\")]\n",
    "print()\n",
    "chroma_store = ChromaDocumentStore()\n",
    "# Resolve the absolute path\n",
    "# absolute_file_path = file_path.resolve()\n",
    "# print(absolute_file_path)\n",
    "pipeline = Pipeline()\n",
    "pipeline.add_component(\"PdfFileConverter\", PyPDFToDocument())\n",
    "pipeline.add_component(\"TextFileConverter\", TextFileToDocument())\n",
    "pipeline.add_component(\"Pdfwriter_chroma\", DocumentWriter(document_store=chroma_store))\n",
    "pipeline.add_component(\"writer_chroma\", DocumentWriter(document_store=chroma_store))\n",
    "\n",
    "pipeline.connect(\"PdfFileConverter\",\"Pdfwriter_chroma\")\n",
    "pipeline.connect(\"TextFileConverter\", \"writer_chroma\")\n",
    "pipeline.run(\n",
    "    {\"PdfFileConverter\": {\"sources\": file_paths, \"batch_size\": 1}},\n",
    "    {\"TextFileConverter\": {\"sources\": file_paths, \"batch_size\": 1}},\n",
    ")\n",
    "    \n",
    "    \n",
    "querying = Pipeline()\n",
    "reader = ExtractiveReader(model=\"deepset/roberta-base-squad2-distilled\")\n",
    "querying.add_component(\"retriever\", ChromaQueryTextRetriever(chroma_store))\n",
    "querying.add_component(\"reader\",reader)\n",
    "results = querying.run({\"retriever\": {\"query\": \"Vishwam\", \"top_k\": 3}})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/unity/f2/asugandhi/Downloads/LLM_Playground\n",
      "{'reader': {'answers': [ExtractedAnswer(query='Who is Aditya?', score=0.6858945488929749, data='Software Engineer', document=Document(id=ce02ebe3fa97972f0c76b2c175f658873b2d0e19987e9cbc38dcacb25b8ebdba, content: 'Aditya Sugandhi's journey as a Software Engineer is characterized by a deep commitment to excellence...', meta: {'file_path': '/unity/f2/asugandhi/Downloads/LLM_Playground/data/Aditya_train.txt', 'source_id': '228fb178549cb032d67e0b2da301131f48d7c88c814b6d6920c92727b1c8f5fd'}, score: 1.191292405128479, embedding: vector of size 384), context=None, document_offset=ExtractedAnswer.Span(start=31, end=48), context_offset=None, meta={}), ExtractedAnswer(query='Who is Aditya?', score=0.627069890499115, data='Sugandhi', document=Document(id=ce02ebe3fa97972f0c76b2c175f658873b2d0e19987e9cbc38dcacb25b8ebdba, content: 'Aditya Sugandhi's journey as a Software Engineer is characterized by a deep commitment to excellence...', meta: {'file_path': '/unity/f2/asugandhi/Downloads/LLM_Playground/data/Aditya_train.txt', 'source_id': '228fb178549cb032d67e0b2da301131f48d7c88c814b6d6920c92727b1c8f5fd'}, score: 1.191292405128479, embedding: vector of size 384), context=None, document_offset=ExtractedAnswer.Span(start=7, end=15), context_offset=None, meta={}), ExtractedAnswer(query='Who is Aditya?', score=0.5672385096549988, data='Software Engineer', document=Document(id=ce02ebe3fa97972f0c76b2c175f658873b2d0e19987e9cbc38dcacb25b8ebdba, content: 'Aditya Sugandhi's journey as a Software Engineer is characterized by a deep commitment to excellence...', meta: {'file_path': '/unity/f2/asugandhi/Downloads/LLM_Playground/data/Aditya_train.txt', 'source_id': '228fb178549cb032d67e0b2da301131f48d7c88c814b6d6920c92727b1c8f5fd'}, score: 1.191292405128479, embedding: vector of size 384), context=None, document_offset=ExtractedAnswer.Span(start=4616, end=4633), context_offset=None, meta={}), ExtractedAnswer(query='Who is Aditya?', score=0.5219605565071106, data='software engineer', document=Document(id=ce02ebe3fa97972f0c76b2c175f658873b2d0e19987e9cbc38dcacb25b8ebdba, content: 'Aditya Sugandhi's journey as a Software Engineer is characterized by a deep commitment to excellence...', meta: {'file_path': '/unity/f2/asugandhi/Downloads/LLM_Playground/data/Aditya_train.txt', 'source_id': '228fb178549cb032d67e0b2da301131f48d7c88c814b6d6920c92727b1c8f5fd'}, score: 1.191292405128479, embedding: vector of size 384), context=None, document_offset=ExtractedAnswer.Span(start=4961, end=4978), context_offset=None, meta={}), ExtractedAnswer(query='Who is Aditya?', score=0.5016087889671326, data='Sugandhi', document=Document(id=ce02ebe3fa97972f0c76b2c175f658873b2d0e19987e9cbc38dcacb25b8ebdba, content: 'Aditya Sugandhi's journey as a Software Engineer is characterized by a deep commitment to excellence...', meta: {'file_path': '/unity/f2/asugandhi/Downloads/LLM_Playground/data/Aditya_train.txt', 'source_id': '228fb178549cb032d67e0b2da301131f48d7c88c814b6d6920c92727b1c8f5fd'}, score: 1.191292405128479, embedding: vector of size 384), context=None, document_offset=ExtractedAnswer.Span(start=4592, end=4600), context_offset=None, meta={}), ExtractedAnswer(query='Who is Aditya?', score=0.44805991649627686, data='Web Developer Intern', document=Document(id=ce02ebe3fa97972f0c76b2c175f658873b2d0e19987e9cbc38dcacb25b8ebdba, content: 'Aditya Sugandhi's journey as a Software Engineer is characterized by a deep commitment to excellence...', meta: {'file_path': '/unity/f2/asugandhi/Downloads/LLM_Playground/data/Aditya_train.txt', 'source_id': '228fb178549cb032d67e0b2da301131f48d7c88c814b6d6920c92727b1c8f5fd'}, score: 1.191292405128479, embedding: vector of size 384), context=None, document_offset=ExtractedAnswer.Span(start=3343, end=3363), context_offset=None, meta={}), ExtractedAnswer(query='Who is Aditya?', score=0.0066661882226549205, data=None, document=None, context=None, document_offset=None, context_offset=None, meta={})]}}\n"
     ]
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "import os\n",
    "from haystack import Pipeline\n",
    "from haystack.components.embedders import SentenceTransformersDocumentEmbedder\n",
    "from haystack.components.converters import PyPDFToDocument, TextFileToDocument\n",
    "from haystack.components.preprocessors import DocumentCleaner, DocumentSplitter\n",
    "from haystack.components.readers import ExtractiveReader\n",
    "from haystack.components.routers import FileTypeRouter\n",
    "from haystack.components.joiners import DocumentJoiner\n",
    "from haystack.components.writers import DocumentWriter\n",
    "from haystack_integrations.document_stores.chroma import ChromaDocumentStore\n",
    "from haystack_integrations.components.retrievers.chroma import ChromaQueryTextRetriever\n",
    "\n",
    "HERE = Path(os.getcwd())\n",
    "print(HERE)\n",
    "\n",
    "data_path = HERE / \"data\"\n",
    "file_paths = [str(data_path / name) for name in os.listdir(data_path)]\n",
    "\n",
    "chroma_store = ChromaDocumentStore()\n",
    "\n",
    "pipeline = Pipeline()\n",
    "pipeline.add_component(\"FileTypeRouter\", FileTypeRouter(mime_types=[\"text/plain\", \"application/pdf\"]))\n",
    "pipeline.add_component(\"TextFileConverter\", TextFileToDocument())\n",
    "pipeline.add_component(\"PdfFileConverter\", PyPDFToDocument())\n",
    "pipeline.add_component(\"Joiner\", DocumentJoiner())\n",
    "pipeline.add_component(\"Cleaner\", DocumentCleaner())\n",
    "pipeline.add_component(\"Splitter\", DocumentSplitter(split_by=\"sentence\", split_length=250, split_overlap=30))\n",
    "# pipeline.add_component(\"Embedder\", SentenceTransformersDocumentEmbedder(model=\"sentence-transformers/all-MiniLM-L6-v2\"))\n",
    "pipeline.add_component(\"Writer\", DocumentWriter(document_store=chroma_store))\n",
    "\n",
    "pipeline.connect(\"FileTypeRouter.text/plain\", \"TextFileConverter.sources\")\n",
    "pipeline.connect(\"FileTypeRouter.application/pdf\", \"PdfFileConverter.sources\")\n",
    "pipeline.connect(\"TextFileConverter.documents\", \"Joiner.documents\")\n",
    "pipeline.connect(\"PdfFileConverter.documents\", \"Joiner.documents\")\n",
    "pipeline.connect(\"Joiner.documents\", \"Cleaner.documents\")\n",
    "pipeline.connect(\"Cleaner.documents\", \"Splitter.documents\")\n",
    "pipeline.connect(\"Splitter.documents\", \"Writer.documents\")\n",
    "# pipeline.connect(\"Embedder.documents\", \"Writer.documents\")\n",
    "\n",
    "pipeline.run(\n",
    "    {\"FileTypeRouter\": {\"sources\": file_paths}},\n",
    ")\n",
    "\n",
    "# Querying pipeline\n",
    "querying = Pipeline()\n",
    "reader = ExtractiveReader(model=\"deepset/roberta-base-squad2-distilled\")\n",
    "querying.add_component(\"retriever\", ChromaQueryTextRetriever(chroma_store))\n",
    "querying.add_component(\"reader\", reader)\n",
    "querying.connect(\"retriever\", \"reader\")\n",
    "query = \"Who is Aditya?\"\n",
    "input_data = {\n",
    "        \"retriever\": {\"query\": query, \"top_k\": 1},\n",
    "        \"reader\": {\"query\": query},\n",
    "        # Use 'max_tokens' instead of 'max_new_tokens'\n",
    "    }\n",
    "results = querying.run(input_data)\n",
    "print(results)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#DON'T RUN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "who is Aditya?\n",
      "{'llm': {'replies': ['Aditya Sugandhi is a Software Engineer with a strong foundation in both theoretical knowledge and practical application, known for his commitment to excellence, passion for technological advancements, and dedication to pushing boundaries in software development. He has experience in various roles such as a Research Assistant, Full Stack Developer, Customer Service Executive, and Web Developer Intern. Aditya is currently pursuing a Master’s of Science in Computer Science at Florida State University and holds a Bachelor of Technology in Computer Science Engineering from SRM University. He is characterized by technical excellence, innovation, and a holistic understanding of software development. Aditya enjoys spending time with his friends SAS, Hunterr, MF, and Rocco.'], 'meta': [{'model': 'gpt-3.5-turbo-0125', 'index': 0, 'finish_reason': 'stop', 'usage': {'completion_tokens': 138, 'prompt_tokens': 917, 'total_tokens': 1055}}]}}\n"
     ]
    }
   ],
   "source": [
    "from haystack import Pipeline\n",
    "from haystack.utils import Secret\n",
    "from haystack_integrations.components.retrievers.chroma import ChromaQueryTextRetriever\n",
    "from haystack.components.readers import ExtractiveReader\n",
    "from haystack.components.generators import GPTGenerator\n",
    "from haystack.components.builders.prompt_builder import PromptBuilder\n",
    "from haystack.components.generators import OpenAIGenerator\n",
    "\n",
    "template = \"\"\"\n",
    "Answer all the questions in the following format and based on Aditya.\n",
    "\n",
    "Context:\n",
    "{% for doc in documents %}\n",
    "  {{ doc.content }}\n",
    "{% endfor %}\n",
    "Question: {{question}}\n",
    "Answer:\n",
    "\"\"\"\n",
    "\n",
    "prompt_builder = PromptBuilder(template=template)\n",
    "retriever = ChromaQueryTextRetriever(document_store = chroma_store)\n",
    "#ExtractiveReader to extract answers from the relevant context\n",
    "api_key = Secret.from_token(\"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\")\n",
    "llm = OpenAIGenerator(model=\"gpt-3.5-turbo-0125\",api_key=api_key)\n",
    "reader = ExtractiveReader(model=\"deepset/roberta-base-squad2-distilled\")\n",
    "\n",
    "extractive_qa_pipeline = Pipeline()\n",
    "extractive_qa_pipeline.add_component(\"retriever\", retriever)\n",
    "# extractive_qa_pipeline.add_component(\"reader\",reader)\n",
    "extractive_qa_pipeline.add_component(instance=prompt_builder, name=\"prompt_builder\")\n",
    "extractive_qa_pipeline.add_component(\"llm\", llm)\n",
    "\n",
    "\n",
    "# extractive_qa_pipeline.connect(\"retriever\", \"reader\")\n",
    "extractive_qa_pipeline.connect(\"retriever\", \"prompt_builder.documents\")\n",
    "extractive_qa_pipeline.connect(\"prompt_builder\", \"llm\")\n",
    "\n",
    "\n",
    "query = \"who is Aditya?\"\n",
    "print(query)\n",
    "# Define the input data for the pipeline components\n",
    "input_data = {\n",
    "    \"retriever\": {\"query\": query, \"top_k\": 1},\n",
    "    \"prompt_builder\": {\"question\": query},\n",
    "     # Use 'max_tokens' instead of 'max_new_tokens'\n",
    "}\n",
    "\n",
    "# Run the pipeline with the updated input data\n",
    "results = extractive_qa_pipeline.run(input_data)\n",
    "print(results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "llama_model_loader: loaded meta data with 23 key-value pairs and 291 tensors from openchat-3.5-1210.Q3_K_S.ggml (version GGUF V3 (latest))\n",
      "llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n",
      "llama_model_loader: - kv   0:                       general.architecture str              = llama\n",
      "llama_model_loader: - kv   1:                               general.name str              = openchat_openchat-3.5-1210\n",
      "llama_model_loader: - kv   2:                       llama.context_length u32              = 8192\n",
      "llama_model_loader: - kv   3:                     llama.embedding_length u32              = 4096\n",
      "llama_model_loader: - kv   4:                          llama.block_count u32              = 32\n",
      "llama_model_loader: - kv   5:                  llama.feed_forward_length u32              = 14336\n",
      "llama_model_loader: - kv   6:                 llama.rope.dimension_count u32              = 128\n",
      "llama_model_loader: - kv   7:                 llama.attention.head_count u32              = 32\n",
      "llama_model_loader: - kv   8:              llama.attention.head_count_kv u32              = 8\n",
      "llama_model_loader: - kv   9:     llama.attention.layer_norm_rms_epsilon f32              = 0.000010\n",
      "llama_model_loader: - kv  10:                       llama.rope.freq_base f32              = 10000.000000\n",
      "llama_model_loader: - kv  11:                          general.file_type u32              = 11\n",
      "llama_model_loader: - kv  12:                       tokenizer.ggml.model str              = llama\n",
      "llama_model_loader: - kv  13:                      tokenizer.ggml.tokens arr[str,32002]   = [\"<unk>\", \"<s>\", \"</s>\", \"<0x00>\", \"<...\n",
      "llama_model_loader: - kv  14:                      tokenizer.ggml.scores arr[f32,32002]   = [0.000000, 0.000000, 0.000000, 0.0000...\n",
      "llama_model_loader: - kv  15:                  tokenizer.ggml.token_type arr[i32,32002]   = [2, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...\n",
      "llama_model_loader: - kv  16:                tokenizer.ggml.bos_token_id u32              = 1\n",
      "llama_model_loader: - kv  17:                tokenizer.ggml.eos_token_id u32              = 32000\n",
      "llama_model_loader: - kv  18:            tokenizer.ggml.padding_token_id u32              = 0\n",
      "llama_model_loader: - kv  19:               tokenizer.ggml.add_bos_token bool             = true\n",
      "llama_model_loader: - kv  20:               tokenizer.ggml.add_eos_token bool             = false\n",
      "llama_model_loader: - kv  21:                    tokenizer.chat_template str              = {{ bos_token }}{% for message in mess...\n",
      "llama_model_loader: - kv  22:               general.quantization_version u32              = 2\n",
      "llama_model_loader: - type  f32:   65 tensors\n",
      "llama_model_loader: - type q3_K:  225 tensors\n",
      "llama_model_loader: - type q6_K:    1 tensors\n",
      "llm_load_vocab: special tokens definition check successful ( 261/32002 ).\n",
      "llm_load_print_meta: format           = GGUF V3 (latest)\n",
      "llm_load_print_meta: arch             = llama\n",
      "llm_load_print_meta: vocab type       = SPM\n",
      "llm_load_print_meta: n_vocab          = 32002\n",
      "llm_load_print_meta: n_merges         = 0\n",
      "llm_load_print_meta: n_ctx_train      = 8192\n",
      "llm_load_print_meta: n_embd           = 4096\n",
      "llm_load_print_meta: n_head           = 32\n",
      "llm_load_print_meta: n_head_kv        = 8\n",
      "llm_load_print_meta: n_layer          = 32\n",
      "llm_load_print_meta: n_rot            = 128\n",
      "llm_load_print_meta: n_embd_head_k    = 128\n",
      "llm_load_print_meta: n_embd_head_v    = 128\n",
      "llm_load_print_meta: n_gqa            = 4\n",
      "llm_load_print_meta: n_embd_k_gqa     = 1024\n",
      "llm_load_print_meta: n_embd_v_gqa     = 1024\n",
      "llm_load_print_meta: f_norm_eps       = 0.0e+00\n",
      "llm_load_print_meta: f_norm_rms_eps   = 1.0e-05\n",
      "llm_load_print_meta: f_clamp_kqv      = 0.0e+00\n",
      "llm_load_print_meta: f_max_alibi_bias = 0.0e+00\n",
      "llm_load_print_meta: n_ff             = 14336\n",
      "llm_load_print_meta: n_expert         = 0\n",
      "llm_load_print_meta: n_expert_used    = 0\n",
      "llm_load_print_meta: rope scaling     = linear\n",
      "llm_load_print_meta: freq_base_train  = 10000.0\n",
      "llm_load_print_meta: freq_scale_train = 1\n",
      "llm_load_print_meta: n_yarn_orig_ctx  = 8192\n",
      "llm_load_print_meta: rope_finetuned   = unknown\n",
      "llm_load_print_meta: model type       = 7B\n",
      "llm_load_print_meta: model ftype      = Q3_K - Small\n",
      "llm_load_print_meta: model params     = 7.24 B\n",
      "llm_load_print_meta: model size       = 2.95 GiB (3.50 BPW) \n",
      "llm_load_print_meta: general.name     = openchat_openchat-3.5-1210\n",
      "llm_load_print_meta: BOS token        = 1 '<s>'\n",
      "llm_load_print_meta: EOS token        = 32000 '<|end_of_turn|>'\n",
      "llm_load_print_meta: UNK token        = 0 '<unk>'\n",
      "llm_load_print_meta: PAD token        = 0 '<unk>'\n",
      "llm_load_print_meta: LF token         = 13 '<0x0A>'\n",
      "llm_load_tensors: ggml ctx size =    0.56 MiB\n",
      "llm_load_tensors: offloading 32 repeating layers to GPU\n",
      "llm_load_tensors: offloading non-repeating layers to GPU\n",
      "llm_load_tensors: offloaded 33/33 layers to GPU\n",
      "llm_load_tensors:        CPU buffer size =    53.71 MiB\n",
      "llm_load_tensors:      CUDA0 buffer size =   804.66 MiB\n",
      "llm_load_tensors:      CUDA1 buffer size =   715.25 MiB\n",
      "llm_load_tensors:      CUDA2 buffer size =   715.25 MiB\n",
      "llm_load_tensors:      CUDA3 buffer size =   728.40 MiB\n",
      ".................................................................................................\n",
      "llama_new_context_with_model: n_ctx      = 10000\n",
      "llama_new_context_with_model: freq_base  = 10000.0\n",
      "llama_new_context_with_model: freq_scale = 1\n",
      "llama_kv_cache_init:      CUDA0 KV buffer size =   351.56 MiB\n",
      "llama_kv_cache_init:      CUDA1 KV buffer size =   312.50 MiB\n",
      "llama_kv_cache_init:      CUDA2 KV buffer size =   312.50 MiB\n",
      "llama_kv_cache_init:      CUDA3 KV buffer size =   273.44 MiB\n",
      "llama_new_context_with_model: KV self size  = 1250.00 MiB, K (f16):  625.00 MiB, V (f16):  625.00 MiB\n"
     ]
    },
    {
     "ename": "",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n",
      "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n",
      "\u001b[1;31mClick <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. \n",
      "\u001b[1;31mView Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details."
     ]
    }
   ],
   "source": [
    "from haystack import Pipeline\n",
    "from haystack.utils import Secret\n",
    "from haystack_integrations.components.retrievers.chroma import ChromaQueryTextRetriever\n",
    "from haystack_integrations.components.generators.llama_cpp import LlamaCppGenerator\n",
    "from haystack.components.readers import ExtractiveReader\n",
    "from haystack.components.generators import GPTGenerator\n",
    "from haystack.components.builders.prompt_builder import PromptBuilder\n",
    "from haystack.components.builders.answer_builder import AnswerBuilder\n",
    "from haystack.components.generators import OpenAIGenerator\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "template = \"\"\"\n",
    "Answer all the questions in the following format and based on Aditya \n",
    "and if not found generate answer accordingly using the given information.\n",
    "\n",
    "Context:\n",
    "{% for doc in documents %}\n",
    "{{ doc.content }}\n",
    "{% endfor %}\n",
    "Question: {{question}}\n",
    "Answer:\n",
    "\"\"\"\n",
    "\n",
    "prompt_builder = PromptBuilder(template=template)\n",
    "retriever = ChromaQueryTextRetriever(document_store = chroma_store)\n",
    "#ExtractiveReader to extract answers from the relevant context\n",
    "\n",
    "llm = LlamaCppGenerator(\n",
    "model_path=\"openchat-3.5-1210.Q3_K_S.ggml\", \n",
    "n_ctx=10000,\n",
    "n_batch=256,\n",
    "model_kwargs={\"n_gpu_layers\": -1},\n",
    "generation_kwargs={\"max_tokens\": 250, \"temperature\": 0.9},\n",
    ")\n",
    "\n",
    "reader = ExtractiveReader(model=\"deepset/roberta-base-squad2-distilled\",)\n",
    "\n",
    "extractive_qa_pipeline = Pipeline()\n",
    "extractive_qa_pipeline.add_component(\"retriever\", ChromaQueryTextRetriever(chroma_store))\n",
    "# extractive_qa_pipeline.add_component(\"reader\",reader)\n",
    "extractive_qa_pipeline.add_component(instance=prompt_builder,   name=\"prompt_builder\")\n",
    "extractive_qa_pipeline.add_component(\"llm\", llm)\n",
    "extractive_qa_pipeline.add_component(instance=AnswerBuilder(), name=\"answer_builder\")\n",
    "\n",
    "# extractive_qa_pipeline.connect(\"retriever.documents\", \"reader\")\n",
    "extractive_qa_pipeline.connect(\"retriever\", \"prompt_builder.documents\")     \n",
    "extractive_qa_pipeline.connect(\"prompt_builder\", \"llm\")\n",
    "extractive_qa_pipeline.connect(\"llm.replies\", \"answer_builder.replies\")\n",
    "extractive_qa_pipeline.connect(\"retriever\", \"answer_builder.documents\")\n",
    "\n",
    "query = \"who is Aditya  did Aditya Pursued his Masters from?\"\n",
    "\n",
    "# Define the input data for the pipeline components\n",
    "input_data = {\n",
    "    \"retriever\": {\"query\": query, \"top_k\": 3},\n",
    "    # \"reader\": {\"query\": query},\n",
    "    \"prompt_builder\": {\"question\": query},\n",
    "    \"answer_builder\": {\"query\": query},\n",
    "    # Use 'max_tokens' instead of 'max_new_tokens'\n",
    "}\n",
    "\n",
    "# Run the pipeline with the updated input data\n",
    "results = extractive_qa_pipeline.run(input_data)\n",
    "\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Aditya pursued his Masters from Florida State University.\n"
     ]
    }
   ],
   "source": [
    "# Assuming results is the dictionary containing the output\n",
    "generated_content = results['llm']['meta'][0]['choices'][0]['text']\n",
    "#print(results)\n",
    "# Print the generated content\n",
    "print(generated_content)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "RAGAPP",
   "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.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}