mickkhaw commited on
Commit
e3e5f9d
1 Parent(s): 25b55b4

copied files

Browse files
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"]
Open_Source_RAG_Leveraging_Hugging_Face_Endpoints_through_LangChain.ipynb ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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. Creating a simple RAG pipeline with [LangChain v0.2.0](https://blog.langchain.dev/langchain-v02-leap-to-stability/)"
20
+ ]
21
+ },
22
+ {
23
+ "cell_type": "markdown",
24
+ "metadata": {
25
+ "id": "-spIWt2J3Quk"
26
+ },
27
+ "source": [
28
+ "## Task 1: Install required libraries\n",
29
+ "\n",
30
+ "Now we've got to get our required libraries!\n",
31
+ "\n",
32
+ "We'll start with our `langchain` and `huggingface` dependencies.\n",
33
+ "\n"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "execution_count": 1,
39
+ "metadata": {
40
+ "id": "EwGLnp31jXJj"
41
+ },
42
+ "outputs": [
43
+ {
44
+ "name": "stdout",
45
+ "output_type": "stream",
46
+ "text": [
47
+ "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
48
+ "s3fs 2023.3.0 requires fsspec==2023.3.0, but you have fsspec 2024.6.0 which is incompatible.\u001b[0m\u001b[31m\n",
49
+ "\u001b[0m"
50
+ ]
51
+ }
52
+ ],
53
+ "source": [
54
+ "!pip install -qU langchain-huggingface langchain-community faiss-cpu"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "markdown",
59
+ "metadata": {
60
+ "id": "SpZTBLwK3TIz"
61
+ },
62
+ "source": [
63
+ "## Task 2: Set Environment Variables\n",
64
+ "\n",
65
+ "We'll need to set our `HF_TOKEN` so that we can send requests to our protected API endpoint.\n",
66
+ "\n",
67
+ "We'll also set-up our OpenAI API key, which we'll leverage later.\n",
68
+ "\n"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": 2,
74
+ "metadata": {
75
+ "colab": {
76
+ "base_uri": "https://localhost:8080/"
77
+ },
78
+ "id": "NspG8I0XlFTt",
79
+ "outputId": "edbf992c-97c0-46b1-9b69-40651a5e60d1"
80
+ },
81
+ "outputs": [],
82
+ "source": [
83
+ "import os\n",
84
+ "import getpass\n",
85
+ "\n",
86
+ "os.environ[\"HF_TOKEN\"] = getpass.getpass(\"HuggingFace Write Token: \")"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "markdown",
91
+ "metadata": {
92
+ "id": "QMru14VBZAtw"
93
+ },
94
+ "source": [
95
+ "## Task 3: Creating LangChain components powered by the endpoints\n",
96
+ "\n",
97
+ "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!"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "markdown",
102
+ "metadata": {
103
+ "id": "TGooehdzcmPb"
104
+ },
105
+ "source": [
106
+ "### HuggingFaceEndpoint for LLM\n",
107
+ "\n",
108
+ "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."
109
+ ]
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "execution_count": 98,
114
+ "metadata": {
115
+ "id": "N7u2Tu1FsURh"
116
+ },
117
+ "outputs": [],
118
+ "source": [
119
+ "YOUR_LLM_ENDPOINT_URL = \"YOUR LLM_ENDPOINT_URL HERE\""
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": 99,
125
+ "metadata": {
126
+ "colab": {
127
+ "base_uri": "https://localhost:8080/"
128
+ },
129
+ "id": "L3Cz6Mrnt2ku",
130
+ "outputId": "f23f611f-5f08-4332-a74c-5b8d8311d185"
131
+ },
132
+ "outputs": [
133
+ {
134
+ "name": "stdout",
135
+ "output_type": "stream",
136
+ "text": [
137
+ "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",
138
+ "Token is valid (permission: write).\n",
139
+ "Your token has been saved to /root/.cache/huggingface/token\n",
140
+ "Login successful\n"
141
+ ]
142
+ }
143
+ ],
144
+ "source": [
145
+ "from langchain_community.llms import HuggingFaceEndpoint\n",
146
+ "\n",
147
+ "hf_llm = HuggingFaceEndpoint(\n",
148
+ " endpoint_url=f\"{YOUR_LLM_ENDPOINT_URL}\",\n",
149
+ " max_new_tokens=512,\n",
150
+ " top_k=10,\n",
151
+ " top_p=0.95,\n",
152
+ " typical_p=0.95,\n",
153
+ " temperature=0.01,\n",
154
+ " repetition_penalty=1.03,\n",
155
+ " huggingfacehub_api_token=os.environ[\"HF_TOKEN\"]\n",
156
+ ")"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {
162
+ "id": "fun4XrRxZK9n"
163
+ },
164
+ "source": [
165
+ "Now we can use our endpoint like we would any other LLM!"
166
+ ]
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "execution_count": 104,
171
+ "metadata": {
172
+ "colab": {
173
+ "base_uri": "https://localhost:8080/",
174
+ "height": 127
175
+ },
176
+ "id": "OFAbFT91Z8QV",
177
+ "outputId": "588714ad-da28-4330-801b-7121b6f17ccf"
178
+ },
179
+ "outputs": [
180
+ {
181
+ "data": {
182
+ "application/vnd.google.colaboratory.intrinsic+json": {
183
+ "type": "string"
184
+ },
185
+ "text/plain": [
186
+ "\" I hope you're having a great day! I just wanted to say that I'm really enjoying your blog and the information you share. It's always great to learn something new and I appreciate the effort you put into creating such a valuable resource. Keep up the good work! Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards, [Your Name]\\nI hope this message is helpful. Let me know if you have any questions or need further assistance. Thank you for your time and consideration. Best regards\""
187
+ ]
188
+ },
189
+ "execution_count": 104,
190
+ "metadata": {},
191
+ "output_type": "execute_result"
192
+ }
193
+ ],
194
+ "source": [
195
+ "hf_llm.invoke(\"Hello, how are you?\")"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "markdown",
200
+ "metadata": {
201
+ "id": "ngH3fhw4aQ8T"
202
+ },
203
+ "source": [
204
+ "Now we can add a RAG-style prompt using Llama 3 Instruct's prompt templating!"
205
+ ]
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "execution_count": 101,
210
+ "metadata": {
211
+ "id": "zdvv4JmkzEtj"
212
+ },
213
+ "outputs": [],
214
+ "source": [
215
+ "from langchain_core.prompts import PromptTemplate\n",
216
+ "\n",
217
+ "RAG_PROMPT_TEMPLATE = \"\"\"\\\n",
218
+ "<|start_header_id|>system<|end_header_id|>\n",
219
+ "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",
220
+ "\n",
221
+ "<|start_header_id|>user<|end_header_id|>\n",
222
+ "User Query:\n",
223
+ "{query}\n",
224
+ "\n",
225
+ "Context:\n",
226
+ "{context}<|eot_id|>\n",
227
+ "\n",
228
+ "<|start_header_id|>assistant<|end_header_id|>\n",
229
+ "\"\"\"\n",
230
+ "\n",
231
+ "rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)"
232
+ ]
233
+ },
234
+ {
235
+ "cell_type": "markdown",
236
+ "metadata": {
237
+ "id": "Oe0Qrzn4adzh"
238
+ },
239
+ "source": [
240
+ "Let's create a simple LCEL chain using our prompt template Runnable and our LLM Runnable."
241
+ ]
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "execution_count": 102,
246
+ "metadata": {
247
+ "id": "CE4djpxM0-Fg"
248
+ },
249
+ "outputs": [],
250
+ "source": [
251
+ "rag_chain = rag_prompt | hf_llm"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": 103,
257
+ "metadata": {
258
+ "colab": {
259
+ "base_uri": "https://localhost:8080/",
260
+ "height": 36
261
+ },
262
+ "id": "PNwrLXqDxHDY",
263
+ "outputId": "f6803286-1aa5-488a-eea9-8bece68da7f5"
264
+ },
265
+ "outputs": [
266
+ {
267
+ "data": {
268
+ "application/vnd.google.colaboratory.intrinsic+json": {
269
+ "type": "string"
270
+ },
271
+ "text/plain": [
272
+ "'According to the context, Carl is 40 years old.'"
273
+ ]
274
+ },
275
+ "execution_count": 103,
276
+ "metadata": {},
277
+ "output_type": "execute_result"
278
+ }
279
+ ],
280
+ "source": [
281
+ "rag_chain.invoke({\"query\" : \"Who old is Carl?\", \"context\" : \"Carl is a sweet dude, he's 40.\"})"
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "markdown",
286
+ "metadata": {
287
+ "id": "emGw4-66aBfa"
288
+ },
289
+ "source": [
290
+ "### HuggingFaceInferenceAPIEmbeddings\n",
291
+ "\n",
292
+ "Now we can leverage the `HuggingFaceInferenceAPIEmbeddings` module in LangChain to connect to our Hugging Face Inference Endpoint hosted embedding model."
293
+ ]
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "execution_count": 105,
298
+ "metadata": {
299
+ "id": "n9Q7e4Gnwe_C"
300
+ },
301
+ "outputs": [],
302
+ "source": [
303
+ "from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddings\n",
304
+ "\n",
305
+ "YOUR_EMBED_MODEL_URL = \"YOUR EMBED MODEL URL HERE\"\n",
306
+ "\n",
307
+ "hf_embeddings = HuggingFaceEndpointEmbeddings(\n",
308
+ " model=YOUR_EMBED_MODEL_URL,\n",
309
+ " task=\"feature-extraction\",\n",
310
+ " huggingfacehub_api_token=os.environ[\"HF_TOKEN\"],\n",
311
+ ")"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "markdown",
316
+ "metadata": {
317
+ "id": "YXYRBqbBayWb"
318
+ },
319
+ "source": [
320
+ "Let's build a simple cosine-similarity function to verify our endpoint is working as expected."
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "execution_count": null,
326
+ "metadata": {
327
+ "id": "lOP6LKr74RG8"
328
+ },
329
+ "outputs": [],
330
+ "source": [
331
+ "import numpy as np\n",
332
+ "from numpy.linalg import norm\n",
333
+ "\n",
334
+ "def cosine_similarity(phrase_1, phrase_2):\n",
335
+ " vec_1 = hf_embeddings.embed_documents([phrase_1])[0]\n",
336
+ " vec2_2 = hf_embeddings.embed_documents([phrase_2])[0]\n",
337
+ " return np.dot(vec_1, vec2_2) / (norm(vec_1) * norm(vec2_2))"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "metadata": {
343
+ "id": "uGZNhxF2bVIr"
344
+ },
345
+ "source": [
346
+ "Let's try a few examples below!"
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "execution_count": null,
352
+ "metadata": {
353
+ "colab": {
354
+ "base_uri": "https://localhost:8080/"
355
+ },
356
+ "id": "5o_cqEZ34f15",
357
+ "outputId": "d3eb4933-8842-4278-fe48-2dc15e430b60"
358
+ },
359
+ "outputs": [
360
+ {
361
+ "data": {
362
+ "text/plain": [
363
+ "0.8903063446222079"
364
+ ]
365
+ },
366
+ "execution_count": 44,
367
+ "metadata": {},
368
+ "output_type": "execute_result"
369
+ }
370
+ ],
371
+ "source": [
372
+ "cosine_similarity(\"I love my fluffy dog!\", \"I adore this furry puppy!\")"
373
+ ]
374
+ },
375
+ {
376
+ "cell_type": "code",
377
+ "execution_count": null,
378
+ "metadata": {
379
+ "colab": {
380
+ "base_uri": "https://localhost:8080/"
381
+ },
382
+ "id": "R1nsAV1n4w4a",
383
+ "outputId": "db53d783-4c87-404f-de67-fc1d01583e68"
384
+ },
385
+ "outputs": [
386
+ {
387
+ "data": {
388
+ "text/plain": [
389
+ "0.743020791930313"
390
+ ]
391
+ },
392
+ "execution_count": 48,
393
+ "metadata": {},
394
+ "output_type": "execute_result"
395
+ }
396
+ ],
397
+ "source": [
398
+ "cosine_similarity(\"I love my fluffy dog!\", \"Eating pizza is the worst! Yuck!\")"
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "markdown",
403
+ "metadata": {
404
+ "id": "iiz6vKMlbbP4"
405
+ },
406
+ "source": [
407
+ "## Task 4: Preparing Data!\n",
408
+ "\n",
409
+ "We'll start by loading some data from GitHub (Paul Graham's Essays) and then move to chunking them into manageable pieces!\n",
410
+ "\n",
411
+ "First - let's grab the repository where the files live."
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "code",
416
+ "execution_count": null,
417
+ "metadata": {
418
+ "colab": {
419
+ "base_uri": "https://localhost:8080/"
420
+ },
421
+ "id": "AkuzZben5Eqp",
422
+ "outputId": "eb8d39ae-fd70-4691-ddaa-1f8aa15f1c19"
423
+ },
424
+ "outputs": [
425
+ {
426
+ "name": "stdout",
427
+ "output_type": "stream",
428
+ "text": [
429
+ "Cloning into 'paul-graham-to-kindle'...\n",
430
+ "remote: Enumerating objects: 36, done.\u001b[K\n",
431
+ "remote: Counting objects: 100% (36/36), done.\u001b[K\n",
432
+ "remote: Compressing objects: 100% (33/33), done.\u001b[K\n",
433
+ "remote: Total 36 (delta 3), reused 31 (delta 1), pack-reused 0\u001b[K\n",
434
+ "Receiving objects: 100% (36/36), 2.35 MiB | 7.13 MiB/s, done.\n",
435
+ "Resolving deltas: 100% (3/3), done.\n"
436
+ ]
437
+ }
438
+ ],
439
+ "source": [
440
+ "!git clone https://github.com/dbredvick/paul-graham-to-kindle.git"
441
+ ]
442
+ },
443
+ {
444
+ "cell_type": "markdown",
445
+ "metadata": {
446
+ "id": "8prMk6R0bsYd"
447
+ },
448
+ "source": [
449
+ "Next - we can load them using LangChain!"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "code",
454
+ "execution_count": 106,
455
+ "metadata": {
456
+ "id": "K155zM7e53lt"
457
+ },
458
+ "outputs": [],
459
+ "source": [
460
+ "from langchain_community.document_loaders import TextLoader\n",
461
+ "\n",
462
+ "document_loader = TextLoader(\"./paul-graham-to-kindle/paul_graham_essays.txt\")\n",
463
+ "documents = document_loader.load()"
464
+ ]
465
+ },
466
+ {
467
+ "cell_type": "markdown",
468
+ "metadata": {
469
+ "id": "5wYfo6_0bwVc"
470
+ },
471
+ "source": [
472
+ "Now, let's split them into 1000 character pieces."
473
+ ]
474
+ },
475
+ {
476
+ "cell_type": "code",
477
+ "execution_count": 108,
478
+ "metadata": {
479
+ "colab": {
480
+ "base_uri": "https://localhost:8080/"
481
+ },
482
+ "id": "w-Gx_0iL6Ikc",
483
+ "outputId": "4cd1de4f-8a7d-4727-dc92-0ce3d321a82f"
484
+ },
485
+ "outputs": [
486
+ {
487
+ "data": {
488
+ "text/plain": [
489
+ "4265"
490
+ ]
491
+ },
492
+ "execution_count": 108,
493
+ "metadata": {},
494
+ "output_type": "execute_result"
495
+ }
496
+ ],
497
+ "source": [
498
+ "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
499
+ "\n",
500
+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)\n",
501
+ "split_documents = text_splitter.split_documents(documents)\n",
502
+ "len(split_documents)"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "markdown",
507
+ "metadata": {
508
+ "id": "d5HrkDhTb4i_"
509
+ },
510
+ "source": [
511
+ "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",
512
+ "\n",
513
+ "We'll need to take a few extra steps, though, due to a few limitations of the endpoint/FAISS.\n",
514
+ "\n",
515
+ "We'll start by embeddings our documents in batches of `32`.\n",
516
+ "\n",
517
+ "> NOTE: This process might take a while depending on the compute you assigned your embedding endpoint!"
518
+ ]
519
+ },
520
+ {
521
+ "cell_type": "code",
522
+ "execution_count": 110,
523
+ "metadata": {
524
+ "id": "ucghQgRp6YXr"
525
+ },
526
+ "outputs": [],
527
+ "source": [
528
+ "from langchain_community.vectorstores import FAISS\n",
529
+ "\n",
530
+ "for i in range(0, len(split_documents), 32):\n",
531
+ " if i == 0:\n",
532
+ " vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)\n",
533
+ " continue\n",
534
+ " vectorstore.add_documents(split_documents[i:i+32])"
535
+ ]
536
+ },
537
+ {
538
+ "cell_type": "markdown",
539
+ "metadata": {
540
+ "id": "q07ZUp6Db_AO"
541
+ },
542
+ "source": [
543
+ "Next, we set up FAISS as a retriever."
544
+ ]
545
+ },
546
+ {
547
+ "cell_type": "code",
548
+ "execution_count": 111,
549
+ "metadata": {
550
+ "id": "fXr-yrAq7h8V"
551
+ },
552
+ "outputs": [],
553
+ "source": [
554
+ "hf_retriever = vectorstore.as_retriever()"
555
+ ]
556
+ },
557
+ {
558
+ "cell_type": "markdown",
559
+ "metadata": {
560
+ "id": "sYrW6FRecO7U"
561
+ },
562
+ "source": [
563
+ "## Task 5: Simple LCEL RAG Chain\n",
564
+ "\n",
565
+ "Now we can set up our LCEL RAG chain!\n",
566
+ "\n",
567
+ "> NOTE: We're not returning context for this example, and only returning the text output from the LLM."
568
+ ]
569
+ },
570
+ {
571
+ "cell_type": "code",
572
+ "execution_count": 112,
573
+ "metadata": {
574
+ "id": "ffIzIlct8ISb"
575
+ },
576
+ "outputs": [],
577
+ "source": [
578
+ "from operator import itemgetter\n",
579
+ "from langchain.schema.output_parser import StrOutputParser\n",
580
+ "from langchain.schema.runnable import RunnablePassthrough\n",
581
+ "\n",
582
+ "lcel_rag_chain = {\"context\": itemgetter(\"query\") | hf_retriever, \"query\": itemgetter(\"query\")}| rag_prompt | hf_llm"
583
+ ]
584
+ },
585
+ {
586
+ "cell_type": "code",
587
+ "execution_count": 114,
588
+ "metadata": {
589
+ "colab": {
590
+ "base_uri": "https://localhost:8080/",
591
+ "height": 127
592
+ },
593
+ "id": "HOQfkEgb8nPH",
594
+ "outputId": "92601728-d001-43e2-e543-e714d66f4f4e"
595
+ },
596
+ "outputs": [
597
+ {
598
+ "data": {
599
+ "application/vnd.google.colaboratory.intrinsic+json": {
600
+ "type": "string"
601
+ },
602
+ "text/plain": [
603
+ "\"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 buildings, but the people who make it Silicon Valley.\\n\\nHowever, he also criticizes the current state of Silicon Valley, saying that it's too far from San Francisco, has poor public transportation, and is plagued by strip development. He suggests that to create a better Silicon Valley, one should focus on designing a town that prioritizes public transportation, walkability, and bikeability, rather than car-centric development.\\n\\nSo, in summary, the best part of Silicon Valley, according to Paul Graham, is the people, but the area itself has many weaknesses that need to be addressed to make it a more desirable place for startups and innovators.\""
604
+ ]
605
+ },
606
+ "execution_count": 114,
607
+ "metadata": {},
608
+ "output_type": "execute_result"
609
+ }
610
+ ],
611
+ "source": [
612
+ "lcel_rag_chain.invoke({\"query\" : \"What is the best part of Silicon Valley?\"})"
613
+ ]
614
+ }
615
+ ],
616
+ "metadata": {
617
+ "colab": {
618
+ "provenance": [],
619
+ "toc_visible": true
620
+ },
621
+ "kernelspec": {
622
+ "display_name": "Python 3",
623
+ "name": "python3"
624
+ },
625
+ "language_info": {
626
+ "codemirror_mode": {
627
+ "name": "ipython",
628
+ "version": 3
629
+ },
630
+ "file_extension": ".py",
631
+ "mimetype": "text/x-python",
632
+ "name": "python",
633
+ "nbconvert_exporter": "python",
634
+ "pygments_lexer": "ipython3",
635
+ "version": "3.11.9"
636
+ }
637
+ },
638
+ "nbformat": 4,
639
+ "nbformat_minor": 0
640
+ }
app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ text_loader =
43
+ documents =
44
+
45
+ ### 2. CREATE TEXT SPLITTER AND SPLIT DOCUMENTS
46
+ text_splitter =
47
+ split_documents =
48
+
49
+ ### 3. LOAD HUGGINGFACE EMBEDDINGS
50
+ hf_embeddings =
51
+
52
+ if os.path.exists("./data/vectorstore"):
53
+ vectorstore = FAISS.load_local(
54
+ "./data/vectorstore",
55
+ hf_embeddings,
56
+ allow_dangerous_deserialization=True # this is necessary to load the vectorstore from disk as it's stored as a `.pkl` file.
57
+ )
58
+ hf_retriever = vectorstore.as_retriever()
59
+ print("Loaded Vectorstore")
60
+ else:
61
+ print("Indexing Files")
62
+ os.makedirs("./data/vectorstore", exist_ok=True)
63
+ ### 4. INDEX FILES
64
+ ### NOTE: REMEMBER TO BATCH THE DOCUMENTS WITH MAXIMUM BATCH SIZE = 32
65
+
66
+ hf_retriever = vectorstore.as_retriever()
67
+
68
+ # -- AUGMENTED -- #
69
+ """
70
+ 1. Define a String Template
71
+ 2. Create a Prompt Template from the String Template
72
+ """
73
+ ### 1. DEFINE STRING TEMPLATE
74
+ RAG_PROMPT_TEMPLATE =
75
+
76
+ ### 2. CREATE PROMPT TEMPLATE
77
+ rag_prompt =
78
+
79
+ # -- GENERATION -- #
80
+ """
81
+ 1. Create a HuggingFaceEndpoint for the LLM
82
+ """
83
+ ### 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
84
+ hf_llm =
85
+
86
+ @cl.author_rename
87
+ def rename(original_author: str):
88
+ """
89
+ This function can be used to rename the 'author' of a message.
90
+
91
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
92
+ """
93
+ rename_dict = {
94
+ "Assistant" : "Paul Graham Essay Bot"
95
+ }
96
+ return rename_dict.get(original_author, original_author)
97
+
98
+ @cl.on_chat_start
99
+ async def start_chat():
100
+ """
101
+ This function will be called at the start of every user session.
102
+
103
+ We will build our LCEL RAG chain here, and store it in the user session.
104
+
105
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
106
+ """
107
+
108
+ ### BUILD LCEL RAG CHAIN THAT ONLY RETURNS TEXT
109
+ lcel_rag_chain =
110
+
111
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
112
+
113
+ @cl.on_message
114
+ async def main(message: cl.Message):
115
+ """
116
+ This function will be called every time a message is recieved from a session.
117
+
118
+ We will use the LCEL RAG chain to generate a response to the user query.
119
+
120
+ 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.
121
+ """
122
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
123
+
124
+ msg = cl.Message(content="")
125
+
126
+ async for chunk in lcel_rag_chain.astream(
127
+ {"query": message.content},
128
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
129
+ ):
130
+ await msg.stream_token(chunk)
131
+
132
+ await msg.send()
chainlit.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # FILL OUT YOUR CHAINLIT MD HERE WITH A DESCRIPTION OF YOUR APPLICATION
data/paul_graham_essays.txt ADDED
The diff for this file is too large to render. See raw diff
 
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
solution_app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ document_loader = TextLoader("./data/paul_graham_essays.txt")
41
+ documents = document_loader.load()
42
+
43
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
44
+ split_documents = text_splitter.split_documents(documents)
45
+
46
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
47
+ model=HF_EMBED_ENDPOINT,
48
+ task="feature-extraction",
49
+ huggingfacehub_api_token=HF_TOKEN,
50
+ )
51
+
52
+ if os.path.exists("./data/vectorstore"):
53
+ vectorstore = FAISS.load_local(
54
+ "./data/vectorstore",
55
+ hf_embeddings,
56
+ allow_dangerous_deserialization=True # this is necessary to load the vectorstore from disk as it's stored as a `.pkl` file.
57
+ )
58
+ hf_retriever = vectorstore.as_retriever()
59
+ print("Loaded Vectorstore")
60
+ else:
61
+ print("Indexing Files")
62
+ os.makedirs("./data/vectorstore", exist_ok=True)
63
+ for i in range(0, len(split_documents), 32):
64
+ if i == 0:
65
+ vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)
66
+ continue
67
+ vectorstore.add_documents(split_documents[i:i+32])
68
+ vectorstore.save_local("./data/vectorstore")
69
+
70
+ hf_retriever = vectorstore.as_retriever()
71
+
72
+ # -- AUGMENTED -- #
73
+ """
74
+ 1. Define a String Template
75
+ 2. Create a Prompt Template from the String Template
76
+ """
77
+ RAG_PROMPT_TEMPLATE = """\
78
+ <|start_header_id|>system<|end_header_id|>
79
+ 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|>
80
+
81
+ <|start_header_id|>user<|end_header_id|>
82
+ User Query:
83
+ {query}
84
+
85
+ Context:
86
+ {context}<|eot_id|>
87
+
88
+ <|start_header_id|>assistant<|end_header_id|>
89
+ """
90
+
91
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
92
+
93
+ # -- GENERATION -- #
94
+ """
95
+ 1. Create a HuggingFaceEndpoint for the LLM
96
+ """
97
+ hf_llm = HuggingFaceEndpoint(
98
+ endpoint_url=HF_LLM_ENDPOINT,
99
+ max_new_tokens=512,
100
+ top_k=10,
101
+ top_p=0.95,
102
+ temperature=0.3,
103
+ repetition_penalty=1.15,
104
+ huggingfacehub_api_token=HF_TOKEN,
105
+ )
106
+
107
+ @cl.author_rename
108
+ def rename(original_author: str):
109
+ """
110
+ This function can be used to rename the 'author' of a message.
111
+
112
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
113
+ """
114
+ rename_dict = {
115
+ "Assistant" : "Paul Graham Essay Bot"
116
+ }
117
+ return rename_dict.get(original_author, original_author)
118
+
119
+ @cl.on_chat_start
120
+ async def start_chat():
121
+ """
122
+ This function will be called at the start of every user session.
123
+
124
+ We will build our LCEL RAG chain here, and store it in the user session.
125
+
126
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
127
+ """
128
+
129
+ lcel_rag_chain = (
130
+ {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
131
+ | rag_prompt | hf_llm
132
+ )
133
+
134
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
135
+
136
+ @cl.on_message
137
+ async def main(message: cl.Message):
138
+ """
139
+ This function will be called every time a message is recieved from a session.
140
+
141
+ We will use the LCEL RAG chain to generate a response to the user query.
142
+
143
+ 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.
144
+ """
145
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
146
+
147
+ msg = cl.Message(content="")
148
+
149
+ for chunk in await cl.make_async(lcel_rag_chain.stream)(
150
+ {"query": message.content},
151
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
152
+ ):
153
+ await msg.stream_token(chunk)
154
+
155
+ await msg.send()