kenny commited on
Commit
4f49129
·
1 Parent(s): 1a54ac2

Create app

Browse files
Files changed (10) hide show
  1. .env.sample +5 -0
  2. .gitignore +6 -0
  3. Dockerfile +29 -0
  4. README.md +4 -7
  5. app.py +241 -0
  6. chainlit.md +1 -0
  7. data/paul_graham_essays.txt +0 -0
  8. pyproject.toml +22 -0
  9. solution_app.py +190 -0
  10. uv.lock +0 -0
.env.sample ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # !!! DO NOT UPDATE THIS FILE DIRECTLY. MAKE A COPY AND RENAME IT `.env` TO PROCEED !!! #
2
+ HF_LLM_ENDPOINT="YOUR_LLM_ENDPOINT_URL_HERE"
3
+ HF_EMBED_ENDPOINT="YOUR_EMBED_MODEL_ENDPOINT_URL_HERE"
4
+ HF_TOKEN="YOUR_HF_TOKEN_HERE"
5
+ # !!! DO NOT UPDATE THIS FILE DIRECTLY. MAKE A COPY AND RENAME IT `.env` TO PROCEED !!! #
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ .chainlit
4
+ *.faiss
5
+ *.pkl
6
+ .files
Dockerfile ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Get a distribution that has uv already installed
2
+ FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim
3
+
4
+ # Add user - this is the user that will run the app
5
+ # If you do not set user, the app will run as root (undesirable)
6
+ RUN useradd -m -u 1000 user
7
+ USER user
8
+
9
+ # Set the home directory and path
10
+ ENV HOME=/home/user \
11
+ PATH=/home/user/.local/bin:$PATH
12
+
13
+ ENV UVICORN_WS_PROTOCOL=websockets
14
+
15
+ # Set the working directory
16
+ WORKDIR $HOME/app
17
+
18
+ # Copy the app to the container
19
+ COPY --chown=user . $HOME/app
20
+
21
+ # Install the dependencies
22
+ # RUN uv sync --frozen
23
+ RUN uv sync
24
+
25
+ # Expose the port
26
+ EXPOSE 7860
27
+
28
+ # Run the app
29
+ CMD ["uv", "run", "chainlit", "run", "solution_app.py", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,11 +1,8 @@
1
  ---
2
- title: Open Source Embeddings
3
- emoji: 🌖
4
- colorFrom: blue
5
  colorTo: red
6
  sdk: docker
7
  pinned: false
8
- short_description: A chainlit app using open source embeddings
9
- ---
10
-
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Demo For Session 15
3
+ emoji: 🐢
4
+ colorFrom: yellow
5
  colorTo: red
6
  sdk: docker
7
  pinned: false
8
+ ---
 
 
 
app.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from tqdm.asyncio import tqdm_asyncio
15
+ import asyncio
16
+ from tqdm.asyncio import tqdm
17
+
18
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
19
+ # ---- ENV VARIABLES ---- #
20
+ """
21
+ This function will load our environment file (.env) if it is present.
22
+
23
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
24
+ """
25
+ load_dotenv()
26
+
27
+ """
28
+ We will load our environment variables here.
29
+ """
30
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
31
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
32
+ HF_TOKEN = os.environ["HF_TOKEN"]
33
+
34
+ # ---- GLOBAL DECLARATIONS ---- #
35
+
36
+ # -- RETRIEVAL -- #
37
+ """
38
+ 1. Load Documents from Text File
39
+ 2. Split Documents into Chunks
40
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
41
+ 4. Index Files if they do not exist, otherwise load the vectorstore
42
+ """
43
+ # 1. CREATE TEXT LOADER AND LOAD DOCUMENTS
44
+ # NOTE: PAY ATTENTION TO THE PATH THEY ARE IN.
45
+ text_loader = TextLoader("./data/paul_graham_essays.txt")
46
+ documents = text_loader.load()
47
+
48
+ # 2. CREATE TEXT SPLITTER AND SPLIT DOCUMENTS
49
+ text_splitter = RecursiveCharacterTextSplitter(
50
+ chunk_size=1000, chunk_overlap=30)
51
+ split_documents = text_splitter.split_documents(documents)
52
+ len(split_documents)
53
+
54
+ # 3. LOAD HUGGINGFACE EMBEDDINGS
55
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
56
+ model=HF_EMBED_ENDPOINT,
57
+ task="feature-extraction",
58
+ huggingfacehub_api_token=HF_TOKEN,
59
+ )
60
+
61
+
62
+ async def add_documents_async(vectorstore, documents):
63
+ await vectorstore.aadd_documents(documents)
64
+
65
+
66
+ async def process_batch(vectorstore, batch, is_first_batch, pbar):
67
+ if is_first_batch:
68
+ result = await FAISS.afrom_documents(batch, hf_embeddings)
69
+ else:
70
+ await add_documents_async(vectorstore, batch)
71
+ result = vectorstore
72
+ pbar.update(len(batch))
73
+ return result
74
+
75
+
76
+ async def main():
77
+ print("Indexing Files")
78
+
79
+ vectorstore = None
80
+ batch_size = 32
81
+
82
+ batches = [split_documents[i:i+batch_size]
83
+ for i in range(0, len(split_documents), batch_size)]
84
+
85
+ async def process_all_batches():
86
+ nonlocal vectorstore
87
+ tasks = []
88
+ pbars = []
89
+
90
+ for i, batch in enumerate(batches):
91
+ pbar = tqdm(total=len(batch),
92
+ desc=f"Batch {i+1}/{len(batches)}", position=i)
93
+ pbars.append(pbar)
94
+
95
+ if i == 0:
96
+ vectorstore = await process_batch(None, batch, True, pbar)
97
+ else:
98
+ tasks.append(process_batch(vectorstore, batch, False, pbar))
99
+
100
+ if tasks:
101
+ await asyncio.gather(*tasks)
102
+
103
+ for pbar in pbars:
104
+ pbar.close()
105
+
106
+ await process_all_batches()
107
+
108
+ hf_retriever = vectorstore.as_retriever()
109
+ print("\nIndexing complete. Vectorstore is ready for use.")
110
+ return hf_retriever
111
+
112
+
113
+ async def run():
114
+ retriever = await main()
115
+ return retriever
116
+
117
+ hf_retriever = asyncio.run(run())
118
+
119
+ # -- AUGMENTED -- #
120
+ """
121
+ 1. Define a String Template
122
+ 2. Create a Prompt Template from the String Template
123
+ """
124
+ # 1. DEFINE STRING TEMPLATE
125
+ RAG_PROMPT_TEMPLATE = """\
126
+ <|start_header_id|>system<|end_header_id|>
127
+ 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|>
128
+
129
+ <|start_header_id|>user<|end_header_id|>
130
+ User Query:
131
+ {query}
132
+
133
+ Context:
134
+ {context}<|eot_id|>
135
+
136
+ <|start_header_id|>assistant<|end_header_id|>
137
+ """
138
+
139
+ # 2. CREATE PROMPT TEMPLATE
140
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
141
+
142
+ # -- GENERATION -- #
143
+ """
144
+ 1. Create a HuggingFaceEndpoint for the LLM
145
+ """
146
+ # 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
147
+ hf_llm = HuggingFaceEndpoint(
148
+ endpoint_url=f"{HF_LLM_ENDPOINT}",
149
+ task="text-generation",
150
+ max_new_tokens=512,
151
+ top_k=10,
152
+ top_p=0.95,
153
+ typical_p=0.95,
154
+ temperature=0.01,
155
+ repetition_penalty=1.03,
156
+ stop_sequences=["<|eot_id|>"]
157
+ )
158
+
159
+
160
+ @cl.author_rename
161
+ def rename(original_author: str):
162
+ """
163
+ This function can be used to rename the 'author' of a message.
164
+
165
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
166
+ """
167
+ rename_dict = {
168
+ "Assistant": "Paul Graham Essay Bot"
169
+ }
170
+ return rename_dict.get(original_author, original_author)
171
+
172
+
173
+ @cl.on_chat_start
174
+ async def start_chat():
175
+ """
176
+ This function will be called at the start of every user session.
177
+
178
+ We will build our LCEL RAG chain here, and store it in the user session.
179
+
180
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
181
+ """
182
+
183
+ # Store the retriever in the user session
184
+ cl.user_session.set("hf_retriever", hf_retriever)
185
+
186
+ # BUILD LCEL RAG CHAIN WITH RETRIEVAL
187
+ async def get_context(query_dict):
188
+ docs = await hf_retriever.aget_relevant_documents(query_dict["query"])
189
+ return {"context": "\n\n".join([doc.page_content for doc in docs]), "query": query_dict["query"]}
190
+
191
+ # Post-processing to clean up any token markers
192
+ def clean_output(text):
193
+ return text.replace("<|eot_id|>", "").strip()
194
+
195
+ # Store individual components
196
+ cl.user_session.set("get_context", get_context)
197
+ cl.user_session.set("rag_prompt", rag_prompt)
198
+ cl.user_session.set("llm", hf_llm)
199
+
200
+ # Also store the full chain for non-streaming use cases
201
+ lcel_rag_chain = (
202
+ get_context
203
+ | rag_prompt
204
+ | hf_llm
205
+ | StrOutputParser()
206
+ | clean_output
207
+ )
208
+
209
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
210
+
211
+
212
+ @cl.on_message
213
+ async def main(message: cl.Message):
214
+ """
215
+ This function will be called every time a message is recieved from a session.
216
+
217
+ We will use the LCEL RAG chain to generate a response to the user query.
218
+
219
+ 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.
220
+ """
221
+ # Get the chain without the clean_output step
222
+ get_context = cl.user_session.get("get_context")
223
+ rag_prompt_template = cl.user_session.get("rag_prompt")
224
+ llm = cl.user_session.get("llm")
225
+
226
+ # Create a streaming chain
227
+ streaming_chain = get_context | rag_prompt_template | llm
228
+
229
+ msg = cl.Message(content="")
230
+
231
+ # Stream and clean tokens on the fly
232
+ async for chunk in streaming_chain.astream(
233
+ {"query": message.content},
234
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
235
+ ):
236
+ # Clean the chunk before streaming it
237
+ cleaned_chunk = chunk.replace("<|eot_id|>", "")
238
+ if cleaned_chunk.strip(): # Only stream non-empty chunks
239
+ await msg.stream_token(cleaned_chunk)
240
+
241
+ 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
 
pyproject.toml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "15-app"
3
+ version = "0.1.0"
4
+ description = "Session 15 - Open Source Endpoints"
5
+ readme = "README.md"
6
+ requires-python = ">=3.09"
7
+ dependencies = [
8
+ "asyncio===3.4.3",
9
+ "chainlit==2.2.1",
10
+ "huggingface-hub==0.27.0",
11
+ "langchain-huggingface==0.1.2",
12
+ "langchain==0.3.19",
13
+ "langchain-community==0.3.18",
14
+ "langsmith==0.3.11",
15
+ "python-dotenv==1.0.1",
16
+ "tqdm==4.67.1",
17
+ "langchain-openai==0.3.7",
18
+ "langchain-text-splitters==0.3.6",
19
+ "jupyter>=1.1.1",
20
+ "faiss-cpu>=1.10.0",
21
+ "websockets>=15.0",
22
+ ]
solution_app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from tqdm.asyncio import tqdm_asyncio
15
+ import asyncio
16
+ from tqdm.asyncio import tqdm
17
+
18
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
19
+ # ---- ENV VARIABLES ---- #
20
+ """
21
+ This function will load our environment file (.env) if it is present.
22
+
23
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
24
+ """
25
+ load_dotenv()
26
+
27
+ """
28
+ We will load our environment variables here.
29
+ """
30
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
31
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
32
+ HF_TOKEN = os.environ["HF_TOKEN"]
33
+
34
+ # ---- GLOBAL DECLARATIONS ---- #
35
+
36
+ # -- RETRIEVAL -- #
37
+ """
38
+ 1. Load Documents from Text File
39
+ 2. Split Documents into Chunks
40
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
41
+ 4. Index Files if they do not exist, otherwise load the vectorstore
42
+ """
43
+ document_loader = TextLoader("./data/paul_graham_essays.txt")
44
+ documents = document_loader.load()
45
+
46
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
47
+ split_documents = text_splitter.split_documents(documents)
48
+
49
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
50
+ model=HF_EMBED_ENDPOINT,
51
+ task="feature-extraction",
52
+ huggingfacehub_api_token=HF_TOKEN,
53
+ )
54
+
55
+ async def add_documents_async(vectorstore, documents):
56
+ await vectorstore.aadd_documents(documents)
57
+
58
+ async def process_batch(vectorstore, batch, is_first_batch, pbar):
59
+ if is_first_batch:
60
+ result = await FAISS.afrom_documents(batch, hf_embeddings)
61
+ else:
62
+ await add_documents_async(vectorstore, batch)
63
+ result = vectorstore
64
+ pbar.update(len(batch))
65
+ return result
66
+
67
+ async def main():
68
+ print("Indexing Files")
69
+
70
+ vectorstore = None
71
+ batch_size = 32
72
+
73
+ batches = [split_documents[i:i+batch_size] for i in range(0, len(split_documents), batch_size)]
74
+
75
+ async def process_all_batches():
76
+ nonlocal vectorstore
77
+ tasks = []
78
+ pbars = []
79
+
80
+ for i, batch in enumerate(batches):
81
+ pbar = tqdm(total=len(batch), desc=f"Batch {i+1}/{len(batches)}", position=i)
82
+ pbars.append(pbar)
83
+
84
+ if i == 0:
85
+ vectorstore = await process_batch(None, batch, True, pbar)
86
+ else:
87
+ tasks.append(process_batch(vectorstore, batch, False, pbar))
88
+
89
+ if tasks:
90
+ await asyncio.gather(*tasks)
91
+
92
+ for pbar in pbars:
93
+ pbar.close()
94
+
95
+ await process_all_batches()
96
+
97
+ hf_retriever = vectorstore.as_retriever()
98
+ print("\nIndexing complete. Vectorstore is ready for use.")
99
+ return hf_retriever
100
+
101
+ async def run():
102
+ retriever = await main()
103
+ return retriever
104
+
105
+ hf_retriever = asyncio.run(run())
106
+
107
+ # -- AUGMENTED -- #
108
+ """
109
+ 1. Define a String Template
110
+ 2. Create a Prompt Template from the String Template
111
+ """
112
+ RAG_PROMPT_TEMPLATE = """\
113
+ <|start_header_id|>system<|end_header_id|>
114
+ 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|>
115
+
116
+ <|start_header_id|>user<|end_header_id|>
117
+ User Query:
118
+ {query}
119
+
120
+ Context:
121
+ {context}<|eot_id|>
122
+
123
+ <|start_header_id|>assistant<|end_header_id|>
124
+ """
125
+
126
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
127
+
128
+ # -- GENERATION -- #
129
+ """
130
+ 1. Create a HuggingFaceEndpoint for the LLM
131
+ """
132
+ hf_llm = HuggingFaceEndpoint(
133
+ endpoint_url=HF_LLM_ENDPOINT,
134
+ max_new_tokens=512,
135
+ top_k=10,
136
+ top_p=0.95,
137
+ temperature=0.3,
138
+ repetition_penalty=1.15,
139
+ huggingfacehub_api_token=HF_TOKEN,
140
+ )
141
+
142
+ @cl.author_rename
143
+ def rename(original_author: str):
144
+ """
145
+ This function can be used to rename the 'author' of a message.
146
+
147
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
148
+ """
149
+ rename_dict = {
150
+ "Assistant" : "Paul Graham Essay Bot"
151
+ }
152
+ return rename_dict.get(original_author, original_author)
153
+
154
+ @cl.on_chat_start
155
+ async def start_chat():
156
+ """
157
+ This function will be called at the start of every user session.
158
+
159
+ We will build our LCEL RAG chain here, and store it in the user session.
160
+
161
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
162
+ """
163
+
164
+ lcel_rag_chain = (
165
+ {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
166
+ | rag_prompt | hf_llm
167
+ )
168
+
169
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
170
+
171
+ @cl.on_message
172
+ async def main(message: cl.Message):
173
+ """
174
+ This function will be called every time a message is recieved from a session.
175
+
176
+ We will use the LCEL RAG chain to generate a response to the user query.
177
+
178
+ 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.
179
+ """
180
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
181
+
182
+ msg = cl.Message(content="")
183
+
184
+ for chunk in await cl.make_async(lcel_rag_chain.stream)(
185
+ {"query": message.content},
186
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
187
+ ):
188
+ await msg.stream_token(chunk)
189
+
190
+ await msg.send()
uv.lock ADDED
The diff for this file is too large to render. See raw diff