HW7
Browse files- .gitignore +6 -0
- Dockerfile +11 -0
- Open_Source_RAG_Leveraging_Hugging_Face_Endpoints_through_LangChain.ipynb +636 -0
- README.md +150 -10
- app.py +165 -0
- chainlit.md +1 -0
- data/paul_graham_essays.txt +0 -0
- paul-graham-to-kindle +1 -0
- requirements.txt +8 -0
- solution_app.py +155 -0
.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,636 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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": null,
|
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": 1,
|
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": 2,
|
104 |
+
"metadata": {
|
105 |
+
"id": "N7u2Tu1FsURh"
|
106 |
+
},
|
107 |
+
"outputs": [],
|
108 |
+
"source": [
|
109 |
+
"YOUR_LLM_ENDPOINT_URL = \"https://mixri33bkq7pn1ko.us-east-1.aws.endpoints.huggingface.cloud\""
|
110 |
+
]
|
111 |
+
},
|
112 |
+
{
|
113 |
+
"cell_type": "code",
|
114 |
+
"execution_count": 3,
|
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": "stderr",
|
125 |
+
"output_type": "stream",
|
126 |
+
"text": [
|
127 |
+
"/home/fzrilic/miniconda3/envs/llmops-course/lib/python3.11/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",
|
128 |
+
" warn_deprecated(\n"
|
129 |
+
]
|
130 |
+
},
|
131 |
+
{
|
132 |
+
"name": "stdout",
|
133 |
+
"output_type": "stream",
|
134 |
+
"text": [
|
135 |
+
"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",
|
136 |
+
"Token is valid (permission: write).\n",
|
137 |
+
"Your token has been saved to /home/fzrilic/.cache/huggingface/token\n",
|
138 |
+
"Login successful\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": 4,
|
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 |
+
"\" 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\""
|
182 |
+
]
|
183 |
+
},
|
184 |
+
"execution_count": 4,
|
185 |
+
"metadata": {},
|
186 |
+
"output_type": "execute_result"
|
187 |
+
}
|
188 |
+
],
|
189 |
+
"source": [
|
190 |
+
"hf_llm.invoke(\"Hello, how are you?\")"
|
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": 5,
|
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 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": 6,
|
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": 7,
|
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 40 years old.'"
|
265 |
+
]
|
266 |
+
},
|
267 |
+
"execution_count": 7,
|
268 |
+
"metadata": {},
|
269 |
+
"output_type": "execute_result"
|
270 |
+
}
|
271 |
+
],
|
272 |
+
"source": [
|
273 |
+
"rag_chain.invoke({\"query\" : \"Who old is Carl?\", \"context\" : \"Carl is a sweet dude, he's 40.\"})"
|
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": 8,
|
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://mzecyobnj3l0x5kl.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": 9,
|
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": 10,
|
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.8903063446222079"
|
356 |
+
]
|
357 |
+
},
|
358 |
+
"execution_count": 10,
|
359 |
+
"metadata": {},
|
360 |
+
"output_type": "execute_result"
|
361 |
+
}
|
362 |
+
],
|
363 |
+
"source": [
|
364 |
+
"cosine_similarity(\"I love my fluffy dog!\", \"I adore this furry puppy!\")"
|
365 |
+
]
|
366 |
+
},
|
367 |
+
{
|
368 |
+
"cell_type": "code",
|
369 |
+
"execution_count": 11,
|
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.7430207919303131"
|
382 |
+
]
|
383 |
+
},
|
384 |
+
"execution_count": 11,
|
385 |
+
"metadata": {},
|
386 |
+
"output_type": "execute_result"
|
387 |
+
}
|
388 |
+
],
|
389 |
+
"source": [
|
390 |
+
"cosine_similarity(\"I love my fluffy dog!\", \"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": 12,
|
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\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 | 5.33 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": 13,
|
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": 14,
|
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": 14,
|
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": 15,
|
515 |
+
"metadata": {
|
516 |
+
"id": "ucghQgRp6YXr"
|
517 |
+
},
|
518 |
+
"outputs": [],
|
519 |
+
"source": [
|
520 |
+
"from langchain_community.vectorstores import FAISS\n",
|
521 |
+
"\n",
|
522 |
+
"for i in range(0, len(split_documents), 32):\n",
|
523 |
+
" if i == 0:\n",
|
524 |
+
" vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)\n",
|
525 |
+
" continue\n",
|
526 |
+
" vectorstore.add_documents(split_documents[i:i+32])"
|
527 |
+
]
|
528 |
+
},
|
529 |
+
{
|
530 |
+
"cell_type": "markdown",
|
531 |
+
"metadata": {
|
532 |
+
"id": "q07ZUp6Db_AO"
|
533 |
+
},
|
534 |
+
"source": [
|
535 |
+
"Next, we set up FAISS as a retriever."
|
536 |
+
]
|
537 |
+
},
|
538 |
+
{
|
539 |
+
"cell_type": "code",
|
540 |
+
"execution_count": 16,
|
541 |
+
"metadata": {
|
542 |
+
"id": "fXr-yrAq7h8V"
|
543 |
+
},
|
544 |
+
"outputs": [],
|
545 |
+
"source": [
|
546 |
+
"hf_retriever = vectorstore.as_retriever()"
|
547 |
+
]
|
548 |
+
},
|
549 |
+
{
|
550 |
+
"cell_type": "markdown",
|
551 |
+
"metadata": {
|
552 |
+
"id": "sYrW6FRecO7U"
|
553 |
+
},
|
554 |
+
"source": [
|
555 |
+
"## Task 5: Simple LCEL RAG Chain\n",
|
556 |
+
"\n",
|
557 |
+
"Now we can set up our LCEL RAG chain!\n",
|
558 |
+
"\n",
|
559 |
+
"> NOTE: We're not returning context for this example, and only returning the text output from the LLM."
|
560 |
+
]
|
561 |
+
},
|
562 |
+
{
|
563 |
+
"cell_type": "code",
|
564 |
+
"execution_count": 17,
|
565 |
+
"metadata": {
|
566 |
+
"id": "ffIzIlct8ISb"
|
567 |
+
},
|
568 |
+
"outputs": [],
|
569 |
+
"source": [
|
570 |
+
"from operator import itemgetter\n",
|
571 |
+
"from langchain.schema.output_parser import StrOutputParser\n",
|
572 |
+
"from langchain.schema.runnable import RunnablePassthrough\n",
|
573 |
+
"\n",
|
574 |
+
"lcel_rag_chain = {\"context\": itemgetter(\"query\") | hf_retriever, \"query\": itemgetter(\"query\")}| rag_prompt | hf_llm"
|
575 |
+
]
|
576 |
+
},
|
577 |
+
{
|
578 |
+
"cell_type": "code",
|
579 |
+
"execution_count": 18,
|
580 |
+
"metadata": {
|
581 |
+
"colab": {
|
582 |
+
"base_uri": "https://localhost:8080/",
|
583 |
+
"height": 127
|
584 |
+
},
|
585 |
+
"id": "HOQfkEgb8nPH",
|
586 |
+
"outputId": "92601728-d001-43e2-e543-e714d66f4f4e"
|
587 |
+
},
|
588 |
+
"outputs": [
|
589 |
+
{
|
590 |
+
"data": {
|
591 |
+
"text/plain": [
|
592 |
+
"\"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.\""
|
593 |
+
]
|
594 |
+
},
|
595 |
+
"execution_count": 18,
|
596 |
+
"metadata": {},
|
597 |
+
"output_type": "execute_result"
|
598 |
+
}
|
599 |
+
],
|
600 |
+
"source": [
|
601 |
+
"lcel_rag_chain.invoke({\"query\" : \"What is the best part of Silicon Valley?\"})"
|
602 |
+
]
|
603 |
+
},
|
604 |
+
{
|
605 |
+
"cell_type": "code",
|
606 |
+
"execution_count": null,
|
607 |
+
"metadata": {},
|
608 |
+
"outputs": [],
|
609 |
+
"source": []
|
610 |
+
}
|
611 |
+
],
|
612 |
+
"metadata": {
|
613 |
+
"colab": {
|
614 |
+
"provenance": [],
|
615 |
+
"toc_visible": true
|
616 |
+
},
|
617 |
+
"kernelspec": {
|
618 |
+
"display_name": "Python 3",
|
619 |
+
"name": "python3"
|
620 |
+
},
|
621 |
+
"language_info": {
|
622 |
+
"codemirror_mode": {
|
623 |
+
"name": "ipython",
|
624 |
+
"version": 3
|
625 |
+
},
|
626 |
+
"file_extension": ".py",
|
627 |
+
"mimetype": "text/x-python",
|
628 |
+
"name": "python",
|
629 |
+
"nbconvert_exporter": "python",
|
630 |
+
"pygments_lexer": "ipython3",
|
631 |
+
"version": "3.11.9"
|
632 |
+
}
|
633 |
+
},
|
634 |
+
"nbformat": 4,
|
635 |
+
"nbformat_minor": 0
|
636 |
+
}
|
README.md
CHANGED
@@ -1,10 +1,150 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Week 4: Tuesday
|
2 |
+
|
3 |
+
In today's assignment, we'll be creating an Open Source LLM-powered LangChain RAG Application in Chainlit.
|
4 |
+
|
5 |
+
There are 2 main sections to this assignment:
|
6 |
+
|
7 |
+
## Build 🏗️
|
8 |
+
|
9 |
+
### Build Task 1: Deploy LLM and Embedding Model to SageMaker Endpoint Through Hugging Face Inference Endpoints
|
10 |
+
|
11 |
+
#### LLM Endpoint
|
12 |
+
|
13 |
+
Select "Inference Endpoint" from the "Solutions" button in Hugging Face:
|
14 |
+
|
15 |
+
![image](https://i.imgur.com/6KC9TCD.png)
|
16 |
+
|
17 |
+
Create a "+ New Endpoint" from the Inference Endpoints dashboard.
|
18 |
+
|
19 |
+
![image](https://i.imgur.com/G6Bq9KC.png)
|
20 |
+
|
21 |
+
Select the `NousResearch/Meta-Llama-3-8B-Instruct` model repository and name your endpoint. Select N. Virginia as your region (`us-east-1`). Give your endpoint an appropriate name. Make sure to select *at least* a L4 GPU.
|
22 |
+
|
23 |
+
![image](https://i.imgur.com/X3YlUbh.png)
|
24 |
+
|
25 |
+
Select the following settings for your `Advanced Configuration`.
|
26 |
+
|
27 |
+
![image](https://i.imgur.com/c0HQ7g1.png)
|
28 |
+
|
29 |
+
Create a `Protected` endpoint.
|
30 |
+
|
31 |
+
![image](https://i.imgur.com/Ak8kchZ.png)
|
32 |
+
|
33 |
+
If you were successful, you should see the following screen:
|
34 |
+
|
35 |
+
![image](https://i.imgur.com/IBYG3wm.png)
|
36 |
+
|
37 |
+
#### Embedding Model Endpoint
|
38 |
+
We'll be using `Snowflake/snowflake-arctic-embed-m` for our embedding model today.
|
39 |
+
|
40 |
+
The process is the same as the LLM - but we'll make a few specific tweaks:
|
41 |
+
|
42 |
+
Let's make sure our set-up reflects the following screenshots:
|
43 |
+
|
44 |
+
![image](https://i.imgur.com/IHh8FnC.png)
|
45 |
+
|
46 |
+
After which, make sure the advanced configuration is set like so:
|
47 |
+
|
48 |
+
![image](https://i.imgur.com/bbcrhUj.png)
|
49 |
+
|
50 |
+
> #### NOTE: PLEASE SHUTDOWN YOUR INSTANCES WHEN YOU HAVE COMPLETED THE ASSIGNMENT TO PREVENT UNESSECARY CHARGES.
|
51 |
+
|
52 |
+
### Build Task 2: Create RAG Pipeline with LangChain
|
53 |
+
|
54 |
+
Follow the [notebook](https://colab.research.google.com/drive/1v1FYmvKH4gsqcdZwIT9wvbQe0GUjrc9d?usp=sharing) to create a LangChain pipeline powered by Hugging Face endpoints!
|
55 |
+
|
56 |
+
Once you're done - please move on to Build Task 3!
|
57 |
+
|
58 |
+
### Build Task 3: Create a Chainlit Application
|
59 |
+
|
60 |
+
1. Create a new empty Docker space through Hugging Face - with the following settings:
|
61 |
+
|
62 |
+
![image](https://i.imgur.com/0YzyQX7.png)
|
63 |
+
|
64 |
+
> NOTE: You may notice the application builds slowly (~15min.) with the default free-tier hardware. The process will be faster using the `CPU upgrade` Space Hardware - though it is not required.
|
65 |
+
|
66 |
+
2. Clone the newly created space into a directory that is *NOT IN YOUR AI MAKERSPACE REPOSITORY* using the SSH option.
|
67 |
+
|
68 |
+
> NOTE: You may need to ensure you've added your SSH key to Hugging Face, as well as GitHub. This should already be done.
|
69 |
+
|
70 |
+
![image](https://i.imgur.com/5RyBdP5.png)
|
71 |
+
|
72 |
+
3. Copy and Paste (`cp ...` or through UI) the contents of `Week 4/Day 1` into the newly cloned repository.
|
73 |
+
|
74 |
+
> NOTE: Please keep the `README.md` that was cloned from your space and delete the class `README.md`.
|
75 |
+
|
76 |
+
4. Using the `ls` command or the `tree` command verify that you have copied over:
|
77 |
+
- `app.py`
|
78 |
+
- `Dockerfile`
|
79 |
+
- `data/paul_graham_essays.txt`
|
80 |
+
- `chainlit.md`
|
81 |
+
- `.gitignore`
|
82 |
+
- `.env.sample`
|
83 |
+
- `solution_app.py`
|
84 |
+
- `requirements.txt`
|
85 |
+
|
86 |
+
Here is an example as the `ls -al` CLI command:
|
87 |
+
|
88 |
+
![image](https://i.imgur.com/vazGYeb.png)
|
89 |
+
|
90 |
+
5. Work through the `app.py` file to migrate your LCEL LangChain RAG Chain from the Notebook to Chainlit!
|
91 |
+
|
92 |
+
6. Be sure to modify your `README.md` and `chainlit.md` as you see fit!
|
93 |
+
|
94 |
+
> NOTE: If you get stuck, there is a working reference version in `solution_app.py`.
|
95 |
+
|
96 |
+
7. When you are done with local testing - push your changes to your space.
|
97 |
+
|
98 |
+
8. Make sure you add your `HF_LLM_ENDPOINT`, `HF_EMBED_ENDPOINT`, `HF_TOKEN` as "Secrets" in your Hugging Face Space.
|
99 |
+
|
100 |
+
### Terminating Your Resources
|
101 |
+
|
102 |
+
Please head to the settings of each endpoint and select `Delete Endpoint`. You will need to type the name of the endpoint to delete the resources.
|
103 |
+
|
104 |
+
### Deliverables
|
105 |
+
|
106 |
+
- Completed Notebook
|
107 |
+
- Chainlit Application in a Hugging Face Space Powered by Hugging Face Endpoints
|
108 |
+
- Screenshot of endpoint usage
|
109 |
+
|
110 |
+
Example Screen Shot:
|
111 |
+
|
112 |
+
![image](https://i.imgur.com/qfbcVpS.png)
|
113 |
+
|
114 |
+
## Ship 🚢
|
115 |
+
|
116 |
+
Create a Hugging Face Space powered by Hugging Face Endpoints!
|
117 |
+
|
118 |
+
### Deliverables
|
119 |
+
|
120 |
+
- A short Loom of the space, and a 1min. walkthrough of the application in full
|
121 |
+
|
122 |
+
## Share 🚀
|
123 |
+
|
124 |
+
Make a social media post about your final application!
|
125 |
+
|
126 |
+
### Deliverables
|
127 |
+
|
128 |
+
- Make a post on any social media platform about what you built!
|
129 |
+
|
130 |
+
Here's a template to get you started:
|
131 |
+
|
132 |
+
```
|
133 |
+
🚀 Exciting News! 🚀
|
134 |
+
|
135 |
+
I am thrilled to announce that I have just built and shipped a open-source LLM-powered Retrieval Augmented Generation Application with LangChain! 🎉🤖
|
136 |
+
|
137 |
+
🔍 Three Key Takeaways:
|
138 |
+
1️⃣
|
139 |
+
2️⃣
|
140 |
+
3️⃣
|
141 |
+
|
142 |
+
Let's continue pushing the boundaries of what's possible in the world of AI and question-answering. Here's to many more innovations! 🚀
|
143 |
+
Shout out to @AIMakerspace !
|
144 |
+
|
145 |
+
#LangChain #QuestionAnswering #RetrievalAugmented #Innovation #AI #TechMilestone
|
146 |
+
|
147 |
+
Feel free to reach out if you're curious or would like to collaborate on similar projects! 🤝🔥
|
148 |
+
```
|
149 |
+
|
150 |
+
> #### NOTE: PLEASE SHUTDOWN YOUR INSTANCES WHEN YOU HAVE COMPLETED THE ASSIGNMENT TO PREVENT UNESSECARY CHARGES.
|
app.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = TextLoader("./data/paul_graham_essays.txt")
|
43 |
+
documents = text_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=os.environ["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 |
+
|
70 |
+
for i in range(0, len(split_documents), 32):
|
71 |
+
if i == 0:
|
72 |
+
vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)
|
73 |
+
continue
|
74 |
+
vectorstore.add_documents(split_documents[i:i+32])
|
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.
|
87 |
+
If you can't answer the question with the provided context, say you don't know.<|eot_id|>
|
88 |
+
|
89 |
+
<|start_header_id|>user<|end_header_id|>
|
90 |
+
User Query:
|
91 |
+
{query}
|
92 |
+
|
93 |
+
Context:
|
94 |
+
{context}<|eot_id|>
|
95 |
+
|
96 |
+
<|start_header_id|>assistant<|end_header_id|>
|
97 |
+
"""
|
98 |
+
|
99 |
+
### 2. CREATE PROMPT TEMPLATE
|
100 |
+
rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
|
101 |
+
|
102 |
+
# -- GENERATION -- #
|
103 |
+
"""
|
104 |
+
1. Create a HuggingFaceEndpoint for the LLM
|
105 |
+
"""
|
106 |
+
### 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
|
107 |
+
|
108 |
+
hf_llm = HuggingFaceEndpoint(
|
109 |
+
endpoint_url=f"{HF_LLM_ENDPOINT}",
|
110 |
+
max_new_tokens=512,
|
111 |
+
top_k=10,
|
112 |
+
top_p=0.95,
|
113 |
+
typical_p=0.95,
|
114 |
+
temperature=0.01,
|
115 |
+
repetition_penalty=1.03,
|
116 |
+
huggingfacehub_api_token=os.environ["HF_TOKEN"]
|
117 |
+
)
|
118 |
+
|
119 |
+
@cl.author_rename
|
120 |
+
def rename(original_author: str):
|
121 |
+
"""
|
122 |
+
This function can be used to rename the 'author' of a message.
|
123 |
+
|
124 |
+
In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
|
125 |
+
"""
|
126 |
+
rename_dict = {
|
127 |
+
"Assistant" : "Paul Graham Essay Bot"
|
128 |
+
}
|
129 |
+
return rename_dict.get(original_author, original_author)
|
130 |
+
|
131 |
+
@cl.on_chat_start
|
132 |
+
async def start_chat():
|
133 |
+
"""
|
134 |
+
This function will be called at the start of every user session.
|
135 |
+
|
136 |
+
We will build our LCEL RAG chain here, and store it in the user session.
|
137 |
+
|
138 |
+
The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
|
139 |
+
"""
|
140 |
+
|
141 |
+
### BUILD LCEL RAG CHAIN THAT ONLY RETURNS TEXT
|
142 |
+
lcel_rag_chain = {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}| rag_prompt | hf_llm
|
143 |
+
|
144 |
+
cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
|
145 |
+
|
146 |
+
@cl.on_message
|
147 |
+
async def main(message: cl.Message):
|
148 |
+
"""
|
149 |
+
This function will be called every time a message is recieved from a session.
|
150 |
+
|
151 |
+
We will use the LCEL RAG chain to generate a response to the user query.
|
152 |
+
|
153 |
+
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.
|
154 |
+
"""
|
155 |
+
lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
|
156 |
+
|
157 |
+
msg = cl.Message(content="")
|
158 |
+
|
159 |
+
async for chunk in lcel_rag_chain.astream(
|
160 |
+
{"query": message.content},
|
161 |
+
config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
|
162 |
+
):
|
163 |
+
await msg.stream_token(chunk)
|
164 |
+
|
165 |
+
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
|
|
paul-graham-to-kindle
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit 0ec72911d312317e77c15c1a874156190b34e746
|
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()
|