drewgenai commited on
Commit
54eae24
·
1 Parent(s): 2f6eab6

initial commit

Browse files
Files changed (7) hide show
  1. .gitignore +7 -0
  2. Dockerfile +29 -0
  3. app.py +185 -0
  4. chainlit.md +2 -0
  5. data/paul_graham_essays.txt +0 -0
  6. pyproject.toml +22 -0
  7. uv.lock +0 -0
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ .chainlit
4
+ *.faiss
5
+ *.pkl
6
+ .files
7
+ .venv
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", "app.py", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ load_dotenv()
19
+
20
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
21
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
22
+ HF_TOKEN = os.environ["HF_TOKEN"]
23
+
24
+ if not all([HF_LLM_ENDPOINT, HF_EMBED_ENDPOINT, HF_TOKEN]):
25
+ raise ValueError("Missing required Hugging Face API environment variables.")
26
+
27
+ if not os.path.exists("./data/paul_graham_essays.txt"):
28
+ raise FileNotFoundError("The specified document file is missing.")
29
+
30
+
31
+ document_loader = TextLoader("./data/paul_graham_essays.txt")
32
+ documents = document_loader.load()
33
+
34
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
35
+ split_documents = text_splitter.split_documents(documents)
36
+
37
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
38
+ model=HF_EMBED_ENDPOINT,
39
+ task="feature-extraction",
40
+ huggingfacehub_api_token=HF_TOKEN,
41
+ )
42
+
43
+ async def add_documents_async(vectorstore, documents):
44
+ await vectorstore.aadd_documents(documents)
45
+
46
+ async def process_batch(vectorstore, batch, is_first_batch, pbar):
47
+ if is_first_batch:
48
+ result = await FAISS.afrom_documents(batch, hf_embeddings)
49
+ else:
50
+ await add_documents_async(vectorstore, batch)
51
+ result = vectorstore
52
+ pbar.update(len(batch))
53
+ return result
54
+
55
+ async def main():
56
+ print("Indexing Files")
57
+
58
+ vectorstore = None
59
+ batch_size = 32
60
+
61
+ batches = [split_documents[i:i+batch_size] for i in range(0, len(split_documents), batch_size)]
62
+
63
+ async def process_all_batches():
64
+ nonlocal vectorstore
65
+ tasks = []
66
+ pbars = []
67
+
68
+ for i, batch in enumerate(batches):
69
+ pbar = tqdm(total=len(batch), desc=f"Batch {i+1}/{len(batches)}", position=i)
70
+ pbars.append(pbar)
71
+
72
+ if i == 0:
73
+ vectorstore = await process_batch(None, batch, True, pbar)
74
+ else:
75
+ tasks.append(process_batch(vectorstore, batch, False, pbar))
76
+
77
+ if tasks:
78
+ await asyncio.gather(*tasks)
79
+
80
+ for pbar in pbars:
81
+ pbar.close()
82
+
83
+ await process_all_batches()
84
+
85
+ hf_retriever = vectorstore.as_retriever()
86
+ print("\nIndexing complete. Vectorstore is ready for use.")
87
+ return hf_retriever
88
+
89
+ async def run():
90
+ retriever = await main()
91
+ return retriever
92
+
93
+ hf_retriever = asyncio.run(run())
94
+
95
+
96
+ RAG_PROMPT_TEMPLATE = """\
97
+ <|start_header_id|>system<|end_header_id|>
98
+ 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|>
99
+
100
+ <|start_header_id|>user<|end_header_id|>
101
+ User Query:
102
+ {query}
103
+
104
+ Context:
105
+ {context}<|eot_id|>
106
+
107
+ <|start_header_id|>assistant<|end_header_id|>
108
+ """
109
+
110
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
111
+
112
+
113
+ ### 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
114
+ hf_llm = HuggingFaceEndpoint(
115
+ endpoint_url=HF_LLM_ENDPOINT,
116
+ max_new_tokens=512,
117
+ top_k=10,
118
+ top_p=0.95,
119
+ temperature=0.3,
120
+ repetition_penalty=1.15,
121
+ huggingfacehub_api_token=HF_TOKEN,
122
+ )
123
+
124
+ @cl.author_rename
125
+ def rename(original_author: str):
126
+ """
127
+ This function can be used to rename the 'author' of a message.
128
+
129
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
130
+ """
131
+ rename_dict = {
132
+ "Assistant" : "Paul Graham Essay Bot"
133
+ }
134
+ return rename_dict.get(original_author, original_author)
135
+
136
+ @cl.on_chat_start
137
+ async def start_chat():
138
+ """
139
+ This function will be called at the start of every user session.
140
+
141
+ We will build our LCEL RAG chain here, and store it in the user session.
142
+
143
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
144
+ """
145
+
146
+ ### BUILD LCEL RAG CHAIN THAT ONLY RETURNS TEXT
147
+ lcel_rag_chain = (
148
+ {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
149
+ | rag_prompt | hf_llm
150
+ )
151
+
152
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
153
+ await cl.Message(content="Welcome to the Paul Graham Essay Bot! Ask me anything about Paul Graham's essays.").send()
154
+
155
+ @cl.on_message
156
+ async def main(message: cl.Message):
157
+ """
158
+ This function will be called every time a message is received from a session.
159
+
160
+ We will use the LCEL RAG chain to generate a response to the user query.
161
+
162
+ 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.
163
+ """
164
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
165
+
166
+ msg = cl.Message(content="")
167
+
168
+ # Create a buffer to store the complete response
169
+ complete_response = ""
170
+
171
+ async for chunk in lcel_rag_chain.astream(
172
+ {"query": message.content},
173
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
174
+ ):
175
+ # Clean the chunk of any <|eot_id|> tokens
176
+ clean_chunk = chunk.replace("<|eot_id|>", "")
177
+ complete_response += chunk # Store original for final cleaning
178
+ await msg.stream_token(clean_chunk)
179
+
180
+ # If <|eot_id|> appears at the end of the complete response, remove it
181
+ if complete_response.endswith("<|eot_id|>"):
182
+ # Update the final message content without the token
183
+ await msg.update(content=complete_response.replace("<|eot_id|>", ""))
184
+
185
+ await msg.send()
chainlit.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Paul Graham Essay Bot
2
+ Welcome to the Paul Graham Essay Bot, a retrieval-augmented generation (RAG) chatbot powered by Hugging Face and FAISS vector search.
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