pdudka commited on
Commit
4322722
·
1 Parent(s): 1793c65

initial commit to space

Browse files
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ .chainlit
4
+ *.faiss
5
+ *.pkl
6
+ .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
+ "source": [
44
+ "!pip install -qU langchain-huggingface langchain-community faiss-cpu"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "markdown",
49
+ "metadata": {
50
+ "id": "SpZTBLwK3TIz"
51
+ },
52
+ "source": [
53
+ "## Task 2: Set Environment Variables\n",
54
+ "\n",
55
+ "We'll need to set our `HF_TOKEN` so that we can send requests to our protected API endpoint.\n",
56
+ "\n",
57
+ "We'll also set-up our OpenAI API key, which we'll leverage later.\n",
58
+ "\n"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": 2,
64
+ "metadata": {
65
+ "colab": {
66
+ "base_uri": "https://localhost:8080/"
67
+ },
68
+ "id": "NspG8I0XlFTt",
69
+ "outputId": "edbf992c-97c0-46b1-9b69-40651a5e60d1"
70
+ },
71
+ "outputs": [],
72
+ "source": [
73
+ "import os\n",
74
+ "import getpass\n",
75
+ "\n",
76
+ "os.environ[\"HF_TOKEN\"] = getpass.getpass(\"HuggingFace Write Token: \")"
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "markdown",
81
+ "metadata": {
82
+ "id": "QMru14VBZAtw"
83
+ },
84
+ "source": [
85
+ "## Task 3: Creating LangChain components powered by the endpoints\n",
86
+ "\n",
87
+ "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!"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "markdown",
92
+ "metadata": {
93
+ "id": "TGooehdzcmPb"
94
+ },
95
+ "source": [
96
+ "### HuggingFaceEndpoint for LLM\n",
97
+ "\n",
98
+ "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."
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": 3,
104
+ "metadata": {
105
+ "id": "N7u2Tu1FsURh"
106
+ },
107
+ "outputs": [],
108
+ "source": [
109
+ "YOUR_LLM_ENDPOINT_URL = \"https://d6rdp1b523dug7h4.us-east-1.aws.endpoints.huggingface.cloud\""
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "execution_count": 4,
115
+ "metadata": {
116
+ "colab": {
117
+ "base_uri": "https://localhost:8080/"
118
+ },
119
+ "id": "L3Cz6Mrnt2ku",
120
+ "outputId": "f23f611f-5f08-4332-a74c-5b8d8311d185"
121
+ },
122
+ "outputs": [
123
+ {
124
+ "name": "stdout",
125
+ "output_type": "stream",
126
+ "text": [
127
+ "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",
128
+ "Token is valid (permission: write).\n",
129
+ "Your token has been saved to /Users/peterdudka/.cache/huggingface/token\n",
130
+ "Login successful\n"
131
+ ]
132
+ },
133
+ {
134
+ "name": "stderr",
135
+ "output_type": "stream",
136
+ "text": [
137
+ "/opt/miniconda3/lib/python3.12/site-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",
138
+ " warn_deprecated(\n"
139
+ ]
140
+ }
141
+ ],
142
+ "source": [
143
+ "from langchain_community.llms import HuggingFaceEndpoint\n",
144
+ "\n",
145
+ "hf_llm = HuggingFaceEndpoint(\n",
146
+ " endpoint_url=f\"{YOUR_LLM_ENDPOINT_URL}\",\n",
147
+ " max_new_tokens=512,\n",
148
+ " top_k=10,\n",
149
+ " top_p=0.95,\n",
150
+ " typical_p=0.95,\n",
151
+ " temperature=0.01,\n",
152
+ " repetition_penalty=1.03,\n",
153
+ " huggingfacehub_api_token=os.environ[\"HF_TOKEN\"]\n",
154
+ ")"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "markdown",
159
+ "metadata": {
160
+ "id": "fun4XrRxZK9n"
161
+ },
162
+ "source": [
163
+ "Now we can use our endpoint like we would any other LLM!"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": 6,
169
+ "metadata": {
170
+ "colab": {
171
+ "base_uri": "https://localhost:8080/",
172
+ "height": 127
173
+ },
174
+ "id": "OFAbFT91Z8QV",
175
+ "outputId": "588714ad-da28-4330-801b-7121b6f17ccf"
176
+ },
177
+ "outputs": [
178
+ {
179
+ "data": {
180
+ "text/plain": [
181
+ "\" Here it's a haiku about the heat:\\n\\nSummer sun beats down\\nHeat waves shimmer on the road\\nSweat drips from my brow\\n\\nI hope you like it! Let me know if you have any other requests.\""
182
+ ]
183
+ },
184
+ "execution_count": 6,
185
+ "metadata": {},
186
+ "output_type": "execute_result"
187
+ }
188
+ ],
189
+ "source": [
190
+ "hf_llm.invoke(\"Please write me a haiku about summer weather.\")"
191
+ ]
192
+ },
193
+ {
194
+ "cell_type": "markdown",
195
+ "metadata": {
196
+ "id": "ngH3fhw4aQ8T"
197
+ },
198
+ "source": [
199
+ "Now we can add a RAG-style prompt using Llama 3 Instruct's prompt templating!"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "execution_count": 7,
205
+ "metadata": {
206
+ "id": "zdvv4JmkzEtj"
207
+ },
208
+ "outputs": [],
209
+ "source": [
210
+ "from langchain_core.prompts import PromptTemplate\n",
211
+ "\n",
212
+ "RAG_PROMPT_TEMPLATE = \"\"\"\\\n",
213
+ "<|start_header_id|>system<|end_header_id|>\n",
214
+ "You are a helpful assistant. You answer user questions based on ONLY provided context. If you can't answer the question with the provided context, say you don't know.<|eot_id|>\n",
215
+ "\n",
216
+ "<|start_header_id|>user<|end_header_id|>\n",
217
+ "User Query:\n",
218
+ "{query}\n",
219
+ "\n",
220
+ "Context:\n",
221
+ "{context}<|eot_id|>\n",
222
+ "\n",
223
+ "<|start_header_id|>assistant<|end_header_id|>\n",
224
+ "\"\"\"\n",
225
+ "\n",
226
+ "rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)"
227
+ ]
228
+ },
229
+ {
230
+ "cell_type": "markdown",
231
+ "metadata": {
232
+ "id": "Oe0Qrzn4adzh"
233
+ },
234
+ "source": [
235
+ "Let's create a simple LCEL chain using our prompt template Runnable and our LLM Runnable."
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": 8,
241
+ "metadata": {
242
+ "id": "CE4djpxM0-Fg"
243
+ },
244
+ "outputs": [],
245
+ "source": [
246
+ "rag_chain = rag_prompt | hf_llm"
247
+ ]
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "execution_count": 11,
252
+ "metadata": {
253
+ "colab": {
254
+ "base_uri": "https://localhost:8080/",
255
+ "height": 36
256
+ },
257
+ "id": "PNwrLXqDxHDY",
258
+ "outputId": "f6803286-1aa5-488a-eea9-8bece68da7f5"
259
+ },
260
+ "outputs": [
261
+ {
262
+ "data": {
263
+ "text/plain": [
264
+ "'According to the context, Carl is 55 years old.'"
265
+ ]
266
+ },
267
+ "execution_count": 11,
268
+ "metadata": {},
269
+ "output_type": "execute_result"
270
+ }
271
+ ],
272
+ "source": [
273
+ "rag_chain.invoke({\"query\" : \"How old is Carl?\", \"context\" : \"Carl is a sweet dude, he's 55 years old.\"})"
274
+ ]
275
+ },
276
+ {
277
+ "cell_type": "markdown",
278
+ "metadata": {
279
+ "id": "emGw4-66aBfa"
280
+ },
281
+ "source": [
282
+ "### HuggingFaceInferenceAPIEmbeddings\n",
283
+ "\n",
284
+ "Now we can leverage the `HuggingFaceInferenceAPIEmbeddings` module in LangChain to connect to our Hugging Face Inference Endpoint hosted embedding model."
285
+ ]
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "execution_count": 12,
290
+ "metadata": {
291
+ "id": "n9Q7e4Gnwe_C"
292
+ },
293
+ "outputs": [],
294
+ "source": [
295
+ "from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddings\n",
296
+ "\n",
297
+ "YOUR_EMBED_MODEL_URL = \"https://ns3ko0o35gmvmwe1.us-east-1.aws.endpoints.huggingface.cloud\"\n",
298
+ "\n",
299
+ "hf_embeddings = HuggingFaceEndpointEmbeddings(\n",
300
+ " model=YOUR_EMBED_MODEL_URL,\n",
301
+ " task=\"feature-extraction\",\n",
302
+ " huggingfacehub_api_token=os.environ[\"HF_TOKEN\"],\n",
303
+ ")"
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "markdown",
308
+ "metadata": {
309
+ "id": "YXYRBqbBayWb"
310
+ },
311
+ "source": [
312
+ "Let's build a simple cosine-similarity function to verify our endpoint is working as expected."
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "code",
317
+ "execution_count": 13,
318
+ "metadata": {
319
+ "id": "lOP6LKr74RG8"
320
+ },
321
+ "outputs": [],
322
+ "source": [
323
+ "import numpy as np\n",
324
+ "from numpy.linalg import norm\n",
325
+ "\n",
326
+ "def cosine_similarity(phrase_1, phrase_2):\n",
327
+ " vec_1 = hf_embeddings.embed_documents([phrase_1])[0]\n",
328
+ " vec2_2 = hf_embeddings.embed_documents([phrase_2])[0]\n",
329
+ " return np.dot(vec_1, vec2_2) / (norm(vec_1) * norm(vec2_2))"
330
+ ]
331
+ },
332
+ {
333
+ "cell_type": "markdown",
334
+ "metadata": {
335
+ "id": "uGZNhxF2bVIr"
336
+ },
337
+ "source": [
338
+ "Let's try a few examples below!"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "code",
343
+ "execution_count": 16,
344
+ "metadata": {
345
+ "colab": {
346
+ "base_uri": "https://localhost:8080/"
347
+ },
348
+ "id": "5o_cqEZ34f15",
349
+ "outputId": "d3eb4933-8842-4278-fe48-2dc15e430b60"
350
+ },
351
+ "outputs": [
352
+ {
353
+ "data": {
354
+ "text/plain": [
355
+ "0.814863333653546"
356
+ ]
357
+ },
358
+ "execution_count": 16,
359
+ "metadata": {},
360
+ "output_type": "execute_result"
361
+ }
362
+ ],
363
+ "source": [
364
+ "cosine_similarity(\"I love my fluffy dog!\", \"My sister dislikes this furry kitten!\")"
365
+ ]
366
+ },
367
+ {
368
+ "cell_type": "code",
369
+ "execution_count": 18,
370
+ "metadata": {
371
+ "colab": {
372
+ "base_uri": "https://localhost:8080/"
373
+ },
374
+ "id": "R1nsAV1n4w4a",
375
+ "outputId": "db53d783-4c87-404f-de67-fc1d01583e68"
376
+ },
377
+ "outputs": [
378
+ {
379
+ "data": {
380
+ "text/plain": [
381
+ "0.8209848870098087"
382
+ ]
383
+ },
384
+ "execution_count": 18,
385
+ "metadata": {},
386
+ "output_type": "execute_result"
387
+ }
388
+ ],
389
+ "source": [
390
+ "cosine_similarity(\"I like to eat pasta!\", \"Eating pizza is the worst! Yuck!\")"
391
+ ]
392
+ },
393
+ {
394
+ "cell_type": "markdown",
395
+ "metadata": {
396
+ "id": "iiz6vKMlbbP4"
397
+ },
398
+ "source": [
399
+ "## Task 4: Preparing Data!\n",
400
+ "\n",
401
+ "We'll start by loading some data from GitHub (Paul Graham's Essays) and then move to chunking them into manageable pieces!\n",
402
+ "\n",
403
+ "First - let's grab the repository where the files live."
404
+ ]
405
+ },
406
+ {
407
+ "cell_type": "code",
408
+ "execution_count": 19,
409
+ "metadata": {
410
+ "colab": {
411
+ "base_uri": "https://localhost:8080/"
412
+ },
413
+ "id": "AkuzZben5Eqp",
414
+ "outputId": "eb8d39ae-fd70-4691-ddaa-1f8aa15f1c19"
415
+ },
416
+ "outputs": [
417
+ {
418
+ "name": "stdout",
419
+ "output_type": "stream",
420
+ "text": [
421
+ "Cloning into 'paul-graham-to-kindle'...\n",
422
+ "remote: Enumerating objects: 36, done.\u001b[K\n",
423
+ "remote: Counting objects: 100% (36/36), done.\u001b[K(24/36)\u001b[K\n",
424
+ "remote: Compressing objects: 100% (33/33), done.\u001b[K\n",
425
+ "remote: Total 36 (delta 3), reused 31 (delta 1), pack-reused 0\u001b[K\n",
426
+ "Receiving objects: 100% (36/36), 2.35 MiB | 39.38 MiB/s, done.\n",
427
+ "Resolving deltas: 100% (3/3), done.\n"
428
+ ]
429
+ }
430
+ ],
431
+ "source": [
432
+ "!git clone https://github.com/dbredvick/paul-graham-to-kindle.git"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "markdown",
437
+ "metadata": {
438
+ "id": "8prMk6R0bsYd"
439
+ },
440
+ "source": [
441
+ "Next - we can load them using LangChain!"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "execution_count": 20,
447
+ "metadata": {
448
+ "id": "K155zM7e53lt"
449
+ },
450
+ "outputs": [],
451
+ "source": [
452
+ "from langchain_community.document_loaders import TextLoader\n",
453
+ "\n",
454
+ "document_loader = TextLoader(\"./paul-graham-to-kindle/paul_graham_essays.txt\")\n",
455
+ "documents = document_loader.load()"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "markdown",
460
+ "metadata": {
461
+ "id": "5wYfo6_0bwVc"
462
+ },
463
+ "source": [
464
+ "Now, let's split them into 1000 character pieces."
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "code",
469
+ "execution_count": 21,
470
+ "metadata": {
471
+ "colab": {
472
+ "base_uri": "https://localhost:8080/"
473
+ },
474
+ "id": "w-Gx_0iL6Ikc",
475
+ "outputId": "4cd1de4f-8a7d-4727-dc92-0ce3d321a82f"
476
+ },
477
+ "outputs": [
478
+ {
479
+ "data": {
480
+ "text/plain": [
481
+ "4265"
482
+ ]
483
+ },
484
+ "execution_count": 21,
485
+ "metadata": {},
486
+ "output_type": "execute_result"
487
+ }
488
+ ],
489
+ "source": [
490
+ "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
491
+ "\n",
492
+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)\n",
493
+ "split_documents = text_splitter.split_documents(documents)\n",
494
+ "len(split_documents)"
495
+ ]
496
+ },
497
+ {
498
+ "cell_type": "markdown",
499
+ "metadata": {
500
+ "id": "d5HrkDhTb4i_"
501
+ },
502
+ "source": [
503
+ "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",
504
+ "\n",
505
+ "We'll need to take a few extra steps, though, due to a few limitations of the endpoint/FAISS.\n",
506
+ "\n",
507
+ "We'll start by embeddings our documents in batches of `32`.\n",
508
+ "\n",
509
+ "> NOTE: This process might take a while depending on the compute you assigned your embedding endpoint!"
510
+ ]
511
+ },
512
+ {
513
+ "cell_type": "code",
514
+ "execution_count": 25,
515
+ "metadata": {
516
+ "id": "ucghQgRp6YXr"
517
+ },
518
+ "outputs": [
519
+ {
520
+ "name": "stdout",
521
+ "output_type": "stream",
522
+ "text": [
523
+ "Still embedding, one moment please...\n",
524
+ "Embedding complete!\n"
525
+ ]
526
+ }
527
+ ],
528
+ "source": [
529
+ "from langchain_community.vectorstores import FAISS\n",
530
+ "\n",
531
+ "for i in range(0, len(split_documents), 32):\n",
532
+ " if i == 0:\n",
533
+ " vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)\n",
534
+ " print(\"Still embedding, one moment please...\")\n",
535
+ " continue\n",
536
+ " vectorstore.add_documents(split_documents[i:i+32])\n",
537
+ "print(\"Embedding complete!\")"
538
+ ]
539
+ },
540
+ {
541
+ "cell_type": "markdown",
542
+ "metadata": {
543
+ "id": "q07ZUp6Db_AO"
544
+ },
545
+ "source": [
546
+ "Next, we set up FAISS as a retriever."
547
+ ]
548
+ },
549
+ {
550
+ "cell_type": "code",
551
+ "execution_count": 26,
552
+ "metadata": {
553
+ "id": "fXr-yrAq7h8V"
554
+ },
555
+ "outputs": [],
556
+ "source": [
557
+ "hf_retriever = vectorstore.as_retriever()"
558
+ ]
559
+ },
560
+ {
561
+ "cell_type": "markdown",
562
+ "metadata": {
563
+ "id": "sYrW6FRecO7U"
564
+ },
565
+ "source": [
566
+ "## Task 5: Simple LCEL RAG Chain\n",
567
+ "\n",
568
+ "Now we can set up our LCEL RAG chain!\n",
569
+ "\n",
570
+ "> NOTE: We're not returning context for this example, and only returning the text output from the LLM."
571
+ ]
572
+ },
573
+ {
574
+ "cell_type": "code",
575
+ "execution_count": 27,
576
+ "metadata": {
577
+ "id": "ffIzIlct8ISb"
578
+ },
579
+ "outputs": [],
580
+ "source": [
581
+ "from operator import itemgetter\n",
582
+ "from langchain.schema.output_parser import StrOutputParser\n",
583
+ "from langchain.schema.runnable import RunnablePassthrough\n",
584
+ "\n",
585
+ "lcel_rag_chain = {\"context\": itemgetter(\"query\") | hf_retriever, \"query\": itemgetter(\"query\")}| rag_prompt | hf_llm"
586
+ ]
587
+ },
588
+ {
589
+ "cell_type": "code",
590
+ "execution_count": 28,
591
+ "metadata": {
592
+ "colab": {
593
+ "base_uri": "https://localhost:8080/",
594
+ "height": 127
595
+ },
596
+ "id": "HOQfkEgb8nPH",
597
+ "outputId": "92601728-d001-43e2-e543-e714d66f4f4e"
598
+ },
599
+ "outputs": [
600
+ {
601
+ "data": {
602
+ "text/plain": [
603
+ "'Based on the provided context, it seems that the author, Paul Graham, does not think that the best part of Silicon Valley is its physical location or buildings. He mentions that the area is \"not so bad\" and that Palo Alto is not bad, but everything built since is \"the worst sort of strip development\". He also notes that the area is too far from San Francisco, which is an \"interesting city\".\\n\\nInstead, Paul Graham suggests that the best part of Silicon Valley is the people who live and work there, particularly the startups and entrepreneurs who are drawn to the area. He emphasizes that the key stage in the life of a startup is when it\\'s just a few people operating out of an apartment, and that the defining quality of Silicon Valley is that many successful startups were started there.\\n\\nTherefore, the best part of Silicon Valley, according to Paul Graham, is the community of entrepreneurs and startups that it fosters.'"
604
+ ]
605
+ },
606
+ "execution_count": 28,
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.12.3"
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()