kcheng0816 commited on
Commit
abc3ae0
·
1 Parent(s): 225a649

Add Assignment15

Browse files
Files changed (6) hide show
  1. Dockerfile +29 -0
  2. README.md +1 -1
  3. app.py +203 -0
  4. data/paul_graham_essays.txt +0 -0
  5. pyproject.toml +22 -0
  6. uv.lock +0 -0
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
@@ -8,4 +8,4 @@ pinned: false
8
  short_description: AIE5 15 Assignment
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
8
  short_description: AIE5 15 Assignment
9
  ---
10
 
11
+ open-source LLM-powered Retrieval Augmented Generation Application with LangChain 🎉🤖
app.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import chainlit as cl
3
+ from dotenv import load_dotenv
4
+ from langchain_community.document_loaders import TextLoader
5
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
6
+ from operator import itemgetter
7
+ from langchain_huggingface import HuggingFaceEndpoint
8
+ from langchain_community.document_loaders import TextLoader
9
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
10
+ from langchain_community.vectorstores import FAISS
11
+ from langchain_huggingface import HuggingFaceEndpointEmbeddings
12
+ from langchain_core.prompts import PromptTemplate
13
+ from langchain.schema.output_parser import StrOutputParser
14
+ from langchain.schema.runnable import RunnablePassthrough
15
+ from langchain.schema.runnable.config import RunnableConfig
16
+ from tqdm.asyncio import tqdm_asyncio
17
+ import asyncio
18
+ from tqdm.asyncio import tqdm
19
+
20
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
21
+ # ---- ENV VARIABLES ---- #
22
+ """
23
+ This function will load our environment file (.env) if it is present.
24
+
25
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
26
+ """
27
+ load_dotenv()
28
+
29
+ """
30
+ We will load our environment variables here.
31
+ """
32
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
33
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
34
+ HF_TOKEN = os.environ["HF_TOKEN"]
35
+
36
+ # ---- GLOBAL DECLARATIONS ---- #
37
+
38
+ # -- RETRIEVAL -- #
39
+ """
40
+ 1. Load Documents from Text File
41
+ 2. Split Documents into Chunks
42
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
43
+ 4. Index Files if they do not exist, otherwise load the vectorstore
44
+ """
45
+ ### 1. CREATE TEXT LOADER AND LOAD DOCUMENTS
46
+ ### NOTE: PAY ATTENTION TO THE PATH THEY ARE IN.
47
+ document_loader = TextLoader("./data/paul_graham_essays.txt")
48
+ documents = document_loader.load()
49
+
50
+ ### 2. CREATE TEXT SPLITTER AND SPLIT DOCUMENTS
51
+ text_splitter = RecursiveCharacterTextSplitter(
52
+ chunk_size = 1000,
53
+ chunk_overlap = 30
54
+ )
55
+ split_documents = text_splitter.split_documents(document_loader.load())
56
+
57
+ ### 3. LOAD HUGGINGFACE EMBEDDINGS
58
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
59
+ model=HF_EMBED_ENDPOINT,
60
+ task="feature-extraction",
61
+ huggingfacehub_api_token=HF_TOKEN,
62
+ )
63
+
64
+ async def add_documents_async(vectorstore, documents):
65
+ await vectorstore.aadd_documents(documents)
66
+
67
+ async def process_batch(vectorstore, batch, is_first_batch, pbar):
68
+ if is_first_batch:
69
+ result = await FAISS.afrom_documents(batch, hf_embeddings)
70
+ else:
71
+ await add_documents_async(vectorstore, batch)
72
+ result = vectorstore
73
+ pbar.update(len(batch))
74
+ return result
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] for i in range(0, len(split_documents), batch_size)]
83
+
84
+ async def process_all_batches():
85
+ nonlocal vectorstore
86
+ tasks = []
87
+ pbars = []
88
+
89
+ for i, batch in enumerate(batches):
90
+ pbar = tqdm(total=len(batch), desc=f"Batch {i+1}/{len(batches)}", position=i)
91
+ pbars.append(pbar)
92
+
93
+ if i == 0:
94
+ vectorstore = await process_batch(None, batch, True, pbar)
95
+ else:
96
+ tasks.append(process_batch(vectorstore, batch, False, pbar))
97
+
98
+ if tasks:
99
+ await asyncio.gather(*tasks)
100
+
101
+ for pbar in pbars:
102
+ pbar.close()
103
+
104
+ await process_all_batches()
105
+
106
+ hf_retriever = vectorstore.as_retriever()
107
+ print("\nIndexing complete. Vectorstore is ready for use.")
108
+ return hf_retriever
109
+
110
+ async def run():
111
+ retriever = await main()
112
+ return retriever
113
+
114
+ hf_retriever = asyncio.run(run())
115
+
116
+ # -- AUGMENTED -- #
117
+ """
118
+ 1. Define a String Template
119
+ 2. Create a Prompt Template from the String Template
120
+ """
121
+ ### 1. DEFINE STRING TEMPLATE
122
+ RAG_PROMPT_TEMPLATE = """\
123
+ <|start_header_id|>system<|end_header_id|>
124
+ 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|>
125
+
126
+ <|start_header_id|>user<|end_header_id|>
127
+ User Query:
128
+ {query}
129
+
130
+ Context:
131
+ {context}<|eot_id|>
132
+
133
+ <|start_header_id|>assistant<|end_header_id|>
134
+ """
135
+
136
+ ### 2. CREATE PROMPT TEMPLATE
137
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
138
+
139
+ # -- GENERATION -- #
140
+ """
141
+ 1. Create a HuggingFaceEndpoint for the LLM
142
+ """
143
+ ### 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
144
+ hf_llm = HuggingFaceEndpoint(
145
+ endpoint_url=HF_LLM_ENDPOINT,
146
+ max_new_tokens=512,
147
+ top_k=10,
148
+ top_p=0.95,
149
+ temperature=0.3,
150
+ repetition_penalty=1.15,
151
+ huggingfacehub_api_token=HF_TOKEN,
152
+ )
153
+
154
+ @cl.author_rename
155
+ def rename(original_author: str):
156
+ """
157
+ This function can be used to rename the 'author' of a message.
158
+
159
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
160
+ """
161
+ rename_dict = {
162
+ "Assistant" : "Paul Graham Essay Bot"
163
+ }
164
+ return rename_dict.get(original_author, original_author)
165
+
166
+ @cl.on_chat_start
167
+ async def start_chat():
168
+ """
169
+ This function will be called at the start of every user session.
170
+
171
+ We will build our LCEL RAG chain here, and store it in the user session.
172
+
173
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
174
+ """
175
+
176
+ ### BUILD LCEL RAG CHAIN THAT ONLY RETURNS TEXT
177
+ lcel_rag_chain = (
178
+ {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
179
+ | rag_prompt | hf_llm
180
+ )
181
+
182
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
183
+
184
+ @cl.on_message
185
+ async def main(message: cl.Message):
186
+ """
187
+ This function will be called every time a message is recieved from a session.
188
+
189
+ We will use the LCEL RAG chain to generate a response to the user query.
190
+
191
+ 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.
192
+ """
193
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
194
+
195
+ msg = cl.Message(content="")
196
+
197
+ async for chunk in lcel_rag_chain.astream(
198
+ {"query": message.content},
199
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
200
+ ):
201
+ await msg.stream_token(chunk)
202
+
203
+ await msg.send()
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
+ ]
uv.lock ADDED
The diff for this file is too large to render. See raw diff