Shipmaster1 commited on
Commit
1227663
Β·
verified Β·
1 Parent(s): a09c2bf

Upload 4 files

Browse files
Files changed (4) hide show
  1. Pythonic_RAG_Assignment.ipynb +1381 -0
  2. README.md +76 -13
  3. app.py +36 -0
  4. requirements.txt +11 -0
Pythonic_RAG_Assignment.ipynb ADDED
@@ -0,0 +1,1381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "lElF3o5PR6ys"
7
+ },
8
+ "source": [
9
+ "# Your First RAG Application\n",
10
+ "\n",
11
+ "In this notebook, we'll walk you through each of the components that are involved in a simple RAG application.\n",
12
+ "\n",
13
+ "We won't be leveraging any fancy tools, just the OpenAI Python SDK, Numpy, and some classic Python.\n",
14
+ "\n",
15
+ "> NOTE: This was done with Python 3.11.4.\n",
16
+ "\n",
17
+ "> NOTE: There might be [compatibility issues](https://github.com/wandb/wandb/issues/7683) if you're on NVIDIA driver >552.44 As an interim solution - you can rollback your drivers to the 552.44."
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "5CtcL8P8R6yt"
24
+ },
25
+ "source": [
26
+ "## Table of Contents:\n",
27
+ "\n",
28
+ "- Task 1: Imports and Utilities\n",
29
+ "- Task 2: Documents\n",
30
+ "- Task 3: Embeddings and Vectors\n",
31
+ "- Task 4: Prompts\n",
32
+ "- Task 5: Retrieval Augmented Generation\n",
33
+ " - 🚧 Activity #1: Augment RAG"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "markdown",
38
+ "metadata": {
39
+ "id": "1Dz6GYilR6yt"
40
+ },
41
+ "source": [
42
+ "Let's look at a rather complicated looking visual representation of a basic RAG application.\n",
43
+ "\n",
44
+ "<img src=\"https://i.imgur.com/vD8b016.png\" />"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "markdown",
49
+ "metadata": {
50
+ "id": "PjmC0KFtR6yt"
51
+ },
52
+ "source": [
53
+ "## Task 1: Imports and Utility\n",
54
+ "\n",
55
+ "We're just doing some imports and enabling `async` to work within the Jupyter environment here, nothing too crazy!"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "execution_count": 1,
61
+ "metadata": {
62
+ "id": "Z1dyrG4hR6yt"
63
+ },
64
+ "outputs": [],
65
+ "source": [
66
+ "from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter\n",
67
+ "from aimakerspace.vectordatabase import VectorDatabase\n",
68
+ "import asyncio"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": 2,
74
+ "metadata": {
75
+ "id": "9OrFZRnER6yt"
76
+ },
77
+ "outputs": [],
78
+ "source": [
79
+ "import nest_asyncio\n",
80
+ "nest_asyncio.apply()"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "markdown",
85
+ "metadata": {
86
+ "id": "M0jGnpQsR6yu"
87
+ },
88
+ "source": [
89
+ "## Task 2: Documents\n",
90
+ "\n",
91
+ "We'll be concerning ourselves with this part of the flow in the following section:\n",
92
+ "\n",
93
+ "<img src=\"https://i.imgur.com/jTm9gjk.png\" />"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "markdown",
98
+ "metadata": {
99
+ "id": "-SFPWvRUR6yu"
100
+ },
101
+ "source": [
102
+ "### Loading Source Documents\n",
103
+ "\n",
104
+ "So, first things first, we need some documents to work with.\n",
105
+ "\n",
106
+ "While we could work directly with the `.txt` files (or whatever file-types you wanted to extend this to) we can instead do some batch processing of those documents at the beginning in order to store them in a more machine compatible format.\n",
107
+ "\n",
108
+ "In this case, we're going to parse our text file into a single document in memory.\n",
109
+ "\n",
110
+ "Let's look at the relevant bits of the `TextFileLoader` class:\n",
111
+ "\n",
112
+ "```python\n",
113
+ "def load_file(self):\n",
114
+ " with open(self.path, \"r\", encoding=self.encoding) as f:\n",
115
+ " self.documents.append(f.read())\n",
116
+ "```\n",
117
+ "\n",
118
+ "We're simply loading the document using the built in `open` method, and storing that output in our `self.documents` list.\n",
119
+ "\n",
120
+ "> NOTE: We're using blogs from PMarca (Marc Andreessen) as our sample data. This data is largely irrelevant as we want to focus on the mechanisms of RAG, which includes out data's shape and quality - but not specifically what the contents of the data are. \n"
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "execution_count": 3,
126
+ "metadata": {
127
+ "colab": {
128
+ "base_uri": "https://localhost:8080/"
129
+ },
130
+ "id": "Ia2sUEuGR6yu",
131
+ "outputId": "84937ecc-c35f-4c4a-a4ab-9da72625954c"
132
+ },
133
+ "outputs": [
134
+ {
135
+ "data": {
136
+ "text/plain": [
137
+ "1"
138
+ ]
139
+ },
140
+ "execution_count": 3,
141
+ "metadata": {},
142
+ "output_type": "execute_result"
143
+ }
144
+ ],
145
+ "source": [
146
+ "text_loader = TextFileLoader(\"data/PMarcaBlogs.txt\")\n",
147
+ "documents = text_loader.load_documents()\n",
148
+ "len(documents)"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "execution_count": 4,
154
+ "metadata": {
155
+ "colab": {
156
+ "base_uri": "https://localhost:8080/"
157
+ },
158
+ "id": "bV-tj5WFR6yu",
159
+ "outputId": "674eb315-1ff3-4597-bcf5-38ece0a812ac"
160
+ },
161
+ "outputs": [
162
+ {
163
+ "name": "stdout",
164
+ "output_type": "stream",
165
+ "text": [
166
+ "\n",
167
+ "The Pmarca Blog Archives\n",
168
+ "(select posts from 2007-2009)\n",
169
+ "Marc Andreessen\n",
170
+ "copyright: Andreessen Horow\n"
171
+ ]
172
+ }
173
+ ],
174
+ "source": [
175
+ "print(documents[0][:100])"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "markdown",
180
+ "metadata": {
181
+ "id": "nHlTvCzYR6yu"
182
+ },
183
+ "source": [
184
+ "### Splitting Text Into Chunks\n",
185
+ "\n",
186
+ "As we can see, there is one massive document.\n",
187
+ "\n",
188
+ "We'll want to chunk the document into smaller parts so it's easier to pass the most relevant snippets to the LLM.\n",
189
+ "\n",
190
+ "There is no fixed way to split/chunk documents - and you'll need to rely on some intuition as well as knowing your data *very* well in order to build the most robust system.\n",
191
+ "\n",
192
+ "For this toy example, we'll just split blindly on length.\n",
193
+ "\n",
194
+ ">There's an opportunity to clear up some terminology here, for this course we will be stick to the following:\n",
195
+ ">\n",
196
+ ">- \"source documents\" : The `.txt`, `.pdf`, `.html`, ..., files that make up the files and information we start with in its raw format\n",
197
+ ">- \"document(s)\" : single (or more) text object(s)\n",
198
+ ">- \"corpus\" : the combination of all of our documents"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "markdown",
203
+ "metadata": {
204
+ "id": "2G6Voc0jR6yv"
205
+ },
206
+ "source": [
207
+ "As you can imagine (though it's not specifically true in this toy example) the idea of splitting documents is to break them into managable sized chunks that retain the most relevant local context."
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "execution_count": 5,
213
+ "metadata": {
214
+ "colab": {
215
+ "base_uri": "https://localhost:8080/"
216
+ },
217
+ "id": "UMC4tsEmR6yv",
218
+ "outputId": "08689c0b-57cd-4040-942a-8193e997f5cb"
219
+ },
220
+ "outputs": [
221
+ {
222
+ "data": {
223
+ "text/plain": [
224
+ "373"
225
+ ]
226
+ },
227
+ "execution_count": 5,
228
+ "metadata": {},
229
+ "output_type": "execute_result"
230
+ }
231
+ ],
232
+ "source": [
233
+ "text_splitter = CharacterTextSplitter()\n",
234
+ "split_documents = text_splitter.split_texts(documents)\n",
235
+ "len(split_documents)"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "markdown",
240
+ "metadata": {
241
+ "id": "W2wKT0WLR6yv"
242
+ },
243
+ "source": [
244
+ "Let's take a look at some of the documents we've managed to split."
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "execution_count": 6,
250
+ "metadata": {
251
+ "colab": {
252
+ "base_uri": "https://localhost:8080/"
253
+ },
254
+ "id": "vcYMwWJoR6yv",
255
+ "outputId": "20d69876-feca-4826-b4be-32915276987a"
256
+ },
257
+ "outputs": [
258
+ {
259
+ "data": {
260
+ "text/plain": [
261
+ "['\\ufeff\\nThe Pmarca Blog Archives\\n(select posts from 2007-2009)\\nMarc Andreessen\\ncopyright: Andreessen Horowitz\\ncover design: Jessica Hagy\\nproduced using: Pressbooks\\nContents\\nTHE PMARCA GUIDE TO STARTUPS\\nPart 1: Why not to do a startup 2\\nPart 2: When the VCs say \"no\" 10\\nPart 3: \"But I don\\'t know any VCs!\" 18\\nPart 4: The only thing that matters 25\\nPart 5: The Moby Dick theory of big companies 33\\nPart 6: How much funding is too little? Too much? 41\\nPart 7: Why a startup\\'s initial business plan doesn\\'t\\nmatter that much\\n49\\nTHE PMARCA GUIDE TO HIRING\\nPart 8: Hiring, managing, promoting, and Dring\\nexecutives\\n54\\nPart 9: How to hire a professional CEO 68\\nHow to hire the best people you\\'ve ever worked\\nwith\\n69\\nTHE PMARCA GUIDE TO BIG COMPANIES\\nPart 1: Turnaround! 82\\nPart 2: Retaining great people 86\\nTHE PMARCA GUIDE TO CAREER, PRODUCTIVITY,\\nAND SOME OTHER THINGS\\nIntroduction 97\\nPart 1: Opportunity 99\\nPart 2: Skills and education 107\\nPart 3: Where to go and why 120\\nThe Pmarca Guide to Personal Productivi']"
262
+ ]
263
+ },
264
+ "execution_count": 6,
265
+ "metadata": {},
266
+ "output_type": "execute_result"
267
+ }
268
+ ],
269
+ "source": [
270
+ "split_documents[0:1]"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "markdown",
275
+ "metadata": {
276
+ "id": "HOU-RFP_R6yv"
277
+ },
278
+ "source": [
279
+ "## Task 3: Embeddings and Vectors\n",
280
+ "\n",
281
+ "Next, we have to convert our corpus into a \"machine readable\" format as we explored in the Embedding Primer notebook.\n",
282
+ "\n",
283
+ "Today, we're going to talk about the actual process of creating, and then storing, these embeddings, and how we can leverage that to intelligently add context to our queries."
284
+ ]
285
+ },
286
+ {
287
+ "cell_type": "markdown",
288
+ "metadata": {},
289
+ "source": [
290
+ "### OpenAI API Key\n",
291
+ "\n",
292
+ "In order to access OpenAI's APIs, we'll need to provide our OpenAI API Key!\n",
293
+ "\n",
294
+ "You can work through the folder \"OpenAI API Key Setup\" for more information on this process if you don't already have an API Key!"
295
+ ]
296
+ },
297
+ {
298
+ "cell_type": "code",
299
+ "execution_count": 7,
300
+ "metadata": {},
301
+ "outputs": [],
302
+ "source": [
303
+ "import os\n",
304
+ "import openai\n",
305
+ "from getpass import getpass\n",
306
+ "\n",
307
+ "openai.api_key = getpass(\"OpenAI API Key: \")\n",
308
+ "os.environ[\"OPENAI_API_KEY\"] = openai.api_key"
309
+ ]
310
+ },
311
+ {
312
+ "cell_type": "markdown",
313
+ "metadata": {},
314
+ "source": [
315
+ "### Vector Database\n",
316
+ "\n",
317
+ "Let's set up our vector database to hold all our documents and their embeddings!"
318
+ ]
319
+ },
320
+ {
321
+ "cell_type": "markdown",
322
+ "metadata": {
323
+ "id": "kDQrfAR1R6yv"
324
+ },
325
+ "source": [
326
+ "While this is all baked into 1 call - we can look at some of the code that powers this process to get a better understanding:\n",
327
+ "\n",
328
+ "Let's look at our `VectorDatabase().__init__()`:\n",
329
+ "\n",
330
+ "```python\n",
331
+ "def __init__(self, embedding_model: EmbeddingModel = None):\n",
332
+ " self.vectors = defaultdict(np.array)\n",
333
+ " self.embedding_model = embedding_model or EmbeddingModel()\n",
334
+ "```\n",
335
+ "\n",
336
+ "As you can see - our vectors are merely stored as a dictionary of `np.array` objects.\n",
337
+ "\n",
338
+ "Secondly, our `VectorDatabase()` has a default `EmbeddingModel()` which is a wrapper for OpenAI's `text-embedding-3-small` model.\n",
339
+ "\n",
340
+ "> **Quick Info About `text-embedding-3-small`**:\n",
341
+ "> - It has a context window of **8191** tokens\n",
342
+ "> - It returns vectors with dimension **1536**"
343
+ ]
344
+ },
345
+ {
346
+ "cell_type": "markdown",
347
+ "metadata": {
348
+ "id": "L273pRdeR6yv"
349
+ },
350
+ "source": [
351
+ "#### ❓Question #1:\n",
352
+ "\n",
353
+ "The default embedding dimension of `text-embedding-3-small` is 1536, as noted above. \n",
354
+ "\n",
355
+ "1. Is there any way to modify this dimension?\n",
356
+ "Yes you can reduce dimension but not increase it. Helps with speeding up searches and reducing cost. We can reduce it up to 256\n",
357
+ "2. What technique does OpenAI use to achieve this?\n",
358
+ "OpenAI uses Principal Component Analysis(PCA) the model first generates a 1536 then uses PCA to reduce the dimension\n",
359
+ "Reducing retains all the important information and benefits relationships between texts reduces resources needed and has good performance even at lower dimensions\n",
360
+ "\n",
361
+ "\n",
362
+ "> NOTE: Check out this [API documentation](https://platform.openai.com/docs/api-reference/embeddings/create) for the answer to question #1, and [this documentation](https://platform.openai.com/docs/guides/embeddings/use-cases) for an answer to question #2!"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "markdown",
367
+ "metadata": {
368
+ "id": "w5FZY7K3R6yv"
369
+ },
370
+ "source": [
371
+ "We can call the `async_get_embeddings` method of our `EmbeddingModel()` on a list of `str` and receive a list of `float` back!\n",
372
+ "\n",
373
+ "```python\n",
374
+ "async def async_get_embeddings(self, list_of_text: List[str]) -> List[List[float]]:\n",
375
+ " return await aget_embeddings(\n",
376
+ " list_of_text=list_of_text, engine=self.embeddings_model_name\n",
377
+ " )\n",
378
+ "```"
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "markdown",
383
+ "metadata": {
384
+ "id": "cSct6X0aR6yv"
385
+ },
386
+ "source": [
387
+ "We cast those to `np.array` when we build our `VectorDatabase()`:\n",
388
+ "\n",
389
+ "```python\n",
390
+ "async def abuild_from_list(self, list_of_text: List[str]) -> \"VectorDatabase\":\n",
391
+ " embeddings = await self.embedding_model.async_get_embeddings(list_of_text)\n",
392
+ " for text, embedding in zip(list_of_text, embeddings):\n",
393
+ " self.insert(text, np.array(embedding))\n",
394
+ " return self\n",
395
+ "```\n",
396
+ "\n",
397
+ "And that's all we need to do!"
398
+ ]
399
+ },
400
+ {
401
+ "cell_type": "code",
402
+ "execution_count": 8,
403
+ "metadata": {
404
+ "id": "O4KoLbVDR6yv"
405
+ },
406
+ "outputs": [],
407
+ "source": [
408
+ "vector_db = VectorDatabase()\n",
409
+ "vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))"
410
+ ]
411
+ },
412
+ {
413
+ "cell_type": "markdown",
414
+ "metadata": {
415
+ "id": "SSZwaGvpR6yv"
416
+ },
417
+ "source": [
418
+ "#### ❓Question #2:\n",
419
+ "\n",
420
+ "What are the benefits of using an `async` approach to collecting our embeddings?\n",
421
+ "\n",
422
+ "Improves scalability, uses resources more efficiently and has faster processing when having many concurrent requests\n",
423
+ "In our case the multiple 100s of api calls and that way our chunks can be processed faster instead of waiting for each chunk to process and sending the next. The scalability of async is better for our examples.\n",
424
+ "\n",
425
+ "\n",
426
+ "> NOTE: Determining the core difference between `async` and `sync` will be useful! If you get stuck - ask ChatGPT!"
427
+ ]
428
+ },
429
+ {
430
+ "cell_type": "markdown",
431
+ "metadata": {
432
+ "id": "nRBdIt-xR6yw"
433
+ },
434
+ "source": [
435
+ "So, to review what we've done so far in natural language:\n",
436
+ "\n",
437
+ "1. We load source documents\n",
438
+ "2. We split those source documents into smaller chunks (documents)\n",
439
+ "3. We send each of those documents to the `text-embedding-3-small` OpenAI API endpoint\n",
440
+ "4. We store each of the text representations with the vector representations as keys/values in a dictionary"
441
+ ]
442
+ },
443
+ {
444
+ "cell_type": "markdown",
445
+ "metadata": {
446
+ "id": "4-vWANZyR6yw"
447
+ },
448
+ "source": [
449
+ "### Semantic Similarity\n",
450
+ "\n",
451
+ "The next step is to be able to query our `VectorDatabase()` with a `str` and have it return to us vectors and text that is most relevant from our corpus.\n",
452
+ "\n",
453
+ "We're going to use the following process to achieve this in our toy example:\n",
454
+ "\n",
455
+ "1. We need to embed our query with the same `EmbeddingModel()` as we used to construct our `VectorDatabase()`\n",
456
+ "2. We loop through every vector in our `VectorDatabase()` and use a distance measure to compare how related they are\n",
457
+ "3. We return a list of the top `k` closest vectors, with their text representations\n",
458
+ "\n",
459
+ "There's some very heavy optimization that can be done at each of these steps - but let's just focus on the basic pattern in this notebook.\n",
460
+ "\n",
461
+ "> We are using [cosine similarity](https://www.engati.com/glossary/cosine-similarity) as a distance metric in this example - but there are many many distance metrics you could use - like [these](https://flavien-vidal.medium.com/similarity-distances-for-natural-language-processing-16f63cd5ba55)\n",
462
+ "\n",
463
+ "> We are using a rather inefficient way of calculating relative distance between the query vector and all other vectors - there are more advanced approaches that are much more efficient, like [ANN](https://towardsdatascience.com/comprehensive-guide-to-approximate-nearest-neighbors-algorithms-8b94f057d6b6)"
464
+ ]
465
+ },
466
+ {
467
+ "cell_type": "code",
468
+ "execution_count": 9,
469
+ "metadata": {
470
+ "colab": {
471
+ "base_uri": "https://localhost:8080/"
472
+ },
473
+ "id": "76d96uavR6yw",
474
+ "outputId": "bbfccc31-20a2-41c7-c14d-46554a43ed2d"
475
+ },
476
+ "outputs": [
477
+ {
478
+ "data": {
479
+ "text/plain": [
480
+ "[('ordingly.\\nSeventh, when hiring the executive to run your former specialty, be\\ncareful you don’t hire someone weak on purpose.\\nThis sounds silly, but you wouldn’t believe how oaen it happens.\\nThe CEO who used to be a product manager who has a weak\\nproduct management executive. The CEO who used to be in\\nsales who has a weak sales executive. The CEO who used to be\\nin marketing who has a weak marketing executive.\\nI call this the β€œMichael Eisner Memorial Weak Executive Problem” β€” aaer the CEO of Disney who had previously been a brilliant TV network executive. When he bought ABC at Disney, it\\npromptly fell to fourth place. His response? β€œIf I had an extra\\ntwo days a week, I could turn around ABC myself.” Well, guess\\nwhat, he didn’t have an extra two days a week.\\nA CEO β€” or a startup founder β€” oaen has a hard time letting\\ngo of the function that brought him to the party. The result: you\\nhire someone weak into the executive role for that function so\\nthat you can continue to be β€œthe man” β€” cons',\n",
481
+ " np.float64(0.6539043027545371)),\n",
482
+ " ('m. They have areas where they are truly deXcient in judgment or skill set. That’s just life. Almost nobody is brilliant\\nat everything. When hiring and when Hring executives, you\\nmust therefore focus on strength rather than lack of weakness. Everybody has severe weaknesses even if you can’t see\\nthem yet. When managing, it’s oaen useful to micromanage and\\nto provide remedial training around these weaknesses. Doing so\\nmay make the diWerence between an executive succeeding or\\nfailing.\\nFor example, you might have a brilliant engineering executive\\nwho generates excellent team loyalty, has terriXc product judgment and makes the trains run on time. This same executive\\nmay be very poor at relating to the other functions in the company. She may generate far more than her share of cross-functional conYicts, cut herself oW from critical information, and\\nsigniXcantly impede your ability to sell and market eWectively.\\nYour alternatives are:\\n(a) Macro-manage and give her an annual or quarterly object',\n",
483
+ " np.float64(0.5036247837648782)),\n",
484
+ " ('ed?\\nIn reality β€” as opposed to Marc’s warped view of reality β€” it will\\nbe extremely helpful for Marc [if he were actually the CEO,\\nwhich he is not] to meet with the new head of engineering daily\\nwhen she comes on board and review all of her thinking and\\ndecisions. This level of micromanagement will accelerate her\\ntraining and improve her long-term eWectiveness. It will make\\nher seem smarter to the rest of the organization which will build\\ncredibility and conXdence while she comes up to speed. Micromanaging new executives is generally a good idea for a limited\\nperiod of time.\\nHowever, that is not the only time that it makes sense to micro66 The Pmarca Blog Archives\\nmanage executives. It turns out that just about every executive\\nin the world has a few things that are seriously wrong with\\nthem. They have areas where they are truly deXcient in judgment or skill set. That’s just life. Almost nobody is brilliant\\nat everything. When hiring and when Hring executives, you\\nmust therefore focus o',\n",
485
+ " np.float64(0.4814861061791066))]"
486
+ ]
487
+ },
488
+ "execution_count": 9,
489
+ "metadata": {},
490
+ "output_type": "execute_result"
491
+ }
492
+ ],
493
+ "source": [
494
+ "vector_db.search_by_text(\"What is the Michael Eisner Memorial Weak Executive Problem?\", k=3)"
495
+ ]
496
+ },
497
+ {
498
+ "cell_type": "markdown",
499
+ "metadata": {
500
+ "id": "TehsfIiKR6yw"
501
+ },
502
+ "source": [
503
+ "## Task 4: Prompts\n",
504
+ "\n",
505
+ "In the following section, we'll be looking at the role of prompts - and how they help us to guide our application in the right direction.\n",
506
+ "\n",
507
+ "In this notebook, we're going to rely on the idea of \"zero-shot in-context learning\".\n",
508
+ "\n",
509
+ "This is a lot of words to say: \"We will ask it to perform our desired task in the prompt, and provide no examples.\""
510
+ ]
511
+ },
512
+ {
513
+ "cell_type": "markdown",
514
+ "metadata": {
515
+ "id": "yXpA0UveR6yw"
516
+ },
517
+ "source": [
518
+ "### XYZRolePrompt\n",
519
+ "\n",
520
+ "Before we do that, let's stop and think a bit about how OpenAI's chat models work.\n",
521
+ "\n",
522
+ "We know they have roles - as is indicated in the following API [documentation](https://platform.openai.com/docs/api-reference/chat/create#chat/create-messages)\n",
523
+ "\n",
524
+ "There are three roles, and they function as follows (taken directly from [OpenAI](https://platform.openai.com/docs/guides/gpt/chat-completions-api)):\n",
525
+ "\n",
526
+ "- `{\"role\" : \"system\"}` : The system message helps set the behavior of the assistant. For example, you can modify the personality of the assistant or provide specific instructions about how it should behave throughout the conversation. However note that the system message is optional and the model’s behavior without a system message is likely to be similar to using a generic message such as \"You are a helpful assistant.\"\n",
527
+ "- `{\"role\" : \"user\"}` : The user messages provide requests or comments for the assistant to respond to.\n",
528
+ "- `{\"role\" : \"assistant\"}` : Assistant messages store previous assistant responses, but can also be written by you to give examples of desired behavior.\n",
529
+ "\n",
530
+ "The main idea is this:\n",
531
+ "\n",
532
+ "1. You start with a system message that outlines how the LLM should respond, what kind of behaviours you can expect from it, and more\n",
533
+ "2. Then, you can provide a few examples in the form of \"assistant\"/\"user\" pairs\n",
534
+ "3. Then, you prompt the model with the true \"user\" message.\n",
535
+ "\n",
536
+ "In this example, we'll be forgoing the 2nd step for simplicities sake."
537
+ ]
538
+ },
539
+ {
540
+ "cell_type": "markdown",
541
+ "metadata": {
542
+ "id": "gdZ2KWKSR6yw"
543
+ },
544
+ "source": [
545
+ "#### Utility Functions\n",
546
+ "\n",
547
+ "You'll notice that we're using some utility functions from the `aimakerspace` module - let's take a peek at these and see what they're doing!"
548
+ ]
549
+ },
550
+ {
551
+ "cell_type": "markdown",
552
+ "metadata": {
553
+ "id": "GFbeJDDsR6yw"
554
+ },
555
+ "source": [
556
+ "##### XYZRolePrompt"
557
+ ]
558
+ },
559
+ {
560
+ "cell_type": "markdown",
561
+ "metadata": {
562
+ "id": "5mojJSE3R6yw"
563
+ },
564
+ "source": [
565
+ "Here we have our `system`, `user`, and `assistant` role prompts.\n",
566
+ "\n",
567
+ "Let's take a peek at what they look like:\n",
568
+ "\n",
569
+ "```python\n",
570
+ "class BasePrompt:\n",
571
+ " def __init__(self, prompt):\n",
572
+ " \"\"\"\n",
573
+ " Initializes the BasePrompt object with a prompt template.\n",
574
+ "\n",
575
+ " :param prompt: A string that can contain placeholders within curly braces\n",
576
+ " \"\"\"\n",
577
+ " self.prompt = prompt\n",
578
+ " self._pattern = re.compile(r\"\\{([^}]+)\\}\")\n",
579
+ "\n",
580
+ " def format_prompt(self, **kwargs):\n",
581
+ " \"\"\"\n",
582
+ " Formats the prompt string using the keyword arguments provided.\n",
583
+ "\n",
584
+ " :param kwargs: The values to substitute into the prompt string\n",
585
+ " :return: The formatted prompt string\n",
586
+ " \"\"\"\n",
587
+ " matches = self._pattern.findall(self.prompt)\n",
588
+ " return self.prompt.format(**{match: kwargs.get(match, \"\") for match in matches})\n",
589
+ "\n",
590
+ " def get_input_variables(self):\n",
591
+ " \"\"\"\n",
592
+ " Gets the list of input variable names from the prompt string.\n",
593
+ "\n",
594
+ " :return: List of input variable names\n",
595
+ " \"\"\"\n",
596
+ " return self._pattern.findall(self.prompt)\n",
597
+ "```\n",
598
+ "\n",
599
+ "Then we have our `RolePrompt` which laser focuses us on the role pattern found in most API endpoints for LLMs.\n",
600
+ "\n",
601
+ "```python\n",
602
+ "class RolePrompt(BasePrompt):\n",
603
+ " def __init__(self, prompt, role: str):\n",
604
+ " \"\"\"\n",
605
+ " Initializes the RolePrompt object with a prompt template and a role.\n",
606
+ "\n",
607
+ " :param prompt: A string that can contain placeholders within curly braces\n",
608
+ " :param role: The role for the message ('system', 'user', or 'assistant')\n",
609
+ " \"\"\"\n",
610
+ " super().__init__(prompt)\n",
611
+ " self.role = role\n",
612
+ "\n",
613
+ " def create_message(self, **kwargs):\n",
614
+ " \"\"\"\n",
615
+ " Creates a message dictionary with a role and a formatted message.\n",
616
+ "\n",
617
+ " :param kwargs: The values to substitute into the prompt string\n",
618
+ " :return: Dictionary containing the role and the formatted message\n",
619
+ " \"\"\"\n",
620
+ " return {\"role\": self.role, \"content\": self.format_prompt(**kwargs)}\n",
621
+ "```\n",
622
+ "\n",
623
+ "We'll look at how the `SystemRolePrompt` is constructed to get a better idea of how that extension works:\n",
624
+ "\n",
625
+ "```python\n",
626
+ "class SystemRolePrompt(RolePrompt):\n",
627
+ " def __init__(self, prompt: str):\n",
628
+ " super().__init__(prompt, \"system\")\n",
629
+ "```\n",
630
+ "\n",
631
+ "That pattern is repeated for our `UserRolePrompt` and our `AssistantRolePrompt` as well."
632
+ ]
633
+ },
634
+ {
635
+ "cell_type": "markdown",
636
+ "metadata": {
637
+ "id": "D361R6sMR6yw"
638
+ },
639
+ "source": [
640
+ "##### ChatOpenAI"
641
+ ]
642
+ },
643
+ {
644
+ "cell_type": "markdown",
645
+ "metadata": {
646
+ "id": "HJVQ2Pm8R6yw"
647
+ },
648
+ "source": [
649
+ "Next we have our model, which is converted to a format analagous to libraries like LangChain and LlamaIndex.\n",
650
+ "\n",
651
+ "Let's take a peek at how that is constructed:\n",
652
+ "\n",
653
+ "```python\n",
654
+ "class ChatOpenAI:\n",
655
+ " def __init__(self, model_name: str = \"gpt-4o-mini\"):\n",
656
+ " self.model_name = model_name\n",
657
+ " self.openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n",
658
+ " if self.openai_api_key is None:\n",
659
+ " raise ValueError(\"OPENAI_API_KEY is not set\")\n",
660
+ "\n",
661
+ " def run(self, messages, text_only: bool = True):\n",
662
+ " if not isinstance(messages, list):\n",
663
+ " raise ValueError(\"messages must be a list\")\n",
664
+ "\n",
665
+ " openai.api_key = self.openai_api_key\n",
666
+ " response = openai.ChatCompletion.create(\n",
667
+ " model=self.model_name, messages=messages\n",
668
+ " )\n",
669
+ "\n",
670
+ " if text_only:\n",
671
+ " return response.choices[0].message.content\n",
672
+ "\n",
673
+ " return response\n",
674
+ "```"
675
+ ]
676
+ },
677
+ {
678
+ "cell_type": "markdown",
679
+ "metadata": {
680
+ "id": "qCU7FfhIR6yw"
681
+ },
682
+ "source": [
683
+ "#### ❓ Question #3:\n",
684
+ "\n",
685
+ "When calling the OpenAI API - are there any ways we can achieve more reproducible outputs?\n",
686
+ "\n",
687
+ "We can have the temperature setting be fixed and it controls the randomness of the model\n",
688
+ "Example: temperature of 1 returns more creative responses vs temperature 0 the responses are more focused\n",
689
+ "combining this with top_p of 1 and the low temperature we can achieve more reproducible outputs \n",
690
+ "\n",
691
+ "> NOTE: Check out [this section](https://platform.openai.com/docs/guides/text-generation/) of the OpenAI documentation for the answer!"
692
+ ]
693
+ },
694
+ {
695
+ "cell_type": "markdown",
696
+ "metadata": {
697
+ "id": "c5wcjMLCR6yw"
698
+ },
699
+ "source": [
700
+ "### Creating and Prompting OpenAI's `gpt-4o-mini`!\n",
701
+ "\n",
702
+ "Let's tie all these together and use it to prompt `gpt-4o-mini`!"
703
+ ]
704
+ },
705
+ {
706
+ "cell_type": "code",
707
+ "execution_count": 10,
708
+ "metadata": {
709
+ "id": "WIfpIot7R6yw"
710
+ },
711
+ "outputs": [],
712
+ "source": [
713
+ "from aimakerspace.openai_utils.prompts import (\n",
714
+ " UserRolePrompt,\n",
715
+ " SystemRolePrompt,\n",
716
+ " AssistantRolePrompt,\n",
717
+ ")\n",
718
+ "\n",
719
+ "from aimakerspace.openai_utils.chatmodel import ChatOpenAI\n",
720
+ "\n",
721
+ "chat_openai = ChatOpenAI()\n",
722
+ "user_prompt_template = \"{content}\"\n",
723
+ "user_role_prompt = UserRolePrompt(user_prompt_template)\n",
724
+ "system_prompt_template = (\n",
725
+ " \"You are an expert in {expertise}, you always answer in a kind way.\"\n",
726
+ ")\n",
727
+ "system_role_prompt = SystemRolePrompt(system_prompt_template)\n",
728
+ "\n",
729
+ "messages = [\n",
730
+ " system_role_prompt.create_message(expertise=\"Python\"),\n",
731
+ " user_role_prompt.create_message(\n",
732
+ " content=\"What is the best way to write a loop?\"\n",
733
+ " ),\n",
734
+ "]\n",
735
+ "\n",
736
+ "response = chat_openai.run(messages)"
737
+ ]
738
+ },
739
+ {
740
+ "cell_type": "code",
741
+ "execution_count": 11,
742
+ "metadata": {
743
+ "colab": {
744
+ "base_uri": "https://localhost:8080/"
745
+ },
746
+ "id": "dHo7lssNR6yw",
747
+ "outputId": "1d3823fa-bb6b-45f6-ddba-b41686388324"
748
+ },
749
+ "outputs": [
750
+ {
751
+ "name": "stdout",
752
+ "output_type": "stream",
753
+ "text": [
754
+ "The \"best\" way to write a loop in Python often depends on the specific use case and what you're trying to accomplish. However, I can share some common practices and examples for writing efficient, readable loops.\n",
755
+ "\n",
756
+ "1. **Using a `for` loop**:\n",
757
+ " This is typically used for iterating over a sequence (like a list, tuple, string, or range).\n",
758
+ "\n",
759
+ " ```python\n",
760
+ " # Example: Iterating over a list\n",
761
+ " fruits = ['apple', 'banana', 'cherry']\n",
762
+ " for fruit in fruits:\n",
763
+ " print(fruit)\n",
764
+ " ```\n",
765
+ "\n",
766
+ "2. **Using a `while` loop**:\n",
767
+ " This is useful when the number of iterations isn't known ahead of time and depends on a condition.\n",
768
+ "\n",
769
+ " ```python\n",
770
+ " # Example: Simple counter\n",
771
+ " count = 0\n",
772
+ " while count < 5:\n",
773
+ " print(count)\n",
774
+ " count += 1\n",
775
+ " ```\n",
776
+ "\n",
777
+ "3. **Using list comprehensions**:\n",
778
+ " If you're creating a new list based on an existing one, list comprehensions are a more concise and often more efficient way to write a loop.\n",
779
+ "\n",
780
+ " ```python\n",
781
+ " # Example: Creating a list of squared numbers\n",
782
+ " numbers = [1, 2, 3, 4, 5]\n",
783
+ " squares = [x**2 for x in numbers]\n",
784
+ " print(squares)\n",
785
+ " ```\n",
786
+ "\n",
787
+ "4. **Using `enumerate()`**:\n",
788
+ " If you need both the index and the value when looping through a list, `enumerate()` can be very handy.\n",
789
+ "\n",
790
+ " ```python\n",
791
+ " # Example: Iterating with index\n",
792
+ " fruits = ['apple', 'banana', 'cherry']\n",
793
+ " for index, fruit in enumerate(fruits):\n",
794
+ " print(f\"{index}: {fruit}\")\n",
795
+ " ```\n",
796
+ "\n",
797
+ "5. **Avoiding deep nesting**:\n",
798
+ " If you find yourself needing deeply nested loops, consider whether you can flatten your logic or use functions to keep your code readable.\n",
799
+ "\n",
800
+ "Here’s an example of combining some of these practices for better structure:\n",
801
+ "\n",
802
+ "```python\n",
803
+ "# Example: Using a function to process elements\n",
804
+ "def process_fruits(fruits):\n",
805
+ " for index, fruit in enumerate(fruits):\n",
806
+ " print(f\"{index}: {fruit.upper()}\")\n",
807
+ "\n",
808
+ "fruits = ['apple', 'banana', 'cherry']\n",
809
+ "process_fruits(fruits)\n",
810
+ "```\n",
811
+ "\n",
812
+ "Each of these methods has its own advantages depending on the scenario. The key is to choose the one that makes your code easy to read and maintain while being efficient. If you have a specific use case in mind, feel free to share, and I’d be happy to help you refine your loop further!\n"
813
+ ]
814
+ }
815
+ ],
816
+ "source": [
817
+ "print(response)"
818
+ ]
819
+ },
820
+ {
821
+ "cell_type": "markdown",
822
+ "metadata": {
823
+ "id": "r2nxxhB2R6yy"
824
+ },
825
+ "source": [
826
+ "## Task 5: Retrieval Augmented Generation\n",
827
+ "\n",
828
+ "Now we can create a RAG prompt - which will help our system behave in a way that makes sense!\n",
829
+ "\n",
830
+ "There is much you could do here, many tweaks and improvements to be made!"
831
+ ]
832
+ },
833
+ {
834
+ "cell_type": "code",
835
+ "execution_count": 12,
836
+ "metadata": {
837
+ "id": "D1hamzGaR6yy"
838
+ },
839
+ "outputs": [],
840
+ "source": [
841
+ "RAG_PROMPT_TEMPLATE = \"\"\" \\\n",
842
+ "Use the provided context to answer the user's query.\n",
843
+ "\n",
844
+ "You may not answer the user's query unless there is specific context in the following text.\n",
845
+ "\n",
846
+ "If you do not know the answer, or cannot answer, please respond with \"I don't know\".\n",
847
+ "\"\"\"\n",
848
+ "\n",
849
+ "rag_prompt = SystemRolePrompt(RAG_PROMPT_TEMPLATE)\n",
850
+ "\n",
851
+ "USER_PROMPT_TEMPLATE = \"\"\" \\\n",
852
+ "Context:\n",
853
+ "{context}\n",
854
+ "\n",
855
+ "User Query:\n",
856
+ "{user_query}\n",
857
+ "\"\"\"\n",
858
+ "\n",
859
+ "\n",
860
+ "user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)\n",
861
+ "\n",
862
+ "class RetrievalAugmentedQAPipeline:\n",
863
+ " def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:\n",
864
+ " self.llm = llm\n",
865
+ " self.vector_db_retriever = vector_db_retriever\n",
866
+ "\n",
867
+ " def run_pipeline(self, user_query: str) -> str:\n",
868
+ " context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
869
+ "\n",
870
+ " context_prompt = \"\"\n",
871
+ " for context in context_list:\n",
872
+ " context_prompt += context[0] + \"\\n\"\n",
873
+ "\n",
874
+ " formatted_system_prompt = rag_prompt.create_message()\n",
875
+ "\n",
876
+ " formatted_user_prompt = user_prompt.create_message(user_query=user_query, context=context_prompt)\n",
877
+ "\n",
878
+ " return {\"response\" : self.llm.run([formatted_system_prompt, formatted_user_prompt]), \"context\" : context_list}"
879
+ ]
880
+ },
881
+ {
882
+ "cell_type": "markdown",
883
+ "metadata": {
884
+ "id": "zZIJI19uR6yz"
885
+ },
886
+ "source": [
887
+ "#### ❓ Question #4:\n",
888
+ "\n",
889
+ "What prompting strategies could you use to make the LLM have a more thoughtful, detailed response?\n",
890
+ "\n",
891
+ "What is that strategy called?\n",
892
+ "\n",
893
+ "Instruction prompting, we get the results we want by directly instructing the model how we want it to respond\n",
894
+ "\n",
895
+ "\n",
896
+ "> NOTE: You can look through [\"Accessing GPT-3.5-turbo Like a Developer\"](https://colab.research.google.com/drive/1mOzbgf4a2SP5qQj33ZxTz2a01-5eXqk2?usp=sharing) for an answer to this question if you get stuck!"
897
+ ]
898
+ },
899
+ {
900
+ "cell_type": "code",
901
+ "execution_count": 13,
902
+ "metadata": {
903
+ "id": "kqbE9fZ6R6yz"
904
+ },
905
+ "outputs": [],
906
+ "source": [
907
+ "retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
908
+ " vector_db_retriever=vector_db,\n",
909
+ " llm=chat_openai\n",
910
+ ")"
911
+ ]
912
+ },
913
+ {
914
+ "cell_type": "code",
915
+ "execution_count": 14,
916
+ "metadata": {
917
+ "colab": {
918
+ "base_uri": "https://localhost:8080/"
919
+ },
920
+ "id": "jAGhaCGOR6yz",
921
+ "outputId": "e4fb3a1b-d2bc-4e18-ec31-dc0adf767163"
922
+ },
923
+ "outputs": [
924
+ {
925
+ "data": {
926
+ "text/plain": [
927
+ "{'response': 'The \\'Michael Eisner Memorial Weak Executive Problem\\' refers to the tendency of a CEO or founder, who has a strong background in a particular function (such as product management, sales, or marketing), to hire a weak executive in that same area. This often occurs because the CEO wants to retain control over that function, thus hiring someone less competent to ensure they remain \"the man.\" The term references Michael Eisner, the former CEO of Disney, who faced challenges when he bought ABC, which struggled under his leadership despite his expertise in television. The implication is that hiring weak executives can hinder the overall effectiveness of an organization.',\n",
928
+ " 'context': [('ordingly.\\nSeventh, when hiring the executive to run your former specialty, be\\ncareful you don’t hire someone weak on purpose.\\nThis sounds silly, but you wouldn’t believe how oaen it happens.\\nThe CEO who used to be a product manager who has a weak\\nproduct management executive. The CEO who used to be in\\nsales who has a weak sales executive. The CEO who used to be\\nin marketing who has a weak marketing executive.\\nI call this the β€œMichael Eisner Memorial Weak Executive Problem” β€” aaer the CEO of Disney who had previously been a brilliant TV network executive. When he bought ABC at Disney, it\\npromptly fell to fourth place. His response? β€œIf I had an extra\\ntwo days a week, I could turn around ABC myself.” Well, guess\\nwhat, he didn’t have an extra two days a week.\\nA CEO β€” or a startup founder β€” oaen has a hard time letting\\ngo of the function that brought him to the party. The result: you\\nhire someone weak into the executive role for that function so\\nthat you can continue to be β€œthe man” β€” cons',\n",
929
+ " np.float64(0.6582349170764753)),\n",
930
+ " ('m. They have areas where they are truly deXcient in judgment or skill set. That’s just life. Almost nobody is brilliant\\nat everything. When hiring and when Hring executives, you\\nmust therefore focus on strength rather than lack of weakness. Everybody has severe weaknesses even if you can’t see\\nthem yet. When managing, it’s oaen useful to micromanage and\\nto provide remedial training around these weaknesses. Doing so\\nmay make the diWerence between an executive succeeding or\\nfailing.\\nFor example, you might have a brilliant engineering executive\\nwho generates excellent team loyalty, has terriXc product judgment and makes the trains run on time. This same executive\\nmay be very poor at relating to the other functions in the company. She may generate far more than her share of cross-functional conYicts, cut herself oW from critical information, and\\nsigniXcantly impede your ability to sell and market eWectively.\\nYour alternatives are:\\n(a) Macro-manage and give her an annual or quarterly object',\n",
931
+ " np.float64(0.5088668708442031)),\n",
932
+ " ('ed?\\nIn reality β€” as opposed to Marc’s warped view of reality β€” it will\\nbe extremely helpful for Marc [if he were actually the CEO,\\nwhich he is not] to meet with the new head of engineering daily\\nwhen she comes on board and review all of her thinking and\\ndecisions. This level of micromanagement will accelerate her\\ntraining and improve her long-term eWectiveness. It will make\\nher seem smarter to the rest of the organization which will build\\ncredibility and conXdence while she comes up to speed. Micromanaging new executives is generally a good idea for a limited\\nperiod of time.\\nHowever, that is not the only time that it makes sense to micro66 The Pmarca Blog Archives\\nmanage executives. It turns out that just about every executive\\nin the world has a few things that are seriously wrong with\\nthem. They have areas where they are truly deXcient in judgment or skill set. That’s just life. Almost nobody is brilliant\\nat everything. When hiring and when Hring executives, you\\nmust therefore focus o',\n",
933
+ " np.float64(0.4790308520865477)),\n",
934
+ " ('nYicts, cut herself oW from critical information, and\\nsigniXcantly impede your ability to sell and market eWectively.\\nYour alternatives are:\\n(a) Macro-manage and give her an annual or quarterly objective\\nto Xx it, or…\\n(b) Intensively micromanage her interactions until she learns\\nthe fundamental interpersonal skills required to be an eWective\\nexecutive.\\nI am arguing that doing (a) will likely result in weak performance. The reason is that she very likely has no idea how to be\\neWective with her peers. If somebody is an executive, it’s very\\nlikely that somewhere along the line somebody gave her feedback β€” perhaps abstractly β€” about all of her weaknesses. Yet\\nthe weakness remains. As a result, executives generally require\\nmore hands-on management than lower level employees to\\nimprove weak areas.\\nSo, micromanagement is like Xne wine. A little at the right times\\nwill really enhance things; too much all the time and you’ll end\\nup in rehab.\\nPart 8: Hiring, managing, promoting, and Dring execut',\n",
935
+ " np.float64(0.46812418038478015))]}"
936
+ ]
937
+ },
938
+ "execution_count": 14,
939
+ "metadata": {},
940
+ "output_type": "execute_result"
941
+ }
942
+ ],
943
+ "source": [
944
+ "retrieval_augmented_qa_pipeline.run_pipeline(\"What is the 'Michael Eisner Memorial Weak Executive Problem'?\")"
945
+ ]
946
+ },
947
+ {
948
+ "cell_type": "markdown",
949
+ "metadata": {},
950
+ "source": [
951
+ "### πŸ—οΈ Activity #1:\n",
952
+ "\n",
953
+ "Enhance your RAG application in some way! \n",
954
+ "\n",
955
+ "Suggestions are: \n",
956
+ "\n",
957
+ "- Allow it to work with PDF files\n",
958
+ "- Implement a new distance metric\n",
959
+ "- Add metadata support to the vector database\n",
960
+ "\n",
961
+ "While these are suggestions, you should feel free to make whatever augmentations you desire! \n",
962
+ "\n",
963
+ "> NOTE: These additions might require you to work within the `aimakerspace` library - that's expected!"
964
+ ]
965
+ },
966
+ {
967
+ "cell_type": "code",
968
+ "execution_count": 41,
969
+ "metadata": {},
970
+ "outputs": [
971
+ {
972
+ "name": "stdout",
973
+ "output_type": "stream",
974
+ "text": [
975
+ "Response: He has a total of 27,649 days to expect to live.\n",
976
+ "\n",
977
+ "Context used:\n",
978
+ "\n",
979
+ "Context 1:\n",
980
+ "oved ones, learn, \n",
981
+ "build for the future, and help others. Whatever you’re doing \n",
982
+ "today, is it worth 1/30,000 of your life?How many days is a \n",
983
+ "typical human lifespan?Maybe you’re good at math; I’m sure...\n",
984
+ "\n",
985
+ "Context 2:\n",
986
+ " AI or other events, \n",
987
+ "use discussion boards, and work on finding some. If your mentors or manager don’t support \n",
988
+ "your growth, find ones who do. I’m also working on how to grow a supportive AI communit...\n",
989
+ "\n",
990
+ "Context 3:\n",
991
+ "nt to keep up.\n",
992
+ "How can you maintain a steady pace of learning for years? If you can cultivate the habit of \n",
993
+ "learning a little bit every week, you can make significant progress with what feels like les...\n",
994
+ "\n",
995
+ "Context 4:\n",
996
+ "deepen \n",
997
+ "your technical knowledge. I’ve known many machine learning engineers who benefitted from \n",
998
+ "deeper skills in an application area such as natural language processing or computer vision, or in \n",
999
+ "a ...\n"
1000
+ ]
1001
+ }
1002
+ ],
1003
+ "source": [
1004
+ "from aimakerspace.text_utils import PDFLoader, CharacterTextSplitter\n",
1005
+ "from aimakerspace.vectordatabase import VectorDatabase\n",
1006
+ "from aimakerspace.openai_utils.prompts import SystemRolePrompt, UserRolePrompt\n",
1007
+ "from aimakerspace.openai_utils.chatmodel import ChatOpenAI\n",
1008
+ "from aimakerspace.openai_utils.embedding import EmbeddingModel\n",
1009
+ "import asyncio\n",
1010
+ "import os\n",
1011
+ "from getpass import getpass\n",
1012
+ "\n",
1013
+ "# Set up OpenAI API key\n",
1014
+ "api_key = os.getenv(\"OPENAI_API_KEY\")\n",
1015
+ "if not api_key:\n",
1016
+ " api_key = getpass(\"Enter your OpenAI API key: \")\n",
1017
+ " os.environ[\"OPENAI_API_KEY\"] = api_key\n",
1018
+ "\n",
1019
+ "\n",
1020
+ "\n",
1021
+ "\n",
1022
+ "# Load the PDF\n",
1023
+ "pdf_loader = PDFLoader(\"data/How-to-Build-a-Career-in-AI.pdf\")\n",
1024
+ "documents = pdf_loader.load_documents()\n",
1025
+ "\n",
1026
+ "# Split the documents into chunks with optimized parameters\n",
1027
+ "text_splitter = CharacterTextSplitter(chunk_size=1500, chunk_overlap=300)\n",
1028
+ "split_documents = text_splitter.split_texts(documents)\n",
1029
+ "\n",
1030
+ "# Create and populate the vector database with explicit embedding model\n",
1031
+ "embedding_model = EmbeddingModel()\n",
1032
+ "vector_db = VectorDatabase(embedding_model=embedding_model)\n",
1033
+ "vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))\n",
1034
+ "\n",
1035
+ "# Set up the RAG prompt templates\n",
1036
+ "RAG_PROMPT_TEMPLATE = \"\"\" \\\n",
1037
+ "Use the provided context to answer the user's query.\n",
1038
+ "\n",
1039
+ "You may not answer the user's query unless there is specific context in the following text.\n",
1040
+ "\n",
1041
+ "If you do not know the answer, or cannot answer, please respond with \"I don't know\".\n",
1042
+ "\"\"\"\n",
1043
+ "\n",
1044
+ "rag_prompt = SystemRolePrompt(RAG_PROMPT_TEMPLATE)\n",
1045
+ "\n",
1046
+ "USER_PROMPT_TEMPLATE = \"\"\" \\\n",
1047
+ "Context:\n",
1048
+ "{context}\n",
1049
+ "\n",
1050
+ "User Query:\n",
1051
+ "{user_query}\n",
1052
+ "\"\"\"\n",
1053
+ "\n",
1054
+ "user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)\n",
1055
+ "\n",
1056
+ "# Create the ChatOpenAI instance\n",
1057
+ "chat_openai = ChatOpenAI()\n",
1058
+ "\n",
1059
+ "# Create the RAG pipeline\n",
1060
+ "class RetrievalAugmentedQAPipeline:\n",
1061
+ " def __init__(self, llm: ChatOpenAI, vector_db_retriever: VectorDatabase) -> None:\n",
1062
+ " self.llm = llm\n",
1063
+ " self.vector_db_retriever = vector_db_retriever\n",
1064
+ "\n",
1065
+ " def run_pipeline(self, user_query: str) -> str:\n",
1066
+ " context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
1067
+ "\n",
1068
+ " context_prompt = \"\"\n",
1069
+ " for context in context_list:\n",
1070
+ " context_prompt += context[0] + \"\\n\"\n",
1071
+ "\n",
1072
+ " formatted_system_prompt = rag_prompt.create_message()\n",
1073
+ " formatted_user_prompt = user_prompt.create_message(\n",
1074
+ " user_query=user_query, \n",
1075
+ " context=context_prompt\n",
1076
+ " )\n",
1077
+ "\n",
1078
+ " return {\n",
1079
+ " \"response\": self.llm.run([formatted_system_prompt, formatted_user_prompt]),\n",
1080
+ " \"context\": context_list\n",
1081
+ " }\n",
1082
+ "\n",
1083
+ "# Create and run the pipeline\n",
1084
+ "retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
1085
+ " vector_db_retriever=vector_db,\n",
1086
+ " llm=chat_openai\n",
1087
+ ")\n",
1088
+ "\n",
1089
+ "# Test \n",
1090
+ "result = retrieval_augmented_qa_pipeline.run_pipeline(\"how many days does he have\")\n",
1091
+ "print(\"Response:\", result[\"response\"])\n",
1092
+ "print(\"\\nContext used:\")\n",
1093
+ "for i, context in enumerate(result[\"context\"], 1):\n",
1094
+ " print(f\"\\nContext {i}:\")\n",
1095
+ " print(context[0][:200] + \"...\")"
1096
+ ]
1097
+ }
1098
+ ],
1099
+ "metadata": {
1100
+ "colab": {
1101
+ "provenance": []
1102
+ },
1103
+ "kernelspec": {
1104
+ "display_name": ".venv",
1105
+ "language": "python",
1106
+ "name": "python3"
1107
+ },
1108
+ "language_info": {
1109
+ "codemirror_mode": {
1110
+ "name": "ipython",
1111
+ "version": 3
1112
+ },
1113
+ "file_extension": ".py",
1114
+ "mimetype": "text/x-python",
1115
+ "name": "python",
1116
+ "nbconvert_exporter": "python",
1117
+ "pygments_lexer": "ipython3",
1118
+ "version": "3.13.2"
1119
+ },
1120
+ "orig_nbformat": 4,
1121
+ "widgets": {
1122
+ "application/vnd.jupyter.widget-state+json": {
1123
+ "1ce393d9afcf427d9d352259c5d32678": {
1124
+ "model_module": "@jupyter-widgets/controls",
1125
+ "model_module_version": "1.5.0",
1126
+ "model_name": "FloatProgressModel",
1127
+ "state": {
1128
+ "_dom_classes": [],
1129
+ "_model_module": "@jupyter-widgets/controls",
1130
+ "_model_module_version": "1.5.0",
1131
+ "_model_name": "FloatProgressModel",
1132
+ "_view_count": null,
1133
+ "_view_module": "@jupyter-widgets/controls",
1134
+ "_view_module_version": "1.5.0",
1135
+ "_view_name": "ProgressView",
1136
+ "bar_style": "",
1137
+ "description": "",
1138
+ "description_tooltip": null,
1139
+ "layout": "IPY_MODEL_4e6efd99f7d346e485b002fb0fa85cc7",
1140
+ "max": 1,
1141
+ "min": 0,
1142
+ "orientation": "horizontal",
1143
+ "style": "IPY_MODEL_3dfb67c39958461da6071e4c19c3fa41",
1144
+ "value": 1
1145
+ }
1146
+ },
1147
+ "3a4ba348cb004f8ab7b2b1395539c81b": {
1148
+ "model_module": "@jupyter-widgets/controls",
1149
+ "model_module_version": "1.5.0",
1150
+ "model_name": "LabelModel",
1151
+ "state": {
1152
+ "_dom_classes": [],
1153
+ "_model_module": "@jupyter-widgets/controls",
1154
+ "_model_module_version": "1.5.0",
1155
+ "_model_name": "LabelModel",
1156
+ "_view_count": null,
1157
+ "_view_module": "@jupyter-widgets/controls",
1158
+ "_view_module_version": "1.5.0",
1159
+ "_view_name": "LabelView",
1160
+ "description": "",
1161
+ "description_tooltip": null,
1162
+ "layout": "IPY_MODEL_d2ea5009dd16442cb5d8a0ac468e50a8",
1163
+ "placeholder": "​",
1164
+ "style": "IPY_MODEL_5f00135fe1044051a50ee5e841cbb8e3",
1165
+ "value": "0.018 MB of 0.018 MB uploaded\r"
1166
+ }
1167
+ },
1168
+ "3dfb67c39958461da6071e4c19c3fa41": {
1169
+ "model_module": "@jupyter-widgets/controls",
1170
+ "model_module_version": "1.5.0",
1171
+ "model_name": "ProgressStyleModel",
1172
+ "state": {
1173
+ "_model_module": "@jupyter-widgets/controls",
1174
+ "_model_module_version": "1.5.0",
1175
+ "_model_name": "ProgressStyleModel",
1176
+ "_view_count": null,
1177
+ "_view_module": "@jupyter-widgets/base",
1178
+ "_view_module_version": "1.2.0",
1179
+ "_view_name": "StyleView",
1180
+ "bar_color": null,
1181
+ "description_width": ""
1182
+ }
1183
+ },
1184
+ "4e6efd99f7d346e485b002fb0fa85cc7": {
1185
+ "model_module": "@jupyter-widgets/base",
1186
+ "model_module_version": "1.2.0",
1187
+ "model_name": "LayoutModel",
1188
+ "state": {
1189
+ "_model_module": "@jupyter-widgets/base",
1190
+ "_model_module_version": "1.2.0",
1191
+ "_model_name": "LayoutModel",
1192
+ "_view_count": null,
1193
+ "_view_module": "@jupyter-widgets/base",
1194
+ "_view_module_version": "1.2.0",
1195
+ "_view_name": "LayoutView",
1196
+ "align_content": null,
1197
+ "align_items": null,
1198
+ "align_self": null,
1199
+ "border": null,
1200
+ "bottom": null,
1201
+ "display": null,
1202
+ "flex": null,
1203
+ "flex_flow": null,
1204
+ "grid_area": null,
1205
+ "grid_auto_columns": null,
1206
+ "grid_auto_flow": null,
1207
+ "grid_auto_rows": null,
1208
+ "grid_column": null,
1209
+ "grid_gap": null,
1210
+ "grid_row": null,
1211
+ "grid_template_areas": null,
1212
+ "grid_template_columns": null,
1213
+ "grid_template_rows": null,
1214
+ "height": null,
1215
+ "justify_content": null,
1216
+ "justify_items": null,
1217
+ "left": null,
1218
+ "margin": null,
1219
+ "max_height": null,
1220
+ "max_width": null,
1221
+ "min_height": null,
1222
+ "min_width": null,
1223
+ "object_fit": null,
1224
+ "object_position": null,
1225
+ "order": null,
1226
+ "overflow": null,
1227
+ "overflow_x": null,
1228
+ "overflow_y": null,
1229
+ "padding": null,
1230
+ "right": null,
1231
+ "top": null,
1232
+ "visibility": null,
1233
+ "width": null
1234
+ }
1235
+ },
1236
+ "56a8e24025594e5e9ff3b8581c344691": {
1237
+ "model_module": "@jupyter-widgets/base",
1238
+ "model_module_version": "1.2.0",
1239
+ "model_name": "LayoutModel",
1240
+ "state": {
1241
+ "_model_module": "@jupyter-widgets/base",
1242
+ "_model_module_version": "1.2.0",
1243
+ "_model_name": "LayoutModel",
1244
+ "_view_count": null,
1245
+ "_view_module": "@jupyter-widgets/base",
1246
+ "_view_module_version": "1.2.0",
1247
+ "_view_name": "LayoutView",
1248
+ "align_content": null,
1249
+ "align_items": null,
1250
+ "align_self": null,
1251
+ "border": null,
1252
+ "bottom": null,
1253
+ "display": null,
1254
+ "flex": null,
1255
+ "flex_flow": null,
1256
+ "grid_area": null,
1257
+ "grid_auto_columns": null,
1258
+ "grid_auto_flow": null,
1259
+ "grid_auto_rows": null,
1260
+ "grid_column": null,
1261
+ "grid_gap": null,
1262
+ "grid_row": null,
1263
+ "grid_template_areas": null,
1264
+ "grid_template_columns": null,
1265
+ "grid_template_rows": null,
1266
+ "height": null,
1267
+ "justify_content": null,
1268
+ "justify_items": null,
1269
+ "left": null,
1270
+ "margin": null,
1271
+ "max_height": null,
1272
+ "max_width": null,
1273
+ "min_height": null,
1274
+ "min_width": null,
1275
+ "object_fit": null,
1276
+ "object_position": null,
1277
+ "order": null,
1278
+ "overflow": null,
1279
+ "overflow_x": null,
1280
+ "overflow_y": null,
1281
+ "padding": null,
1282
+ "right": null,
1283
+ "top": null,
1284
+ "visibility": null,
1285
+ "width": null
1286
+ }
1287
+ },
1288
+ "5f00135fe1044051a50ee5e841cbb8e3": {
1289
+ "model_module": "@jupyter-widgets/controls",
1290
+ "model_module_version": "1.5.0",
1291
+ "model_name": "DescriptionStyleModel",
1292
+ "state": {
1293
+ "_model_module": "@jupyter-widgets/controls",
1294
+ "_model_module_version": "1.5.0",
1295
+ "_model_name": "DescriptionStyleModel",
1296
+ "_view_count": null,
1297
+ "_view_module": "@jupyter-widgets/base",
1298
+ "_view_module_version": "1.2.0",
1299
+ "_view_name": "StyleView",
1300
+ "description_width": ""
1301
+ }
1302
+ },
1303
+ "bb904e05ece143c79ecc4f20de482f45": {
1304
+ "model_module": "@jupyter-widgets/controls",
1305
+ "model_module_version": "1.5.0",
1306
+ "model_name": "VBoxModel",
1307
+ "state": {
1308
+ "_dom_classes": [],
1309
+ "_model_module": "@jupyter-widgets/controls",
1310
+ "_model_module_version": "1.5.0",
1311
+ "_model_name": "VBoxModel",
1312
+ "_view_count": null,
1313
+ "_view_module": "@jupyter-widgets/controls",
1314
+ "_view_module_version": "1.5.0",
1315
+ "_view_name": "VBoxView",
1316
+ "box_style": "",
1317
+ "children": [
1318
+ "IPY_MODEL_3a4ba348cb004f8ab7b2b1395539c81b",
1319
+ "IPY_MODEL_1ce393d9afcf427d9d352259c5d32678"
1320
+ ],
1321
+ "layout": "IPY_MODEL_56a8e24025594e5e9ff3b8581c344691"
1322
+ }
1323
+ },
1324
+ "d2ea5009dd16442cb5d8a0ac468e50a8": {
1325
+ "model_module": "@jupyter-widgets/base",
1326
+ "model_module_version": "1.2.0",
1327
+ "model_name": "LayoutModel",
1328
+ "state": {
1329
+ "_model_module": "@jupyter-widgets/base",
1330
+ "_model_module_version": "1.2.0",
1331
+ "_model_name": "LayoutModel",
1332
+ "_view_count": null,
1333
+ "_view_module": "@jupyter-widgets/base",
1334
+ "_view_module_version": "1.2.0",
1335
+ "_view_name": "LayoutView",
1336
+ "align_content": null,
1337
+ "align_items": null,
1338
+ "align_self": null,
1339
+ "border": null,
1340
+ "bottom": null,
1341
+ "display": null,
1342
+ "flex": null,
1343
+ "flex_flow": null,
1344
+ "grid_area": null,
1345
+ "grid_auto_columns": null,
1346
+ "grid_auto_flow": null,
1347
+ "grid_auto_rows": null,
1348
+ "grid_column": null,
1349
+ "grid_gap": null,
1350
+ "grid_row": null,
1351
+ "grid_template_areas": null,
1352
+ "grid_template_columns": null,
1353
+ "grid_template_rows": null,
1354
+ "height": null,
1355
+ "justify_content": null,
1356
+ "justify_items": null,
1357
+ "left": null,
1358
+ "margin": null,
1359
+ "max_height": null,
1360
+ "max_width": null,
1361
+ "min_height": null,
1362
+ "min_width": null,
1363
+ "object_fit": null,
1364
+ "object_position": null,
1365
+ "order": null,
1366
+ "overflow": null,
1367
+ "overflow_x": null,
1368
+ "overflow_y": null,
1369
+ "padding": null,
1370
+ "right": null,
1371
+ "top": null,
1372
+ "visibility": null,
1373
+ "width": null
1374
+ }
1375
+ }
1376
+ }
1377
+ }
1378
+ },
1379
+ "nbformat": 4,
1380
+ "nbformat_minor": 0
1381
+ }
README.md CHANGED
@@ -1,13 +1,76 @@
1
- ---
2
- title: Rag Implementation
3
- emoji: πŸ“ˆ
4
- colorFrom: blue
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.23.3
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: RAG Implementation Notebook
3
+ emoji: πŸ”
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 3.50.2
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # RAG Implementation Notebook
13
+
14
+ This space contains a Jupyter notebook demonstrating a Retrieval Augmented Generation (RAG) implementation using OpenAI's API and Hugging Face models.
15
+
16
+ ## Features
17
+ - PDF document processing
18
+ - Text chunking and embedding
19
+ - Vector database implementation
20
+ - RAG pipeline with context-aware responses
21
+
22
+ ## How to Use
23
+ 1. Clone this repository
24
+ 2. Install the requirements: `pip install -r requirements.txt`
25
+ 3. Open the notebook: `jupyter notebook Pythonic_RAG_Assignment.ipynb`
26
+
27
+ ## Requirements
28
+ See `requirements.txt` for the complete list of dependencies.
29
+
30
+ # πŸ§‘β€πŸ’»Β What is [AI Engineering](https://maven.com/aimakerspace/ai-eng-bootcamp)?
31
+
32
+ AI Engineering refers to the industry-relevant skills that data science and engineering teams need to successfully **build, deploy, operate, and improve Large Language Model (LLM) applications in production environments**.
33
+
34
+ In practice, this requires understanding both prototyping and production deployments.
35
+
36
+ During the *prototyping* phase, Prompt Engineering, Retrieval Augmented Generation (RAG), Agents, and Fine-Tuning are all necessary tools to be able to understand and leverage. Prototyping includes:
37
+ 1. Building RAG Applications
38
+ 2. Building with Agent and Multi-Agent Frameworks
39
+ 3. Fine-Tuning LLMs & Embedding Models
40
+ 4. Deploying LLM Prototype Applications to Users
41
+
42
+ When *productionizing* LLM application prototypes, there are many important aspects ensuring helpful, harmless, honest, reliable, and scalable solutions for your customers or stakeholders. Productionizing includes:
43
+ 1. Evaluating RAG and Agent Applications
44
+ 2. Improving Search and Retrieval Pipelines for Production
45
+ 3. Monitoring Production KPIs for LLM Applications
46
+ 4. Setting up Inference Servers for LLMs and Embedding Models
47
+ 5. Building LLM Applications with Scalable, Production-Grade Components
48
+
49
+ This bootcamp builds on our two previous courses, [LLM Engineering](https://maven.com/aimakerspace/llm-engineering) and [LLM Operations](https://maven.com/aimakerspace/llmops) πŸ‘‡
50
+
51
+ - Large Language Model Engineering (LLM Engineering) refers to the emerging best-practices and tools for pretraining, post-training, and optimizing LLMs prior to production deployment. Pre- and post-training techniques include unsupervised pretraining, supervised fine-tuning, alignment, model merging, distillation, quantization. and others.
52
+
53
+ - Large Language Model Ops (LLM Ops, or LLMOps (as from [WandB](https://docs.wandb.ai/guides/prompts) and [a16z](https://a16z.com/emerging-architectures-for-llm-applications/))) refers to the emerging best-practices, tooling, and improvement processes used to manage production LLM applications throughout the AI product lifecycle. LLM Ops is a subset of Machine Learning Operations (MLOps) that focuses on LLM-specific infrastructure and ops capabilities required to build, deploy, monitor, and scale complex LLM applications in production environments. _This term is being used much less in industry these days._
54
+
55
+ # πŸ† **Grading and Certification**
56
+
57
+ To become **AI-Makerspace Certified**, which will open you up to additional opportunities for full and part-time work within our community and network, you must:
58
+
59
+ 1. Complete all project assignments.
60
+ 2. Complete a project and present during Demo Day.
61
+ 3. Receive at least an 85% total grade in the course.
62
+
63
+ If you do not complete all assignments, participate in Demo Day, or maintain a high-quality standard of work, you may still be eligible for a *certificate of completion* if you miss no more than 2 live sessions.
64
+
65
+ # πŸ“š About
66
+
67
+ This GitHub repository is your gateway to mastering the art of AI Engineering. ***All assignments for the course will be released here for your building, shipping, and sharing adventures!***
68
+
69
+ # πŸ™ Contributions
70
+
71
+ We believe in the power of collaboration. Contributions, ideas, and feedback are highly encouraged! Let's build the ultimate resource for AI Engineering together.
72
+
73
+ Please to reach out with any questions or suggestions.
74
+
75
+ Happy coding! πŸš€πŸš€πŸš€
76
+
app.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+
4
+ def load_notebook():
5
+ notebook_path = "Pythonic_RAG_Assignment.ipynb"
6
+ if os.path.exists(notebook_path):
7
+ with open(notebook_path, "r", encoding="utf-8") as f:
8
+ return f.read()
9
+ return "Notebook not found"
10
+
11
+ with gr.Blocks() as demo:
12
+ gr.Markdown("# RAG Implementation Notebook")
13
+ gr.Markdown("This space contains a Jupyter notebook demonstrating a Retrieval Augmented Generation (RAG) implementation.")
14
+
15
+ with gr.Tabs():
16
+ with gr.TabItem("Notebook Preview"):
17
+ notebook_content = gr.Markdown(load_notebook())
18
+
19
+ with gr.TabItem("About"):
20
+ gr.Markdown("""
21
+ ## About This Space
22
+
23
+ This space contains a Jupyter notebook that demonstrates:
24
+ - PDF document processing
25
+ - Text chunking and embedding
26
+ - Vector database implementation
27
+ - RAG pipeline with context-aware responses
28
+
29
+ To run the notebook locally:
30
+ 1. Clone this repository
31
+ 2. Install requirements: `pip install -r requirements.txt`
32
+ 3. Run: `jupyter notebook Pythonic_RAG_Assignment.ipynb`
33
+ """)
34
+
35
+ if __name__ == "__main__":
36
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ jupyter
2
+ notebook
3
+ ipykernel
4
+ numpy
5
+ pandas
6
+ matplotlib
7
+ scikit-learn
8
+ transformers
9
+ datasets
10
+ huggingface_hub
11
+ openai