shivXy commited on
Commit
8411472
Β·
1 Parent(s): 46a5c14
Files changed (1) hide show
  1. README.md +368 -5
README.md CHANGED
@@ -1,10 +1,373 @@
1
  ---
2
- title: NoT Llm Wiz CoolN3WSpace
3
- emoji: 🐨
4
- colorFrom: purple
5
- colorTo: red
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: DeployPythonicRAG
3
+ emoji: πŸ“‰
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: docker
7
  pinned: false
8
+ license: apache-2.0
9
  ---
10
 
11
+ # Deploying Pythonic Chat With Your Text File Application
12
+
13
+ In today's breakout rooms, we will be following the process that you saw during the challenge.
14
+
15
+ Today, we will repeat the same process - but powered by our Pythonic RAG implementation we created last week.
16
+
17
+ You'll notice a few differences in the `app.py` logic - as well as a few changes to the `aimakerspace` package to get things working smoothly with Chainlit.
18
+
19
+ > NOTE: If you want to run this locally - be sure to use `uv sync`, and then `uv run chainlit run app.py` to start the application outside of Docker.
20
+
21
+ ## Reference Diagram (It's Busy, but it works)
22
+
23
+ ![image](https://i.imgur.com/IaEVZG2.png)
24
+
25
+ ### Anatomy of a Chainlit Application
26
+
27
+ [Chainlit](https://docs.chainlit.io/get-started/overview) is a Python package similar to Streamlit that lets users write a backend and a front end in a single (or multiple) Python file(s). It is mainly used for prototyping LLM-based Chat Style Applications - though it is used in production in some settings with 1,000,000s of MAUs (Monthly Active Users).
28
+
29
+ The primary method of customizing and interacting with the Chainlit UI is through a few critical [decorators](https://blog.hubspot.com/website/decorators-in-python).
30
+
31
+ > NOTE: Simply put, the decorators (in Chainlit) are just ways we can "plug-in" to the functionality in Chainlit.
32
+
33
+ We'll be concerning ourselves with three main scopes:
34
+
35
+ 1. On application start - when we start the Chainlit application with a command like `chainlit run app.py`
36
+ 2. On chat start - when a chat session starts (a user opens the web browser to the address hosting the application)
37
+ 3. On message - when the users sends a message through the input text box in the Chainlit UI
38
+
39
+ Let's dig into each scope and see what we're doing!
40
+
41
+ ### On Application Start:
42
+
43
+ The first thing you'll notice is that we have the traditional "wall of imports" this is to ensure we have everything we need to run our application.
44
+
45
+ ```python
46
+ import os
47
+ from typing import List
48
+ from chainlit.types import AskFileResponse
49
+ from aimakerspace.text_utils import CharacterTextSplitter, TextFileLoader
50
+ from aimakerspace.openai_utils.prompts import (
51
+ UserRolePrompt,
52
+ SystemRolePrompt,
53
+ AssistantRolePrompt,
54
+ )
55
+ from aimakerspace.openai_utils.embedding import EmbeddingModel
56
+ from aimakerspace.vectordatabase import VectorDatabase
57
+ from aimakerspace.openai_utils.chatmodel import ChatOpenAI
58
+ import chainlit as cl
59
+ ```
60
+
61
+ Next up, we have some prompt templates. As all sessions will use the same prompt templates without modification, and we don't need these templates to be specific per template - we can set them up here - at the application scope.
62
+
63
+ ```python
64
+ system_template = """\
65
+ Use the following context to answer a users question. If you cannot find the answer in the context, say you don't know the answer."""
66
+ system_role_prompt = SystemRolePrompt(system_template)
67
+
68
+ user_prompt_template = """\
69
+ Context:
70
+ {context}
71
+
72
+ Question:
73
+ {question}
74
+ """
75
+ user_role_prompt = UserRolePrompt(user_prompt_template)
76
+ ```
77
+
78
+ > NOTE: You'll notice that these are the exact same prompt templates we used from the Pythonic RAG Notebook in Week 1 Day 2!
79
+
80
+ Following that - we can create the Python Class definition for our RAG pipeline - or *chain*, as we'll refer to it in the rest of this walkthrough.
81
+
82
+ Let's look at the definition first:
83
+
84
+ ```python
85
+ class RetrievalAugmentedQAPipeline:
86
+ def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:
87
+ self.llm = llm
88
+ self.vector_db_retriever = vector_db_retriever
89
+
90
+ async def arun_pipeline(self, user_query: str):
91
+ ### RETRIEVAL
92
+ context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
93
+
94
+ context_prompt = ""
95
+ for context in context_list:
96
+ context_prompt += context[0] + "\n"
97
+
98
+ ### AUGMENTED
99
+ formatted_system_prompt = system_role_prompt.create_message()
100
+
101
+ formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)
102
+
103
+
104
+ ### GENERATION
105
+ async def generate_response():
106
+ async for chunk in self.llm.astream([formatted_system_prompt, formatted_user_prompt]):
107
+ yield chunk
108
+
109
+ return {"response": generate_response(), "context": context_list}
110
+ ```
111
+
112
+ Notice a few things:
113
+
114
+ 1. We have modified this `RetrievalAugmentedQAPipeline` from the initial notebook to support streaming.
115
+ 2. In essence, our pipeline is *chaining* a few events together:
116
+ 1. We take our user query, and chain it into our Vector Database to collect related chunks
117
+ 2. We take those contexts and our user's questions and chain them into the prompt templates
118
+ 3. We take that prompt template and chain it into our LLM call
119
+ 4. We chain the response of the LLM call to the user
120
+ 3. We are using a lot of `async` again!
121
+
122
+ Now, we're going to create a helper function for processing uploaded text files.
123
+
124
+ First, we'll instantiate a shared `CharacterTextSplitter`.
125
+
126
+ ```python
127
+ text_splitter = CharacterTextSplitter()
128
+ ```
129
+
130
+ Now we can define our helper.
131
+
132
+ ```python
133
+ def process_file(file: AskFileResponse):
134
+ import tempfile
135
+ import shutil
136
+
137
+ print(f"Processing file: {file.name}")
138
+
139
+ # Create a temporary file with the correct extension
140
+ suffix = f".{file.name.split('.')[-1]}"
141
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
142
+ # Copy the uploaded file content to the temporary file
143
+ shutil.copyfile(file.path, temp_file.name)
144
+ print(f"Created temporary file at: {temp_file.name}")
145
+
146
+ # Create appropriate loader
147
+ if file.name.lower().endswith('.pdf'):
148
+ loader = PDFLoader(temp_file.name)
149
+ else:
150
+ loader = TextFileLoader(temp_file.name)
151
+
152
+ try:
153
+ # Load and process the documents
154
+ documents = loader.load_documents()
155
+ texts = text_splitter.split_texts(documents)
156
+ return texts
157
+ finally:
158
+ # Clean up the temporary file
159
+ try:
160
+ os.unlink(temp_file.name)
161
+ except Exception as e:
162
+ print(f"Error cleaning up temporary file: {e}")
163
+ ```
164
+
165
+ Simply put, this downloads the file as a temp file, we load it in with `TextFileLoader` and then split it with our `TextSplitter`, and returns that list of strings!
166
+
167
+ #### ❓ QUESTION #1:
168
+
169
+ Why do we want to support streaming? What about streaming is important, or useful?
170
+ A- **Responsiveness:** Streaming enables users to view partial responses as they are being generated, reducing the perceived wait time for the complete answer.
171
+
172
+ **Engagement:** Incremental updates maintain user engagement, especially for longer queries or responses, while also minimizing the impact of perceived latency.
173
+ Async is also important for the same reason it takes way threading locks etc.
174
+
175
+ ### On Chat Start:
176
+
177
+ The next scope is where "the magic happens". On Chat Start is when a user begins a chat session. This will happen whenever a user opens a new chat window, or refreshes an existing chat window.
178
+
179
+ You'll see that our code is set-up to immediately show the user a chat box requesting them to upload a file.
180
+
181
+ ```python
182
+ while files == None:
183
+ files = await cl.AskFileMessage(
184
+ content="Please upload a Text or PDF file to begin!",
185
+ accept=["text/plain", "application/pdf"],
186
+ max_size_mb=2,
187
+ timeout=180,
188
+ ).send()
189
+ ```
190
+
191
+ Once we've obtained the text file - we'll use our processing helper function to process our text!
192
+
193
+ After we have processed our text file - we'll need to create a `VectorDatabase` and populate it with our processed chunks and their related embeddings!
194
+
195
+ ```python
196
+ vector_db = VectorDatabase()
197
+ vector_db = await vector_db.abuild_from_list(texts)
198
+ ```
199
+
200
+ Once we have that piece completed - we can create the chain we'll be using to respond to user queries!
201
+
202
+ ```python
203
+ retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(
204
+ vector_db_retriever=vector_db,
205
+ llm=chat_openai
206
+ )
207
+ ```
208
+
209
+ Now, we'll save that into our user session!
210
+
211
+ > NOTE: Chainlit has some great documentation about [User Session](https://docs.chainlit.io/concepts/user-session).
212
+
213
+ #### ❓ QUESTION #2:
214
+
215
+ Why are we using User Session here? What about Python makes us need to use this? Why not just store everything in a global variable?
216
+ A 1- why user sessions: User sessions allow the application to maintain individual states for each user, preventing data overlap and ensuring personalized interactions.
217
+ A 2- What about Python makes us need to use this? In Python, global variables are shared across all users and sessions, which can lead to data conflicts in multi-user applications. Since Python's default behavior doesn't isolate global variables per user session, using them can cause unintended data sharing and race conditions. Therefore, to manage state information unique to each user, it's essential to implement a session management system like Chainlit's user session.
218
+ A 3- Why not just store everything in a global variable? Prevents data conflicts and ensures that each user's data is isolated.
219
+ ### On Message
220
+
221
+ First, we load our chain from the user session:
222
+
223
+ ```python
224
+ chain = cl.user_session.get("chain")
225
+ ```
226
+
227
+ Then, we run the chain on the content of the message - and stream it to the front end - that's it!
228
+
229
+ ```python
230
+ msg = cl.Message(content="")
231
+ result = await chain.arun_pipeline(message.content)
232
+
233
+ async for stream_resp in result["response"]:
234
+ await msg.stream_token(stream_resp)
235
+ ```
236
+
237
+ ### πŸŽ‰
238
+
239
+ With that - you've created a Chainlit application that moves our Pythonic RAG notebook to a Chainlit application!
240
+
241
+ ## Deploying the Application to Hugging Face Space
242
+
243
+ Due to the way the repository is created - it should be straightforward to deploy this to a Hugging Face Space!
244
+
245
+ > NOTE: If you wish to go through the local deployments using `uv run chainlit run app.py` and Docker - please feel free to do so!
246
+
247
+ <details>
248
+ <summary>Creating a Hugging Face Space</summary>
249
+
250
+ 1. Navigate to the `Spaces` tab.
251
+
252
+ ![image](https://i.imgur.com/aSMlX2T.png)
253
+
254
+ 2. Click on `Create new Space`
255
+
256
+ ![image](https://i.imgur.com/YaSSy5p.png)
257
+
258
+ 3. Create the Space by providing values in the form. Make sure you've selected "Docker" as your Space SDK.
259
+
260
+ ![image](https://i.imgur.com/6h9CgH6.png)
261
+
262
+ </details>
263
+
264
+ <details>
265
+ <summary>Adding this Repository to the Newly Created Space</summary>
266
+
267
+ 1. Collect the SSH address from the newly created Space.
268
+
269
+ ![image](https://i.imgur.com/Oag0m8E.png)
270
+
271
+ > NOTE: The address is the component that starts with `[email protected]:spaces/`.
272
+
273
+ 2. Use the command:
274
+
275
+ ```bash
276
+ git remote add hf HF_SPACE_SSH_ADDRESS_HERE
277
+ ```
278
+
279
+ 3. Use the command:
280
+
281
+ ```bash
282
+ git pull hf main --no-rebase --allow-unrelated-histories -X ours
283
+ ```
284
+
285
+ 4. Use the command:
286
+
287
+ ```bash
288
+ git add .
289
+ ```
290
+
291
+ 5. Use the command:
292
+
293
+ ```bash
294
+ git commit -m "Deploying Pythonic RAG"
295
+ ```
296
+
297
+ 6. Use the command:
298
+
299
+ ```bash
300
+ git push hf main
301
+ ```
302
+
303
+ 7. The Space should automatically build as soon as the push is completed!
304
+
305
+ > NOTE: The build will fail before you complete the following steps!
306
+
307
+ </details>
308
+
309
+ <details>
310
+ <summary>Adding OpenAI Secrets to the Space</summary>
311
+
312
+ 1. Navigate to your Space settings.
313
+
314
+ ![image](https://i.imgur.com/zh0a2By.png)
315
+
316
+ 2. Navigate to `Variables and secrets` on the Settings page and click `New secret`:
317
+
318
+ ![image](https://i.imgur.com/g2KlZdz.png)
319
+
320
+ 3. In the `Name` field - input `OPENAI_API_KEY` in the `Value (private)` field, put your OpenAI API Key.
321
+
322
+ ![image](https://i.imgur.com/eFcZ8U3.png)
323
+
324
+ 4. The Space will begin rebuilding!
325
+
326
+ </details>
327
+
328
+ ## πŸŽ‰
329
+
330
+ You just deployed Pythonic RAG!
331
+
332
+ Try uploading a text file and asking some questions!
333
+
334
+ #### ❓ Discussion Question #1:
335
+
336
+ Upload a PDF file of the recent DeepSeek-R1 paper and ask the following questions:
337
+
338
+ 1. What is RL and how does it help reasoning?
339
+ A- Reinforcement Learning (RL) is a type of machine learning where an agent learns to make decisions by taking actions in an environment to maximize cumulative rewards. In the context provided, RL is particularly effective in domains where feedback can be garnered from external tools, such as coding or mathematics. It helps reasoning by guiding the optimization process through rewards that reflect the quality of the model's outputs.
340
+
341
+ In addition, RL is used in a combined training pipeline with Supervised Fine-Tuning (SFT) to enhance the reasoning capabilities of models. During this process, the model can learn to integrate various patterns and generate responses that incorporate elements of reflection and verification. This helps improve the clarity, accuracy, and reliability of the reasoning exhibited in the model's outputs. By using RL, the model can adapt and refine its responses over many iterations based on the feedback received, ultimately leading to better reasoning abilities.
342
+
343
+
344
+ ![alt text](image.png)
345
+
346
+
347
+
348
+ 2. What is the difference between DeepSeek-R1 and DeepSeek-R1-Zero?
349
+ A- DeepSeek-R1-Zero is a version of the DeepSeek-R1 model that has been fine-tuned on a smaller dataset. This allows the model to be more efficient and faster, while still maintaining a high level of accuracy.
350
+ BUT the paper doesn't mention DeepSeek-R1-Zero.
351
+
352
+
353
+ ![alt text](image-1.png)
354
+
355
+
356
+ 3. What is this paper about?
357
+ A- The DeepSeek-V3.pdf document provides a technical report on DeepSeek-V3, a strong Mixture-of-Experts (MoE) language model featuring 671 billion total parameters, with 37 billion activated for each token. It discusses the efficient training framework, the optimizations made for pipeline and expert parallelism, as well as communication strategies. The document details the architecture based on Multi-head Latent Attention and DeepSeekMoE, the training objectives used, and the extensive pre-training and fine-tuning stages. Additionally, it includes evaluation results showing DeepSeek-V3's performance in comparison with other state-of-the-art models, demonstrating its superiority as an open-source model. Lastly, it addresses limitations and suggests future research directions.
358
+
359
+
360
+ ![alt text](image-2.png)
361
+
362
+
363
+ Does this application pass your vibe check? Are there any immediate pitfalls you're noticing? It passes some of my vibe checks. It still doesn't have a good way to handle the context.
364
+ The vibe check is looking better than past vibe checks. One of the issues I can see is that while we are using a vector database, we are not using it to its full potential. Seems like we would
365
+ want to user query tuning to improve the context window.
366
+
367
+ ## 🚧 CHALLENGE MODE 🚧
368
+
369
+ For the challenge mode, please instead create a simple FastAPI backend with a simple React (or any other JS framework) frontend.
370
+
371
+ You can use the same prompt templates and RAG pipeline as we did here - but you'll need to modify the code to work with FastAPI and React.
372
+
373
+ Deploy this application to Hugging Face Spaces!