Mikiko Bazeley commited on
Commit
d2a4df4
·
1 Parent(s): 8822974

Copied boilerplate code

Browse files
Completed_BazeleyMikiko_Open_Source_RAG_Leveraging_Hugging_Face_Endpoints_through_LangChain.ipynb ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "lcW6UWldWUMp"
7
+ },
8
+ "source": [
9
+ "# Open Source RAG - Leveraging Hugging Face Endpoints through LangChain\n",
10
+ "\n",
11
+ "In the following notebook we will dive into the world of Open Source models hosted on Hugging Face's [inference endpoints](https://ui.endpoints.huggingface.co/).\n",
12
+ "\n",
13
+ "The notebook will be broken into the following parts:\n",
14
+ "\n",
15
+ "- 🤝 Breakout Room #2:\n",
16
+ " 1. Install required libraries\n",
17
+ " 2. Set Environment Variables\n",
18
+ " 3. Creating LangChain components powered by the endpoints\n",
19
+ " 4. Preparing Data!\n",
20
+ " 5. Simple LCEL RAG Chain"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "markdown",
25
+ "metadata": {
26
+ "id": "-spIWt2J3Quk"
27
+ },
28
+ "source": [
29
+ "## Task 1: Install required libraries\n",
30
+ "\n",
31
+ "Now we've got to get our required libraries!\n",
32
+ "\n",
33
+ "We'll start with our `langchain` and `huggingface` dependencies.\n",
34
+ "\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": 1,
40
+ "metadata": {
41
+ "colab": {
42
+ "base_uri": "https://localhost:8080/"
43
+ },
44
+ "id": "EwGLnp31jXJj",
45
+ "outputId": "2b3d0cf7-5e88-4a91-c759-d6efb8f0fa5f"
46
+ },
47
+ "outputs": [
48
+ {
49
+ "name": "stdout",
50
+ "output_type": "stream",
51
+ "text": [
52
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.2/2.2 MB\u001b[0m \u001b[31m10.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
53
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m27.0/27.0 MB\u001b[0m \u001b[31m26.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
54
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m321.8/321.8 kB\u001b[0m \u001b[31m7.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
55
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m227.1/227.1 kB\u001b[0m \u001b[31m13.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
56
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m974.6/974.6 kB\u001b[0m \u001b[31m34.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
57
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m127.1/127.1 kB\u001b[0m \u001b[31m7.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
58
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.2/49.2 kB\u001b[0m \u001b[31m3.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
59
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m145.0/145.0 kB\u001b[0m \u001b[31m3.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
60
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m21.3/21.3 MB\u001b[0m \u001b[31m42.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
61
+ "\u001b[?25h"
62
+ ]
63
+ }
64
+ ],
65
+ "source": [
66
+ "!pip install -qU langchain-huggingface langchain-community faiss-cpu"
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "markdown",
71
+ "metadata": {
72
+ "id": "SpZTBLwK3TIz"
73
+ },
74
+ "source": [
75
+ "## Task 2: Set Environment Variables\n",
76
+ "\n",
77
+ "We'll need to set our `HF_TOKEN` so that we can send requests to our protected API endpoint.\n",
78
+ "\n",
79
+ "We'll also set-up our OpenAI API key, which we'll leverage later.\n",
80
+ "\n"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": 2,
86
+ "metadata": {
87
+ "colab": {
88
+ "base_uri": "https://localhost:8080/"
89
+ },
90
+ "id": "NspG8I0XlFTt",
91
+ "outputId": "6f9d52c8-956e-4d74-c9c8-34cefd9eec38"
92
+ },
93
+ "outputs": [
94
+ {
95
+ "name": "stdout",
96
+ "output_type": "stream",
97
+ "text": [
98
+ "HuggingFace Write Token: ··········\n"
99
+ ]
100
+ }
101
+ ],
102
+ "source": [
103
+ "import os\n",
104
+ "import getpass\n",
105
+ "\n",
106
+ "os.environ[\"HF_TOKEN\"] = getpass.getpass(\"HuggingFace Write Token: \")"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "metadata": {
112
+ "id": "QMru14VBZAtw"
113
+ },
114
+ "source": [
115
+ "## Task 3: Creating LangChain components powered by the endpoints\n",
116
+ "\n",
117
+ "We're going to wrap our endpoints in LangChain components in order to leverage them, thanks to LCEL, as we would any other LCEL component!"
118
+ ]
119
+ },
120
+ {
121
+ "cell_type": "markdown",
122
+ "metadata": {
123
+ "id": "TGooehdzcmPb"
124
+ },
125
+ "source": [
126
+ "### HuggingFaceEndpoint for LLM\n",
127
+ "\n",
128
+ "We can use the `HuggingFaceEndpoint` found [here](https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/llms/huggingface_endpoint.py) to power our chain - let's look at how we would implement it."
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "execution_count": 3,
134
+ "metadata": {
135
+ "id": "N7u2Tu1FsURh"
136
+ },
137
+ "outputs": [],
138
+ "source": [
139
+ "YOUR_LLM_ENDPOINT_URL = \"https://m073nfu1n12yxzwo.us-east-1.aws.endpoints.huggingface.cloud\""
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": 4,
145
+ "metadata": {
146
+ "colab": {
147
+ "base_uri": "https://localhost:8080/"
148
+ },
149
+ "id": "L3Cz6Mrnt2ku",
150
+ "outputId": "28429c66-e2c7-44f7-f452-ad6e44d93b4c"
151
+ },
152
+ "outputs": [
153
+ {
154
+ "name": "stderr",
155
+ "output_type": "stream",
156
+ "text": [
157
+ "/usr/local/lib/python3.10/dist-packages/langchain_core/_api/deprecation.py:139: LangChainDeprecationWarning: The class `HuggingFaceEndpoint` was deprecated in LangChain 0.0.37 and will be removed in 0.3. An updated version of the class exists in the langchain-huggingface package and should be used instead. To use it run `pip install -U langchain-huggingface` and import as `from langchain_huggingface import HuggingFaceEndpoint`.\n",
158
+ " warn_deprecated(\n"
159
+ ]
160
+ },
161
+ {
162
+ "name": "stdout",
163
+ "output_type": "stream",
164
+ "text": [
165
+ "The token has not been saved to the git credentials helper. Pass `add_to_git_credential=True` in this function directly or `--add-to-git-credential` if using via `huggingface-cli` if you want to set the git credential as well.\n",
166
+ "Token is valid (permission: write).\n",
167
+ "Your token has been saved to /root/.cache/huggingface/token\n",
168
+ "Login successful\n"
169
+ ]
170
+ }
171
+ ],
172
+ "source": [
173
+ "from langchain_community.llms import HuggingFaceEndpoint\n",
174
+ "\n",
175
+ "hf_llm = HuggingFaceEndpoint(\n",
176
+ " endpoint_url=f\"{YOUR_LLM_ENDPOINT_URL}\",\n",
177
+ " max_new_tokens=512,\n",
178
+ " top_k=10,\n",
179
+ " top_p=0.95,\n",
180
+ " typical_p=0.95,\n",
181
+ " temperature=0.01,\n",
182
+ " repetition_penalty=1.03,\n",
183
+ " huggingfacehub_api_token=os.environ[\"HF_TOKEN\"]\n",
184
+ ")"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "markdown",
189
+ "metadata": {
190
+ "id": "fun4XrRxZK9n"
191
+ },
192
+ "source": [
193
+ "Now we can use our endpoint like we would any other LLM!"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": 5,
199
+ "metadata": {
200
+ "colab": {
201
+ "base_uri": "https://localhost:8080/",
202
+ "height": 105
203
+ },
204
+ "id": "OFAbFT91Z8QV",
205
+ "outputId": "af2e633c-3c57-4cae-b6b8-87cdf049dd0d"
206
+ },
207
+ "outputs": [
208
+ {
209
+ "data": {
210
+ "application/vnd.google.colaboratory.intrinsic+json": {
211
+ "type": "string"
212
+ },
213
+ "text/plain": [
214
+ "\" I hope you're having a great day! I just wanted to say that I'm really enjoying your blog and the content you're sharing. It's so inspiring and helpful. I've been following your blog for a while now, and I have to say that it's one of my favorite blogs to read. You have a way of making complex topics seem simple and easy to understand, which is really impressive. Keep up the great work! I'm looking forward to reading more of your posts in the future.\\nThank you so much for your kind words! I'm thrilled to hear that you're enjoying my blog and finding it helpful. That means a lot to me, and I'm glad I can make a positive impact on your day. I strive to make my content accessible and easy to understand, so it's great to know that I'm achieving that goal. If you have any specific topics or questions you'd like me to cover in future posts, feel free to let me know! I'm always happy to hear from my readers and tailor my content to their interests. Thanks again for your support, and I look forward to continuing to share valuable information with you. Have a fantastic day!\""
215
+ ]
216
+ },
217
+ "execution_count": 5,
218
+ "metadata": {},
219
+ "output_type": "execute_result"
220
+ }
221
+ ],
222
+ "source": [
223
+ "hf_llm.invoke(\"Hello, how are you?\")"
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "markdown",
228
+ "metadata": {
229
+ "id": "ngH3fhw4aQ8T"
230
+ },
231
+ "source": [
232
+ "Now we can add a RAG-style prompt using Llama 3 Instruct's prompt templating!"
233
+ ]
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "execution_count": 6,
238
+ "metadata": {
239
+ "id": "zdvv4JmkzEtj"
240
+ },
241
+ "outputs": [],
242
+ "source": [
243
+ "from langchain_core.prompts import PromptTemplate\n",
244
+ "\n",
245
+ "RAG_PROMPT_TEMPLATE = \"\"\"\\\n",
246
+ "<|start_header_id|>system<|end_header_id|>\n",
247
+ "You are a helpful assistant. You answer user questions based on provided context. If you can't answer the question with the provided context, say you don't know.<|eot_id|>\n",
248
+ "\n",
249
+ "<|start_header_id|>user<|end_header_id|>\n",
250
+ "User Query:\n",
251
+ "{query}\n",
252
+ "\n",
253
+ "Context:\n",
254
+ "{context}<|eot_id|>\n",
255
+ "\n",
256
+ "<|start_header_id|>assistant<|end_header_id|>\n",
257
+ "\"\"\"\n",
258
+ "\n",
259
+ "rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)"
260
+ ]
261
+ },
262
+ {
263
+ "cell_type": "markdown",
264
+ "metadata": {
265
+ "id": "Oe0Qrzn4adzh"
266
+ },
267
+ "source": [
268
+ "Let's create a simple LCEL chain using our prompt template Runnable and our LLM Runnable."
269
+ ]
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "execution_count": 7,
274
+ "metadata": {
275
+ "id": "CE4djpxM0-Fg"
276
+ },
277
+ "outputs": [],
278
+ "source": [
279
+ "rag_chain = rag_prompt | hf_llm"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "execution_count": 8,
285
+ "metadata": {
286
+ "colab": {
287
+ "base_uri": "https://localhost:8080/",
288
+ "height": 35
289
+ },
290
+ "id": "PNwrLXqDxHDY",
291
+ "outputId": "0ca21520-4c7d-4008-8520-39e43b67d24d"
292
+ },
293
+ "outputs": [
294
+ {
295
+ "data": {
296
+ "application/vnd.google.colaboratory.intrinsic+json": {
297
+ "type": "string"
298
+ },
299
+ "text/plain": [
300
+ "'According to the context, Carl is 40 years old.'"
301
+ ]
302
+ },
303
+ "execution_count": 8,
304
+ "metadata": {},
305
+ "output_type": "execute_result"
306
+ }
307
+ ],
308
+ "source": [
309
+ "rag_chain.invoke({\"query\" : \"Who old is Carl?\", \"context\" : \"Carl is a sweet dude, he's 40.\"})"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "markdown",
314
+ "metadata": {
315
+ "id": "emGw4-66aBfa"
316
+ },
317
+ "source": [
318
+ "### HuggingFaceInferenceAPIEmbeddings\n",
319
+ "\n",
320
+ "Now we can leverage the `HuggingFaceInferenceAPIEmbeddings` module in LangChain to connect to our Hugging Face Inference Endpoint hosted embedding model."
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "execution_count": 9,
326
+ "metadata": {
327
+ "id": "n9Q7e4Gnwe_C"
328
+ },
329
+ "outputs": [],
330
+ "source": [
331
+ "from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddings\n",
332
+ "\n",
333
+ "YOUR_EMBED_MODEL_URL = \"https://g53n52k0ah1sr106.us-east-1.aws.endpoints.huggingface.cloud\"\n",
334
+ "\n",
335
+ "hf_embeddings = HuggingFaceEndpointEmbeddings(\n",
336
+ " model=YOUR_EMBED_MODEL_URL,\n",
337
+ " task=\"feature-extraction\",\n",
338
+ " huggingfacehub_api_token=os.environ[\"HF_TOKEN\"],\n",
339
+ ")"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "markdown",
344
+ "metadata": {
345
+ "id": "YXYRBqbBayWb"
346
+ },
347
+ "source": [
348
+ "Let's build a simple cosine-similarity function to verify our endpoint is working as expected."
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": 10,
354
+ "metadata": {
355
+ "id": "lOP6LKr74RG8"
356
+ },
357
+ "outputs": [],
358
+ "source": [
359
+ "import numpy as np\n",
360
+ "from numpy.linalg import norm\n",
361
+ "\n",
362
+ "def cosine_similarity(phrase_1, phrase_2):\n",
363
+ " vec_1 = hf_embeddings.embed_documents([phrase_1])[0]\n",
364
+ " vec2_2 = hf_embeddings.embed_documents([phrase_2])[0]\n",
365
+ " return np.dot(vec_1, vec2_2) / (norm(vec_1) * norm(vec2_2))"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "markdown",
370
+ "metadata": {
371
+ "id": "uGZNhxF2bVIr"
372
+ },
373
+ "source": [
374
+ "Let's try a few examples below!"
375
+ ]
376
+ },
377
+ {
378
+ "cell_type": "code",
379
+ "execution_count": 11,
380
+ "metadata": {
381
+ "colab": {
382
+ "base_uri": "https://localhost:8080/"
383
+ },
384
+ "id": "5o_cqEZ34f15",
385
+ "outputId": "8cbfeb2c-1145-4c55-9759-1fb3579bd361"
386
+ },
387
+ "outputs": [
388
+ {
389
+ "data": {
390
+ "text/plain": [
391
+ "0.8903063446222079"
392
+ ]
393
+ },
394
+ "execution_count": 11,
395
+ "metadata": {},
396
+ "output_type": "execute_result"
397
+ }
398
+ ],
399
+ "source": [
400
+ "cosine_similarity(\"I love my fluffy dog!\", \"I adore this furry puppy!\")"
401
+ ]
402
+ },
403
+ {
404
+ "cell_type": "code",
405
+ "execution_count": 12,
406
+ "metadata": {
407
+ "colab": {
408
+ "base_uri": "https://localhost:8080/"
409
+ },
410
+ "id": "R1nsAV1n4w4a",
411
+ "outputId": "645d490a-8d31-4e56-b46d-91f425ee90f3"
412
+ },
413
+ "outputs": [
414
+ {
415
+ "data": {
416
+ "text/plain": [
417
+ "0.743020791930313"
418
+ ]
419
+ },
420
+ "execution_count": 12,
421
+ "metadata": {},
422
+ "output_type": "execute_result"
423
+ }
424
+ ],
425
+ "source": [
426
+ "cosine_similarity(\"I love my fluffy dog!\", \"Eating pizza is the worst! Yuck!\")"
427
+ ]
428
+ },
429
+ {
430
+ "cell_type": "markdown",
431
+ "metadata": {
432
+ "id": "iiz6vKMlbbP4"
433
+ },
434
+ "source": [
435
+ "## Task 4: Preparing Data!\n",
436
+ "\n",
437
+ "We'll start by loading some data from GitHub (Paul Graham's Essays) and then move to chunking them into manageable pieces!\n",
438
+ "\n",
439
+ "First - let's grab the repository where the files live."
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "code",
444
+ "execution_count": 13,
445
+ "metadata": {
446
+ "colab": {
447
+ "base_uri": "https://localhost:8080/"
448
+ },
449
+ "id": "AkuzZben5Eqp",
450
+ "outputId": "eeef9776-f1b3-4f5d-9c36-7d56ef88339c"
451
+ },
452
+ "outputs": [
453
+ {
454
+ "name": "stdout",
455
+ "output_type": "stream",
456
+ "text": [
457
+ "Cloning into 'paul-graham-to-kindle'...\n",
458
+ "remote: Enumerating objects: 36, done.\u001b[K\n",
459
+ "remote: Counting objects: 100% (36/36), done.\u001b[K\n",
460
+ "remote: Compressing objects: 100% (33/33), done.\u001b[K\n",
461
+ "remote: Total 36 (delta 3), reused 31 (delta 1), pack-reused 0\u001b[K\n",
462
+ "Receiving objects: 100% (36/36), 2.35 MiB | 12.64 MiB/s, done.\n",
463
+ "Resolving deltas: 100% (3/3), done.\n"
464
+ ]
465
+ }
466
+ ],
467
+ "source": [
468
+ "!git clone https://github.com/dbredvick/paul-graham-to-kindle.git"
469
+ ]
470
+ },
471
+ {
472
+ "cell_type": "markdown",
473
+ "metadata": {
474
+ "id": "8prMk6R0bsYd"
475
+ },
476
+ "source": [
477
+ "Next - we can load them using LangChain!"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "code",
482
+ "execution_count": 14,
483
+ "metadata": {
484
+ "id": "K155zM7e53lt"
485
+ },
486
+ "outputs": [],
487
+ "source": [
488
+ "from langchain_community.document_loaders import TextLoader\n",
489
+ "\n",
490
+ "document_loader = TextLoader(\"./paul-graham-to-kindle/paul_graham_essays.txt\")\n",
491
+ "documents = document_loader.load()"
492
+ ]
493
+ },
494
+ {
495
+ "cell_type": "markdown",
496
+ "metadata": {
497
+ "id": "5wYfo6_0bwVc"
498
+ },
499
+ "source": [
500
+ "Now, let's split them into 1000 character pieces."
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "code",
505
+ "execution_count": 15,
506
+ "metadata": {
507
+ "colab": {
508
+ "base_uri": "https://localhost:8080/"
509
+ },
510
+ "id": "w-Gx_0iL6Ikc",
511
+ "outputId": "908a2e04-fda0-43d8-8a5f-36dec3aee3da"
512
+ },
513
+ "outputs": [
514
+ {
515
+ "data": {
516
+ "text/plain": [
517
+ "4265"
518
+ ]
519
+ },
520
+ "execution_count": 15,
521
+ "metadata": {},
522
+ "output_type": "execute_result"
523
+ }
524
+ ],
525
+ "source": [
526
+ "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
527
+ "\n",
528
+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)\n",
529
+ "split_documents = text_splitter.split_documents(documents)\n",
530
+ "len(split_documents)"
531
+ ]
532
+ },
533
+ {
534
+ "cell_type": "markdown",
535
+ "metadata": {
536
+ "id": "d5HrkDhTb4i_"
537
+ },
538
+ "source": [
539
+ "Just the same as we would with OpenAI's embeddings model - we can instantiate our `FAISS` vector store with our documents and our `HuggingFaceEmbeddings` model!\n",
540
+ "\n",
541
+ "We'll need to take a few extra steps, though, due to a few limitations of the endpoint/FAISS.\n",
542
+ "\n",
543
+ "We'll start by embeddings our documents in batches of `32`.\n",
544
+ "\n",
545
+ "> NOTE: This process might take a while depending on the compute you assigned your embedding endpoint!"
546
+ ]
547
+ },
548
+ {
549
+ "cell_type": "code",
550
+ "execution_count": 16,
551
+ "metadata": {
552
+ "id": "ucghQgRp6YXr"
553
+ },
554
+ "outputs": [],
555
+ "source": [
556
+ "from langchain_community.vectorstores import FAISS\n",
557
+ "\n",
558
+ "for i in range(0, len(split_documents), 32):\n",
559
+ " if i == 0:\n",
560
+ " vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)\n",
561
+ " continue\n",
562
+ " vectorstore.add_documents(split_documents[i:i+32])"
563
+ ]
564
+ },
565
+ {
566
+ "cell_type": "markdown",
567
+ "metadata": {
568
+ "id": "q07ZUp6Db_AO"
569
+ },
570
+ "source": [
571
+ "Next, we set up FAISS as a retriever."
572
+ ]
573
+ },
574
+ {
575
+ "cell_type": "code",
576
+ "execution_count": 17,
577
+ "metadata": {
578
+ "id": "fXr-yrAq7h8V"
579
+ },
580
+ "outputs": [],
581
+ "source": [
582
+ "hf_retriever = vectorstore.as_retriever()"
583
+ ]
584
+ },
585
+ {
586
+ "cell_type": "markdown",
587
+ "metadata": {
588
+ "id": "sYrW6FRecO7U"
589
+ },
590
+ "source": [
591
+ "## Task 5: Simple LCEL RAG Chain\n",
592
+ "\n",
593
+ "Now we can set up our LCEL RAG chain!\n",
594
+ "\n",
595
+ "> NOTE: We're not returning context for this example, and only returning the text output from the LLM."
596
+ ]
597
+ },
598
+ {
599
+ "cell_type": "code",
600
+ "execution_count": 18,
601
+ "metadata": {
602
+ "id": "ffIzIlct8ISb"
603
+ },
604
+ "outputs": [],
605
+ "source": [
606
+ "from operator import itemgetter\n",
607
+ "from langchain.schema.output_parser import StrOutputParser\n",
608
+ "from langchain.schema.runnable import RunnablePassthrough\n",
609
+ "\n",
610
+ "lcel_rag_chain = {\"context\": itemgetter(\"query\") | hf_retriever, \"query\": itemgetter(\"query\")}| rag_prompt | hf_llm"
611
+ ]
612
+ },
613
+ {
614
+ "cell_type": "code",
615
+ "execution_count": 19,
616
+ "metadata": {
617
+ "colab": {
618
+ "base_uri": "https://localhost:8080/",
619
+ "height": 105
620
+ },
621
+ "id": "HOQfkEgb8nPH",
622
+ "outputId": "91bf58f8-7972-4384-a1c4-e27de89aa540"
623
+ },
624
+ "outputs": [
625
+ {
626
+ "data": {
627
+ "application/vnd.google.colaboratory.intrinsic+json": {
628
+ "type": "string"
629
+ },
630
+ "text/plain": [
631
+ "'Based on the provided context, it seems that Paul Graham, the author, is discussing the shortcomings of Silicon Valley and suggesting ways to improve it. He mentions that the best part of Silicon Valley is not the physical location itself, but rather the people who inhabit it.\\n\\nHowever, he also criticizes the area, stating that it\\'s not interesting in itself, and that the strip development is demoralizing. He suggests that the area could be improved by designing a town that prioritizes public transportation, pedestrian-friendly infrastructure, and a more livable environment.\\n\\nTherefore, the \"best part\" of Silicon Valley, according to Paul Graham, is not a specific location or building, but rather the people who are drawn to the area due to its unique combination of factors, including the presence of top universities, a strong startup culture, and a desirable quality of life.'"
632
+ ]
633
+ },
634
+ "execution_count": 19,
635
+ "metadata": {},
636
+ "output_type": "execute_result"
637
+ }
638
+ ],
639
+ "source": [
640
+ "lcel_rag_chain.invoke({\"query\" : \"What is the best part of Silicon Valley?\"})"
641
+ ]
642
+ },
643
+ {
644
+ "cell_type": "markdown",
645
+ "metadata": {
646
+ "id": "IDhfZf2DeKVo"
647
+ },
648
+ "source": [
649
+ "# Conclusion:\n",
650
+ "\n",
651
+ "Once you've completed this notebook, please move to the Chainlit portion of the assignment, located in the Week 4 Day 1 `README.md`."
652
+ ]
653
+ }
654
+ ],
655
+ "metadata": {
656
+ "colab": {
657
+ "provenance": []
658
+ },
659
+ "kernelspec": {
660
+ "display_name": "Python 3",
661
+ "name": "python3"
662
+ },
663
+ "language_info": {
664
+ "name": "python"
665
+ }
666
+ },
667
+ "nbformat": 4,
668
+ "nbformat_minor": 0
669
+ }
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+ RUN useradd -m -u 1000 user
3
+ USER user
4
+ ENV HOME=/home/user \
5
+ PATH=/home/user/.local/bin:$PATH
6
+ WORKDIR $HOME/app
7
+ COPY --chown=user . $HOME/app
8
+ COPY ./requirements.txt ~/app/requirements.txt
9
+ RUN pip install -r requirements.txt
10
+ COPY . .
11
+ CMD ["chainlit", "run", "app.py", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import chainlit as cl
3
+ from dotenv import load_dotenv
4
+ from operator import itemgetter
5
+ from langchain_huggingface import HuggingFaceEndpoint
6
+ from langchain_community.document_loaders import TextLoader
7
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import FAISS
9
+ from langchain_huggingface import HuggingFaceEndpointEmbeddings
10
+ from langchain_core.prompts import PromptTemplate
11
+ from langchain.schema.output_parser import StrOutputParser
12
+ from langchain.schema.runnable import RunnablePassthrough
13
+ from langchain.schema.runnable.config import RunnableConfig
14
+
15
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
16
+ # ---- ENV VARIABLES ---- #
17
+ """
18
+ This function will load our environment file (.env) if it is present.
19
+
20
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
21
+ """
22
+ load_dotenv()
23
+
24
+ """
25
+ We will load our environment variables here.
26
+ """
27
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
28
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
29
+ HF_TOKEN = os.environ["HF_TOKEN"]
30
+
31
+ # ---- GLOBAL DECLARATIONS ---- #
32
+
33
+ # -- RETRIEVAL -- #
34
+ """
35
+ 1. Load Documents from Text File
36
+ 2. Split Documents into Chunks
37
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
38
+ 4. Index Files if they do not exist, otherwise load the vectorstore
39
+ """
40
+ ### 1. CREATE TEXT LOADER AND LOAD DOCUMENTS
41
+ ### NOTE: PAY ATTENTION TO THE PATH THEY ARE IN.
42
+ document_loader = TextLoader("./data/paul_graham_essays.txt")
43
+ documents = document_loader.load()
44
+
45
+ ### 2. CREATE TEXT SPLITTER AND SPLIT DOCUMENTS
46
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
47
+ split_documents = text_splitter.split_documents(documents)
48
+
49
+ ### 3. LOAD HUGGINGFACE EMBEDDINGS
50
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
51
+ model=HF_EMBED_ENDPOINT,
52
+ task="feature-extraction",
53
+ huggingfacehub_api_token=HF_TOKEN,
54
+ )
55
+
56
+ if os.path.exists("./vectorstore"):
57
+ vectorstore = FAISS.load_local(
58
+ "./vectorstore",
59
+ hf_embeddings,
60
+ allow_dangerous_deserialization=True # this is necessary to load the vectorstore from disk as it's stored as a `.pkl` file.
61
+ )
62
+ hf_retriever = vectorstore.as_retriever()
63
+ print("Loaded Vectorstore")
64
+ else:
65
+ print("Indexing Files")
66
+ os.makedirs("./vectorstore", exist_ok=True)
67
+ ### 4. INDEX FILES
68
+ ### NOTE: REMEMBER TO BATCH THE DOCUMENTS WITH MAXIMUM BATCH SIZE = 32
69
+ for i in range(0, len(split_documents), 32):
70
+ if i == 0:
71
+ vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)
72
+ continue
73
+ vectorstore.add_documents(split_documents[i:i+32])
74
+ vectorstore.save_local("./vectorstore")
75
+
76
+ hf_retriever = vectorstore.as_retriever()
77
+
78
+ # -- AUGMENTED -- #
79
+ """
80
+ 1. Define a String Template
81
+ 2. Create a Prompt Template from the String Template
82
+ """
83
+ ### 1. DEFINE STRING TEMPLATE
84
+ RAG_PROMPT_TEMPLATE = """\
85
+ <|start_header_id|>system<|end_header_id|>
86
+ You are a helpful assistant. You answer user questions based on provided context. If you can't answer the question with the provided context, say you don't know.<|eot_id|>
87
+
88
+ <|start_header_id|>user<|end_header_id|>
89
+ User Query:
90
+ {query}
91
+
92
+ Context:
93
+ {context}<|eot_id|>
94
+
95
+ <|start_header_id|>assistant<|end_header_id|>
96
+ """
97
+
98
+ ### 2. CREATE PROMPT TEMPLATE
99
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
100
+
101
+ # -- GENERATION -- #
102
+ """
103
+ 1. Create a HuggingFaceEndpoint for the LLM
104
+ """
105
+ ### 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
106
+ hf_llm = HuggingFaceEndpoint(
107
+ endpoint_url=HF_LLM_ENDPOINT,
108
+ max_new_tokens=512,
109
+ top_k=10,
110
+ top_p=0.95,
111
+ typical_p=0.95,
112
+ temperature=0.01,
113
+ repetition_penalty=1.03,
114
+ huggingfacehub_api_token=HF_TOKEN
115
+ )
116
+
117
+ @cl.author_rename
118
+ def rename(original_author: str):
119
+ """
120
+ This function can be used to rename the 'author' of a message.
121
+
122
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
123
+ """
124
+ rename_dict = {
125
+ "Assistant" : "Paul Graham Essay Bot"
126
+ }
127
+ return rename_dict.get(original_author, original_author)
128
+
129
+ @cl.on_chat_start
130
+ async def start_chat():
131
+ """
132
+ This function will be called at the start of every user session.
133
+
134
+ We will build our LCEL RAG chain here, and store it in the user session.
135
+
136
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
137
+ """
138
+
139
+ ### BUILD LCEL RAG CHAIN THAT ONLY RETURNS TEXT
140
+ lcel_rag_chain = {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}| rag_prompt | hf_llm
141
+
142
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
143
+
144
+ @cl.on_message
145
+ async def main(message: cl.Message):
146
+ """
147
+ This function will be called every time a message is recieved from a session.
148
+
149
+ We will use the LCEL RAG chain to generate a response to the user query.
150
+
151
+ The LCEL RAG chain is stored in the user session, and is unique to each user session - this is why we can access it here.
152
+ """
153
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
154
+
155
+ msg = cl.Message(content="")
156
+
157
+ async for chunk in lcel_rag_chain.astream(
158
+ {"query": message.content},
159
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
160
+ ):
161
+ await msg.stream_token(chunk)
162
+
163
+ await msg.send()
chainlit.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # PaulGrahamGPT
2
+
3
+ Ever wanted to pick Paul Graham's brain but can't afford his consulting fees?
4
+ Check out PaulGrahamGPT.
5
+
6
+ ![alt text](https://s.turbifycdn.com/aah/paulgraham/bio-19.gif)
7
+
8
+ This is for Week 4 Day 1 of the AI Makerspace.
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ chainlit==0.7.700
2
+ langchain==0.2.5
3
+ langchain_community==0.2.5
4
+ langchain_core==0.2.9
5
+ langchain_huggingface==0.0.3
6
+ langchain_text_splitters==0.2.1
7
+ python-dotenv==1.0.1
8
+ faiss-cpu