vinod chandrashekaran commited on
Commit
f63bc6b
1 Parent(s): f27f108

initial commit to hf spaces

Browse files
Files changed (6) hide show
  1. BuildingAChainlitApp.md +227 -0
  2. Dockerfile +11 -0
  3. README.md +128 -0
  4. app_v1.py +360 -0
  5. chainlit.md +20 -0
  6. requirements.txt +7 -0
BuildingAChainlitApp.md ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Building a Chainlit App
2
+
3
+ What if we want to take our Week 1 Day 2 assignment - [Pythonic RAG](https://github.com/AI-Maker-Space/AIE4/tree/main/Week%201/Day%202) - and bring it out of the notebook?
4
+
5
+ Well - we'll cover exactly that here!
6
+
7
+ ## Anatomy of a Chainlit Application
8
+
9
+ [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).
10
+
11
+ 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).
12
+
13
+ > NOTE: Simply put, the decorators (in Chainlit) are just ways we can "plug-in" to the functionality in Chainlit.
14
+
15
+ We'll be concerning ourselves with three main scopes:
16
+
17
+ 1. On application start - when we start the Chainlit application with a command like `chainlit run app.py`
18
+ 2. On chat start - when a chat session starts (a user opens the web browser to the address hosting the application)
19
+ 3. On message - when the users sends a message through the input text box in the Chainlit UI
20
+
21
+ Let's dig into each scope and see what we're doing!
22
+
23
+ ## On Application Start:
24
+
25
+ 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.
26
+
27
+ ```python
28
+ import os
29
+ from typing import List
30
+ from chainlit.types import AskFileResponse
31
+ from aimakerspace.text_utils import CharacterTextSplitter, TextFileLoader
32
+ from aimakerspace.openai_utils.prompts import (
33
+ UserRolePrompt,
34
+ SystemRolePrompt,
35
+ AssistantRolePrompt,
36
+ )
37
+ from aimakerspace.openai_utils.embedding import EmbeddingModel
38
+ from aimakerspace.vectordatabase import VectorDatabase
39
+ from aimakerspace.openai_utils.chatmodel import ChatOpenAI
40
+ import chainlit as cl
41
+ ```
42
+
43
+ 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.
44
+
45
+ ```python
46
+ system_template = """\
47
+ 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."""
48
+ system_role_prompt = SystemRolePrompt(system_template)
49
+
50
+ user_prompt_template = """\
51
+ Context:
52
+ {context}
53
+
54
+ Question:
55
+ {question}
56
+ """
57
+ user_role_prompt = UserRolePrompt(user_prompt_template)
58
+ ```
59
+
60
+ > NOTE: You'll notice that these are the exact same prompt templates we used from the Pythonic RAG Notebook in Week 1 Day 2!
61
+
62
+ 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.
63
+
64
+ Let's look at the definition first:
65
+
66
+ ```python
67
+ class RetrievalAugmentedQAPipeline:
68
+ def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:
69
+ self.llm = llm
70
+ self.vector_db_retriever = vector_db_retriever
71
+
72
+ async def arun_pipeline(self, user_query: str):
73
+ ### RETRIEVAL
74
+ context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
75
+
76
+ context_prompt = ""
77
+ for context in context_list:
78
+ context_prompt += context[0] + "\n"
79
+
80
+ ### AUGMENTED
81
+ formatted_system_prompt = system_role_prompt.create_message()
82
+
83
+ formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)
84
+
85
+
86
+ ### GENERATION
87
+ async def generate_response():
88
+ async for chunk in self.llm.astream([formatted_system_prompt, formatted_user_prompt]):
89
+ yield chunk
90
+
91
+ return {"response": generate_response(), "context": context_list}
92
+ ```
93
+
94
+ Notice a few things:
95
+
96
+ 1. We have modified this `RetrievalAugmentedQAPipeline` from the initial notebook to support streaming.
97
+ 2. In essence, our pipeline is *chaining* a few events together:
98
+ 1. We take our user query, and chain it into our Vector Database to collect related chunks
99
+ 2. We take those contexts and our user's questions and chain them into the prompt templates
100
+ 3. We take that prompt template and chain it into our LLM call
101
+ 4. We chain the response of the LLM call to the user
102
+ 3. We are using a lot of `async` again!
103
+
104
+ Now, we're going to create a helper function for processing uploaded text files.
105
+
106
+ First, we'll instantiate a shared `CharacterTextSplitter`.
107
+
108
+ ```python
109
+ text_splitter = CharacterTextSplitter()
110
+ ```
111
+
112
+ Now we can define our helper.
113
+
114
+ ```python
115
+ def process_text_file(file: AskFileResponse):
116
+ import tempfile
117
+
118
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as temp_file:
119
+ temp_file_path = temp_file.name
120
+
121
+ with open(temp_file_path, "wb") as f:
122
+ f.write(file.content)
123
+
124
+ text_loader = TextFileLoader(temp_file_path)
125
+ documents = text_loader.load_documents()
126
+ texts = text_splitter.split_texts(documents)
127
+ return texts
128
+ ```
129
+
130
+ 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!
131
+
132
+ #### QUESTION #1:
133
+
134
+ Why do we want to support streaming? What about streaming is important, or useful?
135
+
136
+ #### ANSWER #1:
137
+
138
+ Streaming is needed to accommodate transfer of data packets over a network (eg internet).
139
+ Important because nearly all applications are written to be hosted on a network
140
+ (corporate intranet or over the internet) to be used by many people.
141
+
142
+
143
+ ## On Chat Start:
144
+
145
+ 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.
146
+
147
+ You'll see that our code is set-up to immediately show the user a chat box requesting them to upload a file.
148
+
149
+ ```python
150
+ while files == None:
151
+ files = await cl.AskFileMessage(
152
+ content="Please upload a Text File file to begin!",
153
+ accept=["text/plain"],
154
+ max_size_mb=2,
155
+ timeout=180,
156
+ ).send()
157
+ ```
158
+
159
+ Once we've obtained the text file - we'll use our processing helper function to process our text!
160
+
161
+ 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!
162
+
163
+ ```python
164
+ vector_db = VectorDatabase()
165
+ vector_db = await vector_db.abuild_from_list(texts)
166
+ ```
167
+
168
+ Once we have that piece completed - we can create the chain we'll be using to respond to user queries!
169
+
170
+ ```python
171
+ retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(
172
+ vector_db_retriever=vector_db,
173
+ llm=chat_openai
174
+ )
175
+ ```
176
+
177
+ Now, we'll save that into our user session!
178
+
179
+ > NOTE: Chainlit has some great documentation about [User Session](https://docs.chainlit.io/concepts/user-session).
180
+
181
+ ### QUESTION #2:
182
+
183
+ 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?
184
+
185
+ ### ANSWER #2:
186
+ User Session creates a scope akin to a local scope in Python. i.e., setting up and managing variables, etc. for the
187
+ duration of a chat session with a specific user. This provides a clean separation across users (which would not
188
+ happen if everything was stored in a global variable) and lets the app function smoothly for all users (e.g., by preventing the occurrence of race conditions).
189
+
190
+
191
+ ## On Message
192
+
193
+ First, we load our chain from the user session:
194
+
195
+ ```python
196
+ chain = cl.user_session.get("chain")
197
+ ```
198
+
199
+ Then, we run the chain on the content of the message - and stream it to the front end - that's it!
200
+
201
+ ```python
202
+ msg = cl.Message(content="")
203
+ result = await chain.arun_pipeline(message.content)
204
+
205
+ async for stream_resp in result["response"]:
206
+ await msg.stream_token(stream_resp)
207
+ ```
208
+
209
+ ## 🎉
210
+
211
+ With that - you've created a Chainlit application that moves our Pythonic RAG notebook to a Chainlit application!
212
+
213
+ ## 🚧 CHALLENGE MODE 🚧
214
+
215
+ For an extra challenge - modify the behaviour of your applciation by integrating changes you made to your Pythonic RAG notebook (using new retrieval methods, etc.)
216
+
217
+ If you're still looking for a challenge, or didn't make any modifications to your Pythonic RAG notebook:
218
+
219
+ 1) Allow users to upload PDFs (this will require you to build a PDF parser as well)
220
+ 2) Modify the VectorStore to leverage [Qdrant](https://python-client.qdrant.tech/)
221
+
222
+ > NOTE: The motivation for these challenges is simple - the beginning of the course is extremely information dense, and people come from all kinds of different technical backgrounds. In order to ensure that all learners are able to engage with the content confidently and comfortably, we want to focus on the basic units of technical competency required. This leads to a situation where some learners, who came in with more robust technical skills, find the introductory material to be too simple - and these open-ended challenges help us do this!
223
+
224
+
225
+
226
+
227
+
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_v1.py", "--port", "7860"]
README.md CHANGED
@@ -9,3 +9,131 @@ license: apache-2.0
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
12
+
13
+
14
+ # Summary
15
+
16
+ This is my completed pythonic RAG assignment, completed for Session 3 of the AI Engineering Cohort 4.
17
+ I implemented the following:
18
+ 1. Allow user to upload TWO documents (instead of a single document)
19
+ 2. Format of doc: they can be either text files or pdf docs.
20
+ 3. Text splitter - RecursiveTextSplitter from Langchain
21
+ 4. Vector store - using Chroma db
22
+ 5. Coded the chain in two ways for my own education
23
+ a. traditional Langchain syntax - two step process of with 'stuff documents chain' and 'retrieval chain'
24
+ b. using LCEL syntax with Runnables
25
+ 6. Most processing pythonic steps implemented via a single class with modular components
26
+ that can be replaced with others (e.g., text splitter, vector store, etc.)
27
+
28
+
29
+ # Retaining the original content of the README.md for my future reference!!
30
+
31
+
32
+ # Deploying Pythonic Chat With Your Text File Application
33
+
34
+ In today's breakout rooms, we will be following the processed that you saw during the challenge - for reference, the instructions for that are available [here](https://github.com/AI-Maker-Space/Beyond-ChatGPT/tree/main).
35
+
36
+ Today, we will repeat the same process - but powered by our Pythonic RAG implementation we created last week.
37
+
38
+ 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.
39
+
40
+ ## Reference Diagram (It's Busy, but it works)
41
+
42
+ ![image](https://i.imgur.com/IaEVZG2.png)
43
+
44
+ ## Deploying the Application to Hugging Face Space
45
+
46
+ Due to the way the repository is created - it should be straightforward to deploy this to a Hugging Face Space!
47
+
48
+ > NOTE: If you wish to go through the local deployments using `chainlit run app.py` and Docker - please feel free to do so!
49
+
50
+ <details>
51
+ <summary>Creating a Hugging Face Space</summary>
52
+
53
+ 1. Navigate to the `Spaces` tab.
54
+
55
+ ![image](https://i.imgur.com/aSMlX2T.png)
56
+
57
+ 2. Click on `Create new Space`
58
+
59
+ ![image](https://i.imgur.com/YaSSy5p.png)
60
+
61
+ 3. Create the Space by providing values in the form. Make sure you've selected "Docker" as your Space SDK.
62
+
63
+ ![image](https://i.imgur.com/6h9CgH6.png)
64
+
65
+ </details>
66
+
67
+ <details>
68
+ <summary>Adding this Repository to the Newly Created Space</summary>
69
+
70
+ 1. Collect the SSH address from the newly created Space.
71
+
72
+ ![image](https://i.imgur.com/Oag0m8E.png)
73
+
74
+ > NOTE: The address is the component that starts with `[email protected]:spaces/`.
75
+
76
+ 2. Use the command:
77
+
78
+ ```bash
79
+ git remote add hf HF_SPACE_SSH_ADDRESS_HERE
80
+ ```
81
+
82
+ 3. Use the command:
83
+
84
+ ```bash
85
+ git pull hf main --no-rebase --allow-unrelated-histories -X ours
86
+ ```
87
+
88
+ 4. Use the command:
89
+
90
+ ```bash
91
+ git add .
92
+ ```
93
+
94
+ 5. Use the command:
95
+
96
+ ```bash
97
+ git commit -m "Deploying Pythonic RAG"
98
+ ```
99
+
100
+ 6. Use the command:
101
+
102
+ ```bash
103
+ git push hf main
104
+ ```
105
+
106
+ 7. The Space should automatically build as soon as the push is completed!
107
+
108
+ > NOTE: The build will fail before you complete the following steps!
109
+
110
+ </details>
111
+
112
+ <details>
113
+ <summary>Adding OpenAI Secrets to the Space</summary>
114
+
115
+ 1. Navigate to your Space settings.
116
+
117
+ ![image](https://i.imgur.com/zh0a2By.png)
118
+
119
+ 2. Navigate to `Variables and secrets` on the Settings page and click `New secret`:
120
+
121
+ ![image](https://i.imgur.com/g2KlZdz.png)
122
+
123
+ 3. In the `Name` field - input `OPENAI_API_KEY` in the `Value (private)` field, put your OpenAI API Key.
124
+
125
+ ![image](https://i.imgur.com/eFcZ8U3.png)
126
+
127
+ 4. The Space will begin rebuilding!
128
+
129
+ </details>
130
+
131
+ ## 🎉
132
+
133
+ You just deployed Pythonic RAG!
134
+
135
+ Try uploading a text file and asking some questions!
136
+
137
+ ## 🚧CHALLENGE MODE 🚧
138
+
139
+ For more of a challenge, please reference [Building a Chainlit App](./BuildingAChainlitApp.md)!
app_v1.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app_v1.py: v1 of the app
3
+
4
+ 1. allows the user to upload multiple files at runtime (upto a maximum, that is set via a paremeter)
5
+ a. user is told about the max; cl max is 10 files
6
+ b. file type can either be .txt or .pdf
7
+ c. see the use of the accept option in the cl.AskFileMessage object:
8
+ set this as: accept=["text/plain", "application/pdf"]
9
+ 2. uploaded files are processed on start:
10
+ if pdf, then first convert to text: i.e., the collection of uploaded files is converted to text if needed
11
+ text is split into chunks using langchain RecursiveCharacterTextSplitter util -
12
+ options TBD
13
+ 3. uses openai embeddings (specifically, text-embedding-3-small embeddings) to convert chunks into embeddings
14
+ note - the choice of embeddings model can be controlled via optional parameters to be passed in when
15
+ the vector db is instantiated
16
+ 4. save these embeddings in a vector db
17
+ hope to use Chroma or Qdrant
18
+ NOTES here...
19
+
20
+ 5. instantiate the RAQA (retrieval augmented qa) pipeline
21
+ use LangChain
22
+ chat memory needed
23
+
24
+ requires instantiation of an openai client session and the vector db
25
+ in addition, of course we need to set up system and user prompts
26
+ here this is set up using aimakerspace.openai.utils prompts.py module classes
27
+ 6. the cl.on_message decorator wraps the main function
28
+ this function
29
+ a. receives the query that the user types in
30
+ b. runs the RAQA pipeline
31
+ c. sends results back to UI for dislay
32
+
33
+ Additional Notes:
34
+ a. note the use of async functions and await async syntax throughout the module here!
35
+ b. note the use of yield rather than return in certain key functions
36
+ c. note the use of streaming capabilities when needed
37
+ d. the use of the python tempfile module when the user input text file is processed
38
+ (i) NamedTemporaryFile
39
+ (ii) with options to persist the storage of the temp file
40
+
41
+ """
42
+
43
+ import os
44
+ from typing import List
45
+ from dotenv import load_dotenv
46
+ import tempfile
47
+ import getpass
48
+ from uuid import uuid4
49
+ import tempfile
50
+
51
+ # chainlit imports
52
+ import chainlit as cl
53
+ from chainlit.types import AskFileResponse
54
+
55
+ # langchain imports
56
+ # document loader
57
+ from langchain_community.document_loaders import TextLoader, PyPDFLoader
58
+ # text splitter
59
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
60
+ # embeddings model to embed each chunk of text in doc
61
+ from langchain_openai import OpenAIEmbeddings
62
+ # vector store
63
+ from langchain_chroma import Chroma
64
+ # llm for text generation using prompt plus retrieved context plus query
65
+ from langchain_openai import ChatOpenAI
66
+ # templates to create custom prompts
67
+ from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
68
+ # chains
69
+ from langchain.chains import create_retrieval_chain
70
+ from langchain.chains.combine_documents import create_stuff_documents_chain
71
+ # LCEL Runnable Passthrough
72
+ from langchain_core.runnables import RunnablePassthrough
73
+ # to parse output from llm
74
+ from langchain_core.output_parsers import StrOutputParser
75
+
76
+ from langchain.docstore.document import Document
77
+
78
+ # aimakerspace imports
79
+ # from aimakerspace.text_utils import CharacterTextSplitter, TextFileLoader
80
+ # from aimakerspace.openai_utils.prompts import (
81
+ # UserRolePrompt,
82
+ # SystemRolePrompt,
83
+ # AssistantRolePrompt,
84
+ # )
85
+ # from aimakerspace.openai_utils.embedding import EmbeddingModel
86
+ # from aimakerspace.vectordatabase import VectorDatabase
87
+ # from aimakerspace.openai_utils.chatmodel import ChatOpenAI
88
+
89
+
90
+ # use getpass to load api keys at runtime
91
+ # alternative is to use load_dotenv()
92
+ # or, load secrets (eg on hf)
93
+ # os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")
94
+ load_dotenv()
95
+
96
+
97
+ # parameters to manage number of files imported via cl onstart
98
+ max_file_count = 2
99
+
100
+ # parameters to manage splitting
101
+ chunk_kwargs = {
102
+ 'chunk_size': 1000,
103
+ 'chunk_overlap': 100
104
+ }
105
+
106
+ # openai embeddings model parameters
107
+ openai_embed_kwargs = {
108
+ 'model': 'text-embedding-3-small',
109
+ # With the `text-embedding-3` class
110
+ # of models, you can specify the size
111
+ # of the embeddings you want returned.
112
+ # 'dimensions': 1024
113
+ }
114
+
115
+ # chat model parameters
116
+ chat_model_name = {
117
+ 'model_name': 'gpt-4o-mini'
118
+ }
119
+
120
+ openai_embed_kwargs = {
121
+ 'model': 'text-embedding-3-large',
122
+ # With the `text-embedding-3` class
123
+ # of models, you can specify the size
124
+ # of the embeddings you want returned.
125
+ # 'dimensions': 1024
126
+ }
127
+
128
+ retriever_kwargs = {
129
+ 'search_type': 'similarity',
130
+ 'search_kwargs': {
131
+ 'k': 20
132
+ }
133
+ }
134
+
135
+ system_prompt = (
136
+ """You are an assistant for question-answering tasks.
137
+ You will be given political speeches by leading politicians and
138
+ will be asked questions based on these speeches.
139
+
140
+ Use the following pieces of retrieved context to answer
141
+ the question.
142
+
143
+ You must answer the question only based on the context provided.
144
+
145
+ If you don't know the answer or if the context does not provide sufficient information,
146
+ then say that you don't know.
147
+
148
+ Think through your answer step-by-step.
149
+
150
+ \n\n
151
+
152
+ Context:
153
+ {context}
154
+ """
155
+ )
156
+
157
+ custom_rag_template = """\
158
+ You are an assistant for question-answering tasks.
159
+ You will be given political speeches by leading politicians and
160
+ will be asked questions based on these speeches.
161
+
162
+ Use the following pieces of retrieved context to answer
163
+ the question.
164
+
165
+ You must answer the question only based on the context provided.
166
+
167
+ If you don't know the answer or if the context does not provide sufficient information,
168
+ then say that you don't know.
169
+
170
+ Think through your answer step-by-step.
171
+
172
+ Context:
173
+ {context}
174
+
175
+ Question:
176
+ {question}
177
+
178
+ Helpful Answer:
179
+ """
180
+
181
+
182
+ class RetrievalAugmentedQAPipelineWithLangchain:
183
+ def __init__(self,
184
+ list_of_files: List[AskFileResponse],
185
+ chunk_kwargs,
186
+ embed_kwargs,
187
+ retriever_kwargs,
188
+ system_prompt,
189
+ chat_model_name,
190
+ system_prompt_template=None,
191
+ use_lcel_for_chain=False):
192
+ self.list_of_files = list_of_files
193
+ self.chunk_kwargs = chunk_kwargs
194
+ self.embed_kwargs = embed_kwargs
195
+ self.retriever_kwargs = retriever_kwargs
196
+ self.system_prompt = system_prompt
197
+ self.chat_model_name = chat_model_name
198
+ self.system_prompt_template = system_prompt_template
199
+ self.use_lcel_for_chain = use_lcel_for_chain
200
+
201
+ self._setup_text_splitter()
202
+ self._setup_embeddings()
203
+ self._setup_llm()
204
+ return
205
+
206
+ def _setup_text_splitter(self):
207
+ self.text_splitter = RecursiveCharacterTextSplitter(
208
+ add_start_index=True,
209
+ **self.chunk_kwargs
210
+ )
211
+ return self
212
+
213
+ def _setup_embeddings(self):
214
+ self.embeddings = OpenAIEmbeddings(**self.embed_kwargs)
215
+ return self
216
+
217
+ def _setup_llm(self):
218
+ self.llm = ChatOpenAI(**self.chat_model_name)
219
+ return self
220
+
221
+ def format_docs(self):
222
+ return "\n\n".join(doc.page_content for doc in self.all_splits)
223
+
224
+ def process_all_uploaded_files(self):
225
+ self.all_splits = []
226
+ for file in self.list_of_files:
227
+ # set loader depending on type of file
228
+ if file.type == "text/plain":
229
+ Loader = TextLoader
230
+ elif file.type == "application/pdf":
231
+ Loader = PyPDFLoader
232
+
233
+ import tempfile
234
+ # make temporary copy of file and split into chunks
235
+ with tempfile.NamedTemporaryFile() as tempfile:
236
+ tempfile.write(file.content)
237
+ loader = Loader(tempfile.name)
238
+ documents = loader.load()
239
+ splits = self.text_splitter.split_documents(documents)
240
+ for i, split in enumerate(splits):
241
+ split.metadata["source"] = f"{file.name}_source_{i}"
242
+ self.all_splits.extend(splits)
243
+ return self
244
+
245
+ def make_chroma_vector_db(self):
246
+ # initialize vector store
247
+ vectorstore = Chroma.from_documents(documents=self.all_splits, embedding=self.embeddings)
248
+ self.retriever = vectorstore.as_retriever(**self.retriever_kwargs)
249
+ return self
250
+
251
+ def setup_chat_prompt_from_messages(self):
252
+ self.chat_prompt = ChatPromptTemplate.from_messages(
253
+ [
254
+ ("system", self.system_prompt),
255
+ ("human", "{input}"),
256
+ ]
257
+ )
258
+ return self
259
+
260
+ def qa_chain(self):
261
+ self.question_answer_chain = create_stuff_documents_chain(self.llm, self.chat_prompt)
262
+ return self
263
+
264
+ def rag_chain(self):
265
+ self.rag_chain = create_retrieval_chain(self.retriever, self.question_answer_chain)
266
+ return self
267
+
268
+ def setup_prompt_from_template(self):
269
+ self.prompt_from_template = PromptTemplate.from_template(self.system_prompt_template)
270
+ return self
271
+
272
+ def lcel_rag_chain(self):
273
+ self.rag_chain = (
274
+ {"context": self.retriever | self.format_docs, "question": RunnablePassthrough()}
275
+ | self.prompt_from_template
276
+ | self.llm
277
+ | StrOutputParser()
278
+ )
279
+
280
+ def make_raqa_pipeline(self):
281
+ # load all docs uploaded by user, convert into text if needed and split into chunks
282
+ self.process_all_uploaded_files()
283
+
284
+ # load all splits and embeddings into vector db
285
+ self.make_chroma_vector_db()
286
+
287
+ if self.use_lcel_for_chain is False:
288
+ self.setup_chat_prompt_from_messages()
289
+ self.qa_chain()
290
+ self.rag_chain()
291
+ else:
292
+ self.setup_prompt_from_template()
293
+ self.lcel_rag_chain()
294
+ return self.rag_chain
295
+
296
+
297
+ @cl.on_chat_start
298
+ async def on_chat_start():
299
+ files = None
300
+
301
+ # Wait for the user to upload one or more files
302
+ user_input_files = []
303
+ filecount = 0
304
+ user_signals_done = False
305
+ while filecount < max_file_count and user_signals_done is False:
306
+ # while files == None:
307
+ files = await cl.AskFileMessage(
308
+ content=f"Please upload {max_file_count} text files or pdf documents to begin!",
309
+ accept=["text/plain", "application/pdf"],
310
+ max_size_mb=20,
311
+ max_files=2,
312
+ timeout=180,
313
+ ).send()
314
+
315
+ if files:
316
+ user_input_files.append(files[0])
317
+ filecount += 1
318
+ else:
319
+ user_signals_done = True
320
+
321
+ user_input_file_names = [x.name for x in user_input_files]
322
+
323
+ msg = cl.Message(
324
+ content=f"Processing `{user_input_file_names}`...", disable_human_feedback=True
325
+ )
326
+ await msg.send()
327
+
328
+ # instantiate raqa pipeline object
329
+ qabot = RetrievalAugmentedQAPipelineWithLangchain(
330
+ list_of_files=user_input_files,
331
+ chunk_kwargs=chunk_kwargs,
332
+ embed_kwargs=openai_embed_kwargs,
333
+ retriever_kwargs=retriever_kwargs,
334
+ system_prompt=system_prompt,
335
+ chat_model_name=chat_model_name
336
+ )
337
+
338
+ raqa_chain = qabot.make_raqa_pipeline()
339
+
340
+ # Let the user know that the system is ready
341
+ msg.content = f"Processing `{user_input_file_names}` done. You can now ask questions!"
342
+ await msg.update()
343
+
344
+ cl.user_session.set("raqa_chain", raqa_chain)
345
+
346
+
347
+ @cl.on_message
348
+ async def main(message):
349
+ raqa_chain = cl.user_session.get("raqa_chain")
350
+
351
+ msg = cl.Message(content="")
352
+
353
+ # result = await raqa_chain.invoke({"input": message.content})
354
+ result = await cl.make_async(raqa_chain.invoke)({"input": message.content})
355
+
356
+ # async for stream_resp in result["answer"]:
357
+ for stream_resp in result["answer"]:
358
+ await msg.stream_token(stream_resp)
359
+
360
+ await msg.send()
chainlit.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Welcome to Chat with Your Uploaded Files!!
2
+
3
+ This is my completed pythonic RAG assignment, completed for Session 3 of the AI Engineering Cohort 4.
4
+
5
+ With this application, you can chat with TWO uploaded text or pdf fileis that is smaller than 20MB!
6
+
7
+ App features:
8
+ 1. Allow user to upload TWO documents (instead of a single document)
9
+ 2. Format of doc: they can be either text files or pdf docs.
10
+
11
+ Code features:
12
+ 1. Text splitter - RecursiveTextSplitter from Langchain
13
+ 2. Vector store - using Chroma db
14
+ 3. Coded the chain in two ways for my own education
15
+ a. traditional Langchain syntax - two step process of with 'stuff documents chain' and 'retrieval chain'
16
+ b. using LCEL syntax with Runnables
17
+ 4. Most processing pythonic steps implemented via a single class with modular components
18
+ that can be replaced with others (e.g., text splitter, vector store, etc.)
19
+
20
+
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ numpy
2
+ chainlit==0.7.700
3
+ openai
4
+ langchain
5
+ langchain_community
6
+ langchain_chroma
7
+ langchain-openai