Spaces:
Runtime error
Runtime error
Mikiko Bazeley
commited on
Commit
•
b705660
1
Parent(s):
8f8d49c
Completed the HF space
Browse files- .env.sample +5 -0
- .gitignore +6 -0
- Dockerfile +11 -0
- [Completed] BazeleyMikiko_Open_Source_RAG_Leveraging_Hugging_Face_Endpoints_through_LangChain.ipynb +669 -0
- app.py +163 -0
- chainlit.md +1 -0
- data/paul_graham_essays.txt +0 -0
- requirements.txt +8 -0
- solution_app.py +155 -0
.env.sample
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# !!! DO NOT UPDATE THIS FILE DIRECTLY. MAKE A COPY AND RENAME IT `.env` TO PROCEED !!! #
|
2 |
+
HF_LLM_ENDPOINT="YOUR_LLM_ENDPOINT_URL_HERE"
|
3 |
+
HF_EMBED_ENDPOINT="YOUR_EMBED_MODEL_ENDPOINT_URL_HERE"
|
4 |
+
HF_TOKEN="YOUR_HF_TOKEN_HERE"
|
5 |
+
# !!! DO NOT UPDATE THIS FILE DIRECTLY. MAKE A COPY AND RENAME IT `.env` TO PROCEED !!! #
|
.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"]
|
[Completed] BazeleyMikiko_Open_Source_RAG_Leveraging_Hugging_Face_Endpoints_through_LangChain.ipynb
ADDED
@@ -0,0 +1,669 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"nbformat": 4,
|
3 |
+
"nbformat_minor": 0,
|
4 |
+
"metadata": {
|
5 |
+
"colab": {
|
6 |
+
"provenance": []
|
7 |
+
},
|
8 |
+
"kernelspec": {
|
9 |
+
"name": "python3",
|
10 |
+
"display_name": "Python 3"
|
11 |
+
},
|
12 |
+
"language_info": {
|
13 |
+
"name": "python"
|
14 |
+
}
|
15 |
+
},
|
16 |
+
"cells": [
|
17 |
+
{
|
18 |
+
"cell_type": "markdown",
|
19 |
+
"source": [
|
20 |
+
"# Open Source RAG - Leveraging Hugging Face Endpoints through LangChain\n",
|
21 |
+
"\n",
|
22 |
+
"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",
|
23 |
+
"\n",
|
24 |
+
"The notebook will be broken into the following parts:\n",
|
25 |
+
"\n",
|
26 |
+
"- 🤝 Breakout Room #2:\n",
|
27 |
+
" 1. Install required libraries\n",
|
28 |
+
" 2. Set Environment Variables\n",
|
29 |
+
" 3. Creating LangChain components powered by the endpoints\n",
|
30 |
+
" 4. Preparing Data!\n",
|
31 |
+
" 5. Simple LCEL RAG Chain"
|
32 |
+
],
|
33 |
+
"metadata": {
|
34 |
+
"id": "lcW6UWldWUMp"
|
35 |
+
}
|
36 |
+
},
|
37 |
+
{
|
38 |
+
"cell_type": "markdown",
|
39 |
+
"source": [
|
40 |
+
"## Task 1: Install required libraries\n",
|
41 |
+
"\n",
|
42 |
+
"Now we've got to get our required libraries!\n",
|
43 |
+
"\n",
|
44 |
+
"We'll start with our `langchain` and `huggingface` dependencies.\n",
|
45 |
+
"\n"
|
46 |
+
],
|
47 |
+
"metadata": {
|
48 |
+
"id": "-spIWt2J3Quk"
|
49 |
+
}
|
50 |
+
},
|
51 |
+
{
|
52 |
+
"cell_type": "code",
|
53 |
+
"source": [
|
54 |
+
"!pip install -qU langchain-huggingface langchain-community faiss-cpu"
|
55 |
+
],
|
56 |
+
"metadata": {
|
57 |
+
"id": "EwGLnp31jXJj",
|
58 |
+
"outputId": "2b3d0cf7-5e88-4a91-c759-d6efb8f0fa5f",
|
59 |
+
"colab": {
|
60 |
+
"base_uri": "https://localhost:8080/"
|
61 |
+
}
|
62 |
+
},
|
63 |
+
"execution_count": 1,
|
64 |
+
"outputs": [
|
65 |
+
{
|
66 |
+
"output_type": "stream",
|
67 |
+
"name": "stdout",
|
68 |
+
"text": [
|
69 |
+
"\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",
|
70 |
+
"\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",
|
71 |
+
"\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",
|
72 |
+
"\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",
|
73 |
+
"\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",
|
74 |
+
"\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",
|
75 |
+
"\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",
|
76 |
+
"\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",
|
77 |
+
"\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",
|
78 |
+
"\u001b[?25h"
|
79 |
+
]
|
80 |
+
}
|
81 |
+
]
|
82 |
+
},
|
83 |
+
{
|
84 |
+
"cell_type": "markdown",
|
85 |
+
"source": [
|
86 |
+
"## Task 2: Set Environment Variables\n",
|
87 |
+
"\n",
|
88 |
+
"We'll need to set our `HF_TOKEN` so that we can send requests to our protected API endpoint.\n",
|
89 |
+
"\n",
|
90 |
+
"We'll also set-up our OpenAI API key, which we'll leverage later.\n",
|
91 |
+
"\n"
|
92 |
+
],
|
93 |
+
"metadata": {
|
94 |
+
"id": "SpZTBLwK3TIz"
|
95 |
+
}
|
96 |
+
},
|
97 |
+
{
|
98 |
+
"cell_type": "code",
|
99 |
+
"source": [
|
100 |
+
"import os\n",
|
101 |
+
"import getpass\n",
|
102 |
+
"\n",
|
103 |
+
"os.environ[\"HF_TOKEN\"] = getpass.getpass(\"HuggingFace Write Token: \")"
|
104 |
+
],
|
105 |
+
"metadata": {
|
106 |
+
"id": "NspG8I0XlFTt",
|
107 |
+
"colab": {
|
108 |
+
"base_uri": "https://localhost:8080/"
|
109 |
+
},
|
110 |
+
"outputId": "6f9d52c8-956e-4d74-c9c8-34cefd9eec38"
|
111 |
+
},
|
112 |
+
"execution_count": 2,
|
113 |
+
"outputs": [
|
114 |
+
{
|
115 |
+
"name": "stdout",
|
116 |
+
"output_type": "stream",
|
117 |
+
"text": [
|
118 |
+
"HuggingFace Write Token: ··········\n"
|
119 |
+
]
|
120 |
+
}
|
121 |
+
]
|
122 |
+
},
|
123 |
+
{
|
124 |
+
"cell_type": "markdown",
|
125 |
+
"source": [
|
126 |
+
"## Task 3: Creating LangChain components powered by the endpoints\n",
|
127 |
+
"\n",
|
128 |
+
"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!"
|
129 |
+
],
|
130 |
+
"metadata": {
|
131 |
+
"id": "QMru14VBZAtw"
|
132 |
+
}
|
133 |
+
},
|
134 |
+
{
|
135 |
+
"cell_type": "markdown",
|
136 |
+
"source": [
|
137 |
+
"### HuggingFaceEndpoint for LLM\n",
|
138 |
+
"\n",
|
139 |
+
"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."
|
140 |
+
],
|
141 |
+
"metadata": {
|
142 |
+
"id": "TGooehdzcmPb"
|
143 |
+
}
|
144 |
+
},
|
145 |
+
{
|
146 |
+
"cell_type": "code",
|
147 |
+
"source": [
|
148 |
+
"YOUR_LLM_ENDPOINT_URL = \"https://m073nfu1n12yxzwo.us-east-1.aws.endpoints.huggingface.cloud\""
|
149 |
+
],
|
150 |
+
"metadata": {
|
151 |
+
"id": "N7u2Tu1FsURh"
|
152 |
+
},
|
153 |
+
"execution_count": 3,
|
154 |
+
"outputs": []
|
155 |
+
},
|
156 |
+
{
|
157 |
+
"cell_type": "code",
|
158 |
+
"source": [
|
159 |
+
"from langchain_community.llms import HuggingFaceEndpoint\n",
|
160 |
+
"\n",
|
161 |
+
"hf_llm = HuggingFaceEndpoint(\n",
|
162 |
+
" endpoint_url=f\"{YOUR_LLM_ENDPOINT_URL}\",\n",
|
163 |
+
" max_new_tokens=512,\n",
|
164 |
+
" top_k=10,\n",
|
165 |
+
" top_p=0.95,\n",
|
166 |
+
" typical_p=0.95,\n",
|
167 |
+
" temperature=0.01,\n",
|
168 |
+
" repetition_penalty=1.03,\n",
|
169 |
+
" huggingfacehub_api_token=os.environ[\"HF_TOKEN\"]\n",
|
170 |
+
")"
|
171 |
+
],
|
172 |
+
"metadata": {
|
173 |
+
"colab": {
|
174 |
+
"base_uri": "https://localhost:8080/"
|
175 |
+
},
|
176 |
+
"id": "L3Cz6Mrnt2ku",
|
177 |
+
"outputId": "28429c66-e2c7-44f7-f452-ad6e44d93b4c"
|
178 |
+
},
|
179 |
+
"execution_count": 4,
|
180 |
+
"outputs": [
|
181 |
+
{
|
182 |
+
"output_type": "stream",
|
183 |
+
"name": "stderr",
|
184 |
+
"text": [
|
185 |
+
"/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",
|
186 |
+
" warn_deprecated(\n"
|
187 |
+
]
|
188 |
+
},
|
189 |
+
{
|
190 |
+
"output_type": "stream",
|
191 |
+
"name": "stdout",
|
192 |
+
"text": [
|
193 |
+
"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",
|
194 |
+
"Token is valid (permission: write).\n",
|
195 |
+
"Your token has been saved to /root/.cache/huggingface/token\n",
|
196 |
+
"Login successful\n"
|
197 |
+
]
|
198 |
+
}
|
199 |
+
]
|
200 |
+
},
|
201 |
+
{
|
202 |
+
"cell_type": "markdown",
|
203 |
+
"source": [
|
204 |
+
"Now we can use our endpoint like we would any other LLM!"
|
205 |
+
],
|
206 |
+
"metadata": {
|
207 |
+
"id": "fun4XrRxZK9n"
|
208 |
+
}
|
209 |
+
},
|
210 |
+
{
|
211 |
+
"cell_type": "code",
|
212 |
+
"source": [
|
213 |
+
"hf_llm.invoke(\"Hello, how are you?\")"
|
214 |
+
],
|
215 |
+
"metadata": {
|
216 |
+
"colab": {
|
217 |
+
"base_uri": "https://localhost:8080/",
|
218 |
+
"height": 105
|
219 |
+
},
|
220 |
+
"id": "OFAbFT91Z8QV",
|
221 |
+
"outputId": "af2e633c-3c57-4cae-b6b8-87cdf049dd0d"
|
222 |
+
},
|
223 |
+
"execution_count": 5,
|
224 |
+
"outputs": [
|
225 |
+
{
|
226 |
+
"output_type": "execute_result",
|
227 |
+
"data": {
|
228 |
+
"text/plain": [
|
229 |
+
"\" 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!\""
|
230 |
+
],
|
231 |
+
"application/vnd.google.colaboratory.intrinsic+json": {
|
232 |
+
"type": "string"
|
233 |
+
}
|
234 |
+
},
|
235 |
+
"metadata": {},
|
236 |
+
"execution_count": 5
|
237 |
+
}
|
238 |
+
]
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"cell_type": "markdown",
|
242 |
+
"source": [
|
243 |
+
"Now we can add a RAG-style prompt using Llama 3 Instruct's prompt templating!"
|
244 |
+
],
|
245 |
+
"metadata": {
|
246 |
+
"id": "ngH3fhw4aQ8T"
|
247 |
+
}
|
248 |
+
},
|
249 |
+
{
|
250 |
+
"cell_type": "code",
|
251 |
+
"source": [
|
252 |
+
"from langchain_core.prompts import PromptTemplate\n",
|
253 |
+
"\n",
|
254 |
+
"RAG_PROMPT_TEMPLATE = \"\"\"\\\n",
|
255 |
+
"<|start_header_id|>system<|end_header_id|>\n",
|
256 |
+
"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",
|
257 |
+
"\n",
|
258 |
+
"<|start_header_id|>user<|end_header_id|>\n",
|
259 |
+
"User Query:\n",
|
260 |
+
"{query}\n",
|
261 |
+
"\n",
|
262 |
+
"Context:\n",
|
263 |
+
"{context}<|eot_id|>\n",
|
264 |
+
"\n",
|
265 |
+
"<|start_header_id|>assistant<|end_header_id|>\n",
|
266 |
+
"\"\"\"\n",
|
267 |
+
"\n",
|
268 |
+
"rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)"
|
269 |
+
],
|
270 |
+
"metadata": {
|
271 |
+
"id": "zdvv4JmkzEtj"
|
272 |
+
},
|
273 |
+
"execution_count": 6,
|
274 |
+
"outputs": []
|
275 |
+
},
|
276 |
+
{
|
277 |
+
"cell_type": "markdown",
|
278 |
+
"source": [
|
279 |
+
"Let's create a simple LCEL chain using our prompt template Runnable and our LLM Runnable."
|
280 |
+
],
|
281 |
+
"metadata": {
|
282 |
+
"id": "Oe0Qrzn4adzh"
|
283 |
+
}
|
284 |
+
},
|
285 |
+
{
|
286 |
+
"cell_type": "code",
|
287 |
+
"source": [
|
288 |
+
"rag_chain = rag_prompt | hf_llm"
|
289 |
+
],
|
290 |
+
"metadata": {
|
291 |
+
"id": "CE4djpxM0-Fg"
|
292 |
+
},
|
293 |
+
"execution_count": 7,
|
294 |
+
"outputs": []
|
295 |
+
},
|
296 |
+
{
|
297 |
+
"cell_type": "code",
|
298 |
+
"source": [
|
299 |
+
"rag_chain.invoke({\"query\" : \"Who old is Carl?\", \"context\" : \"Carl is a sweet dude, he's 40.\"})"
|
300 |
+
],
|
301 |
+
"metadata": {
|
302 |
+
"id": "PNwrLXqDxHDY",
|
303 |
+
"colab": {
|
304 |
+
"base_uri": "https://localhost:8080/",
|
305 |
+
"height": 35
|
306 |
+
},
|
307 |
+
"outputId": "0ca21520-4c7d-4008-8520-39e43b67d24d"
|
308 |
+
},
|
309 |
+
"execution_count": 8,
|
310 |
+
"outputs": [
|
311 |
+
{
|
312 |
+
"output_type": "execute_result",
|
313 |
+
"data": {
|
314 |
+
"text/plain": [
|
315 |
+
"'According to the context, Carl is 40 years old.'"
|
316 |
+
],
|
317 |
+
"application/vnd.google.colaboratory.intrinsic+json": {
|
318 |
+
"type": "string"
|
319 |
+
}
|
320 |
+
},
|
321 |
+
"metadata": {},
|
322 |
+
"execution_count": 8
|
323 |
+
}
|
324 |
+
]
|
325 |
+
},
|
326 |
+
{
|
327 |
+
"cell_type": "markdown",
|
328 |
+
"source": [
|
329 |
+
"### HuggingFaceInferenceAPIEmbeddings\n",
|
330 |
+
"\n",
|
331 |
+
"Now we can leverage the `HuggingFaceInferenceAPIEmbeddings` module in LangChain to connect to our Hugging Face Inference Endpoint hosted embedding model."
|
332 |
+
],
|
333 |
+
"metadata": {
|
334 |
+
"id": "emGw4-66aBfa"
|
335 |
+
}
|
336 |
+
},
|
337 |
+
{
|
338 |
+
"cell_type": "code",
|
339 |
+
"source": [
|
340 |
+
"from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddings\n",
|
341 |
+
"\n",
|
342 |
+
"YOUR_EMBED_MODEL_URL = \"https://g53n52k0ah1sr106.us-east-1.aws.endpoints.huggingface.cloud\"\n",
|
343 |
+
"\n",
|
344 |
+
"hf_embeddings = HuggingFaceEndpointEmbeddings(\n",
|
345 |
+
" model=YOUR_EMBED_MODEL_URL,\n",
|
346 |
+
" task=\"feature-extraction\",\n",
|
347 |
+
" huggingfacehub_api_token=os.environ[\"HF_TOKEN\"],\n",
|
348 |
+
")"
|
349 |
+
],
|
350 |
+
"metadata": {
|
351 |
+
"id": "n9Q7e4Gnwe_C"
|
352 |
+
},
|
353 |
+
"execution_count": 9,
|
354 |
+
"outputs": []
|
355 |
+
},
|
356 |
+
{
|
357 |
+
"cell_type": "markdown",
|
358 |
+
"source": [
|
359 |
+
"Let's build a simple cosine-similarity function to verify our endpoint is working as expected."
|
360 |
+
],
|
361 |
+
"metadata": {
|
362 |
+
"id": "YXYRBqbBayWb"
|
363 |
+
}
|
364 |
+
},
|
365 |
+
{
|
366 |
+
"cell_type": "code",
|
367 |
+
"source": [
|
368 |
+
"import numpy as np\n",
|
369 |
+
"from numpy.linalg import norm\n",
|
370 |
+
"\n",
|
371 |
+
"def cosine_similarity(phrase_1, phrase_2):\n",
|
372 |
+
" vec_1 = hf_embeddings.embed_documents([phrase_1])[0]\n",
|
373 |
+
" vec2_2 = hf_embeddings.embed_documents([phrase_2])[0]\n",
|
374 |
+
" return np.dot(vec_1, vec2_2) / (norm(vec_1) * norm(vec2_2))"
|
375 |
+
],
|
376 |
+
"metadata": {
|
377 |
+
"id": "lOP6LKr74RG8"
|
378 |
+
},
|
379 |
+
"execution_count": 10,
|
380 |
+
"outputs": []
|
381 |
+
},
|
382 |
+
{
|
383 |
+
"cell_type": "markdown",
|
384 |
+
"source": [
|
385 |
+
"Let's try a few examples below!"
|
386 |
+
],
|
387 |
+
"metadata": {
|
388 |
+
"id": "uGZNhxF2bVIr"
|
389 |
+
}
|
390 |
+
},
|
391 |
+
{
|
392 |
+
"cell_type": "code",
|
393 |
+
"source": [
|
394 |
+
"cosine_similarity(\"I love my fluffy dog!\", \"I adore this furry puppy!\")"
|
395 |
+
],
|
396 |
+
"metadata": {
|
397 |
+
"id": "5o_cqEZ34f15",
|
398 |
+
"colab": {
|
399 |
+
"base_uri": "https://localhost:8080/"
|
400 |
+
},
|
401 |
+
"outputId": "8cbfeb2c-1145-4c55-9759-1fb3579bd361"
|
402 |
+
},
|
403 |
+
"execution_count": 11,
|
404 |
+
"outputs": [
|
405 |
+
{
|
406 |
+
"output_type": "execute_result",
|
407 |
+
"data": {
|
408 |
+
"text/plain": [
|
409 |
+
"0.8903063446222079"
|
410 |
+
]
|
411 |
+
},
|
412 |
+
"metadata": {},
|
413 |
+
"execution_count": 11
|
414 |
+
}
|
415 |
+
]
|
416 |
+
},
|
417 |
+
{
|
418 |
+
"cell_type": "code",
|
419 |
+
"source": [
|
420 |
+
"cosine_similarity(\"I love my fluffy dog!\", \"Eating pizza is the worst! Yuck!\")"
|
421 |
+
],
|
422 |
+
"metadata": {
|
423 |
+
"id": "R1nsAV1n4w4a",
|
424 |
+
"colab": {
|
425 |
+
"base_uri": "https://localhost:8080/"
|
426 |
+
},
|
427 |
+
"outputId": "645d490a-8d31-4e56-b46d-91f425ee90f3"
|
428 |
+
},
|
429 |
+
"execution_count": 12,
|
430 |
+
"outputs": [
|
431 |
+
{
|
432 |
+
"output_type": "execute_result",
|
433 |
+
"data": {
|
434 |
+
"text/plain": [
|
435 |
+
"0.743020791930313"
|
436 |
+
]
|
437 |
+
},
|
438 |
+
"metadata": {},
|
439 |
+
"execution_count": 12
|
440 |
+
}
|
441 |
+
]
|
442 |
+
},
|
443 |
+
{
|
444 |
+
"cell_type": "markdown",
|
445 |
+
"source": [
|
446 |
+
"## Task 4: Preparing Data!\n",
|
447 |
+
"\n",
|
448 |
+
"We'll start by loading some data from GitHub (Paul Graham's Essays) and then move to chunking them into manageable pieces!\n",
|
449 |
+
"\n",
|
450 |
+
"First - let's grab the repository where the files live."
|
451 |
+
],
|
452 |
+
"metadata": {
|
453 |
+
"id": "iiz6vKMlbbP4"
|
454 |
+
}
|
455 |
+
},
|
456 |
+
{
|
457 |
+
"cell_type": "code",
|
458 |
+
"source": [
|
459 |
+
"!git clone https://github.com/dbredvick/paul-graham-to-kindle.git"
|
460 |
+
],
|
461 |
+
"metadata": {
|
462 |
+
"id": "AkuzZben5Eqp",
|
463 |
+
"colab": {
|
464 |
+
"base_uri": "https://localhost:8080/"
|
465 |
+
},
|
466 |
+
"outputId": "eeef9776-f1b3-4f5d-9c36-7d56ef88339c"
|
467 |
+
},
|
468 |
+
"execution_count": 13,
|
469 |
+
"outputs": [
|
470 |
+
{
|
471 |
+
"output_type": "stream",
|
472 |
+
"name": "stdout",
|
473 |
+
"text": [
|
474 |
+
"Cloning into 'paul-graham-to-kindle'...\n",
|
475 |
+
"remote: Enumerating objects: 36, done.\u001b[K\n",
|
476 |
+
"remote: Counting objects: 100% (36/36), done.\u001b[K\n",
|
477 |
+
"remote: Compressing objects: 100% (33/33), done.\u001b[K\n",
|
478 |
+
"remote: Total 36 (delta 3), reused 31 (delta 1), pack-reused 0\u001b[K\n",
|
479 |
+
"Receiving objects: 100% (36/36), 2.35 MiB | 12.64 MiB/s, done.\n",
|
480 |
+
"Resolving deltas: 100% (3/3), done.\n"
|
481 |
+
]
|
482 |
+
}
|
483 |
+
]
|
484 |
+
},
|
485 |
+
{
|
486 |
+
"cell_type": "markdown",
|
487 |
+
"source": [
|
488 |
+
"Next - we can load them using LangChain!"
|
489 |
+
],
|
490 |
+
"metadata": {
|
491 |
+
"id": "8prMk6R0bsYd"
|
492 |
+
}
|
493 |
+
},
|
494 |
+
{
|
495 |
+
"cell_type": "code",
|
496 |
+
"source": [
|
497 |
+
"from langchain_community.document_loaders import TextLoader\n",
|
498 |
+
"\n",
|
499 |
+
"document_loader = TextLoader(\"./paul-graham-to-kindle/paul_graham_essays.txt\")\n",
|
500 |
+
"documents = document_loader.load()"
|
501 |
+
],
|
502 |
+
"metadata": {
|
503 |
+
"id": "K155zM7e53lt"
|
504 |
+
},
|
505 |
+
"execution_count": 14,
|
506 |
+
"outputs": []
|
507 |
+
},
|
508 |
+
{
|
509 |
+
"cell_type": "markdown",
|
510 |
+
"source": [
|
511 |
+
"Now, let's split them into 1000 character pieces."
|
512 |
+
],
|
513 |
+
"metadata": {
|
514 |
+
"id": "5wYfo6_0bwVc"
|
515 |
+
}
|
516 |
+
},
|
517 |
+
{
|
518 |
+
"cell_type": "code",
|
519 |
+
"source": [
|
520 |
+
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
|
521 |
+
"\n",
|
522 |
+
"text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)\n",
|
523 |
+
"split_documents = text_splitter.split_documents(documents)\n",
|
524 |
+
"len(split_documents)"
|
525 |
+
],
|
526 |
+
"metadata": {
|
527 |
+
"id": "w-Gx_0iL6Ikc",
|
528 |
+
"colab": {
|
529 |
+
"base_uri": "https://localhost:8080/"
|
530 |
+
},
|
531 |
+
"outputId": "908a2e04-fda0-43d8-8a5f-36dec3aee3da"
|
532 |
+
},
|
533 |
+
"execution_count": 15,
|
534 |
+
"outputs": [
|
535 |
+
{
|
536 |
+
"output_type": "execute_result",
|
537 |
+
"data": {
|
538 |
+
"text/plain": [
|
539 |
+
"4265"
|
540 |
+
]
|
541 |
+
},
|
542 |
+
"metadata": {},
|
543 |
+
"execution_count": 15
|
544 |
+
}
|
545 |
+
]
|
546 |
+
},
|
547 |
+
{
|
548 |
+
"cell_type": "markdown",
|
549 |
+
"source": [
|
550 |
+
"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",
|
551 |
+
"\n",
|
552 |
+
"We'll need to take a few extra steps, though, due to a few limitations of the endpoint/FAISS.\n",
|
553 |
+
"\n",
|
554 |
+
"We'll start by embeddings our documents in batches of `32`.\n",
|
555 |
+
"\n",
|
556 |
+
"> NOTE: This process might take a while depending on the compute you assigned your embedding endpoint!"
|
557 |
+
],
|
558 |
+
"metadata": {
|
559 |
+
"id": "d5HrkDhTb4i_"
|
560 |
+
}
|
561 |
+
},
|
562 |
+
{
|
563 |
+
"cell_type": "code",
|
564 |
+
"source": [
|
565 |
+
"from langchain_community.vectorstores import FAISS\n",
|
566 |
+
"\n",
|
567 |
+
"for i in range(0, len(split_documents), 32):\n",
|
568 |
+
" if i == 0:\n",
|
569 |
+
" vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)\n",
|
570 |
+
" continue\n",
|
571 |
+
" vectorstore.add_documents(split_documents[i:i+32])"
|
572 |
+
],
|
573 |
+
"metadata": {
|
574 |
+
"id": "ucghQgRp6YXr"
|
575 |
+
},
|
576 |
+
"execution_count": 16,
|
577 |
+
"outputs": []
|
578 |
+
},
|
579 |
+
{
|
580 |
+
"cell_type": "markdown",
|
581 |
+
"source": [
|
582 |
+
"Next, we set up FAISS as a retriever."
|
583 |
+
],
|
584 |
+
"metadata": {
|
585 |
+
"id": "q07ZUp6Db_AO"
|
586 |
+
}
|
587 |
+
},
|
588 |
+
{
|
589 |
+
"cell_type": "code",
|
590 |
+
"source": [
|
591 |
+
"hf_retriever = vectorstore.as_retriever()"
|
592 |
+
],
|
593 |
+
"metadata": {
|
594 |
+
"id": "fXr-yrAq7h8V"
|
595 |
+
},
|
596 |
+
"execution_count": 17,
|
597 |
+
"outputs": []
|
598 |
+
},
|
599 |
+
{
|
600 |
+
"cell_type": "markdown",
|
601 |
+
"source": [
|
602 |
+
"## Task 5: Simple LCEL RAG Chain\n",
|
603 |
+
"\n",
|
604 |
+
"Now we can set up our LCEL RAG chain!\n",
|
605 |
+
"\n",
|
606 |
+
"> NOTE: We're not returning context for this example, and only returning the text output from the LLM."
|
607 |
+
],
|
608 |
+
"metadata": {
|
609 |
+
"id": "sYrW6FRecO7U"
|
610 |
+
}
|
611 |
+
},
|
612 |
+
{
|
613 |
+
"cell_type": "code",
|
614 |
+
"source": [
|
615 |
+
"from operator import itemgetter\n",
|
616 |
+
"from langchain.schema.output_parser import StrOutputParser\n",
|
617 |
+
"from langchain.schema.runnable import RunnablePassthrough\n",
|
618 |
+
"\n",
|
619 |
+
"lcel_rag_chain = {\"context\": itemgetter(\"query\") | hf_retriever, \"query\": itemgetter(\"query\")}| rag_prompt | hf_llm"
|
620 |
+
],
|
621 |
+
"metadata": {
|
622 |
+
"id": "ffIzIlct8ISb"
|
623 |
+
},
|
624 |
+
"execution_count": 18,
|
625 |
+
"outputs": []
|
626 |
+
},
|
627 |
+
{
|
628 |
+
"cell_type": "code",
|
629 |
+
"source": [
|
630 |
+
"lcel_rag_chain.invoke({\"query\" : \"What is the best part of Silicon Valley?\"})"
|
631 |
+
],
|
632 |
+
"metadata": {
|
633 |
+
"id": "HOQfkEgb8nPH",
|
634 |
+
"colab": {
|
635 |
+
"base_uri": "https://localhost:8080/",
|
636 |
+
"height": 105
|
637 |
+
},
|
638 |
+
"outputId": "91bf58f8-7972-4384-a1c4-e27de89aa540"
|
639 |
+
},
|
640 |
+
"execution_count": 19,
|
641 |
+
"outputs": [
|
642 |
+
{
|
643 |
+
"output_type": "execute_result",
|
644 |
+
"data": {
|
645 |
+
"text/plain": [
|
646 |
+
"'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.'"
|
647 |
+
],
|
648 |
+
"application/vnd.google.colaboratory.intrinsic+json": {
|
649 |
+
"type": "string"
|
650 |
+
}
|
651 |
+
},
|
652 |
+
"metadata": {},
|
653 |
+
"execution_count": 19
|
654 |
+
}
|
655 |
+
]
|
656 |
+
},
|
657 |
+
{
|
658 |
+
"cell_type": "markdown",
|
659 |
+
"source": [
|
660 |
+
"# Conclusion:\n",
|
661 |
+
"\n",
|
662 |
+
"Once you've completed this notebook, please move to the Chainlit portion of the assignment, located in the Week 4 Day 1 `README.md`."
|
663 |
+
],
|
664 |
+
"metadata": {
|
665 |
+
"id": "IDhfZf2DeKVo"
|
666 |
+
}
|
667 |
+
}
|
668 |
+
]
|
669 |
+
}
|
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("./paul-graham-to-kindle/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("./data/vectorstore"):
|
57 |
+
vectorstore = FAISS.load_local(
|
58 |
+
"./data/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("./data/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("./data/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=f"{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 @@
|
|
|
|
|
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()
|