Upload 5 files
Browse files- app.py +327 -0
- indexing.py +106 -0
- prompt_template.json +5 -0
- requirements.txt +19 -0
- retrieval.py +108 -0
app.py
ADDED
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
PDF-based chatbot with Retrieval-Augmented Generation
|
3 |
+
"""
|
4 |
+
|
5 |
+
import os
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
from dotenv import load_dotenv
|
9 |
+
|
10 |
+
import indexing
|
11 |
+
import retrieval
|
12 |
+
|
13 |
+
|
14 |
+
# default_persist_directory = './chroma_HF/'
|
15 |
+
list_llm = [
|
16 |
+
"mistralai/Mistral-7B-Instruct-v0.3",
|
17 |
+
"microsoft/Phi-3.5-mini-instruct",
|
18 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
19 |
+
"meta-llama/Llama-3.2-3B-Instruct",
|
20 |
+
"meta-llama/Llama-3.2-1B-Instruct",
|
21 |
+
"HuggingFaceTB/SmolLM2-1.7B-Instruct",
|
22 |
+
"HuggingFaceH4/zephyr-7b-beta",
|
23 |
+
"HuggingFaceH4/zephyr-7b-gemma-v0.1",
|
24 |
+
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
25 |
+
"google/gemma-2-2b-it",
|
26 |
+
"google/gemma-2-9b-it",
|
27 |
+
"Qwen/Qwen2.5-1.5B-Instruct",
|
28 |
+
"Qwen/Qwen2.5-3B-Instruct",
|
29 |
+
"Qwen/Qwen2.5-7B-Instruct",
|
30 |
+
]
|
31 |
+
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
32 |
+
|
33 |
+
|
34 |
+
# Load environment file - HuggingFace API key
|
35 |
+
def retrieve_api():
|
36 |
+
"""Retrieve HuggingFace API Key"""
|
37 |
+
_ = load_dotenv()
|
38 |
+
global huggingfacehub_api_token
|
39 |
+
huggingfacehub_api_token = os.environ.get("HUGGINGFACE_API_KEY")
|
40 |
+
|
41 |
+
|
42 |
+
# Initialize database
|
43 |
+
def initialize_database(list_file_obj, db_type, chunk_size, chunk_overlap, progress=gr.Progress()):
|
44 |
+
"""Initialize database"""
|
45 |
+
|
46 |
+
# Create list of documents (when valid)
|
47 |
+
list_file_path = [x.name for x in list_file_obj if x is not None]
|
48 |
+
|
49 |
+
# Create collection_name for vector database
|
50 |
+
progress(0.1, desc="Creating collection name...")
|
51 |
+
collection_name = indexing.create_collection_name(list_file_path[0])
|
52 |
+
|
53 |
+
progress(0.25, desc="Loading document...")
|
54 |
+
# Load document and create splits
|
55 |
+
doc_splits = indexing.load_doc(list_file_path, chunk_size, chunk_overlap)
|
56 |
+
|
57 |
+
# Create or load vector database
|
58 |
+
progress(0.5, desc="Generating vector database...")
|
59 |
+
|
60 |
+
# global vector_db
|
61 |
+
vector_db = indexing.create_db(doc_splits, collection_name, db_type)
|
62 |
+
|
63 |
+
return vector_db, collection_name, "Complete!"
|
64 |
+
|
65 |
+
|
66 |
+
# Initialize LLM
|
67 |
+
def initialize_llm(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
68 |
+
"""Initialize LLM"""
|
69 |
+
|
70 |
+
# print("llm_option",llm_option)
|
71 |
+
llm_name = list_llm[llm_option]
|
72 |
+
print("llm_name: ", llm_name)
|
73 |
+
qa_chain = retrieval.initialize_llmchain(
|
74 |
+
llm_name, huggingfacehub_api_token, llm_temperature, max_tokens, top_k, vector_db, progress
|
75 |
+
)
|
76 |
+
return qa_chain, "Complete!"
|
77 |
+
|
78 |
+
|
79 |
+
# Chatbot conversation
|
80 |
+
def conversation(qa_chain, message, history):
|
81 |
+
"""Chatbot conversation"""
|
82 |
+
|
83 |
+
qa_chain, new_history, response_sources = retrieval.invoke_qa_chain(qa_chain, message, history)
|
84 |
+
|
85 |
+
# Format output gradio components
|
86 |
+
response_source1 = response_sources[0].page_content.strip()
|
87 |
+
response_source2 = response_sources[1].page_content.strip()
|
88 |
+
response_source3 = response_sources[2].page_content.strip()
|
89 |
+
# Langchain sources are zero-based
|
90 |
+
response_source1_page = response_sources[0].metadata["page"] + 1
|
91 |
+
response_source2_page = response_sources[1].metadata["page"] + 1
|
92 |
+
response_source3_page = response_sources[2].metadata["page"] + 1
|
93 |
+
|
94 |
+
return (
|
95 |
+
qa_chain,
|
96 |
+
gr.update(value=""),
|
97 |
+
new_history,
|
98 |
+
response_source1,
|
99 |
+
response_source1_page,
|
100 |
+
response_source2,
|
101 |
+
response_source2_page,
|
102 |
+
response_source3,
|
103 |
+
response_source3_page,
|
104 |
+
)
|
105 |
+
|
106 |
+
|
107 |
+
SPACE_TITLE = """
|
108 |
+
<center><h2>DocuMind</center></h2>
|
109 |
+
<h3>PDF-based chatbot, Ask any questions about your PDF documents!</h3>
|
110 |
+
"""
|
111 |
+
|
112 |
+
SPACE_INFO = """
|
113 |
+
<b>Description:</b> This AI assistant, using Langchain and open-source LLMs, performs retrieval-augmented generation (RAG) from your PDF documents. \
|
114 |
+
The user interface explicitely shows multiple steps to help understand the RAG workflow.
|
115 |
+
This chatbot takes past questions into account when generating answers (via conversational memory), and includes document references for clarity purposes.<br>
|
116 |
+
<br><b>Notes:</b> Updated space with more recent LLM models (Qwen 2.5, Llama 3.2, SmolLM2 series)
|
117 |
+
<br><b>Warning:</b> This space uses the free CPU Basic hardware from Hugging Face. Some steps and LLM models used below (free inference endpoints) can take some time to generate a reply.
|
118 |
+
"""
|
119 |
+
|
120 |
+
|
121 |
+
# Gradio User Interface
|
122 |
+
def gradio_ui():
|
123 |
+
"""Gradio User Interface"""
|
124 |
+
|
125 |
+
with gr.Blocks(title="DocuMind", theme=gr.themes.Soft()) as demo:
|
126 |
+
vector_db = gr.State()
|
127 |
+
qa_chain = gr.State()
|
128 |
+
collection_name = gr.State()
|
129 |
+
|
130 |
+
gr.Markdown(SPACE_TITLE)
|
131 |
+
gr.Markdown(SPACE_INFO)
|
132 |
+
|
133 |
+
with gr.Tab("Step 1 - Upload PDF"):
|
134 |
+
with gr.Row():
|
135 |
+
document = gr.File(
|
136 |
+
height=200,
|
137 |
+
file_count="multiple",
|
138 |
+
file_types=[".pdf"],
|
139 |
+
interactive=True,
|
140 |
+
label="Upload your PDF documents (single or multiple)",
|
141 |
+
)
|
142 |
+
|
143 |
+
with gr.Tab("Step 2 - Process document"):
|
144 |
+
with gr.Row():
|
145 |
+
db_type_selector = gr.Radio(
|
146 |
+
["ChromaDB", "Weaviate", "FAISS", "Qdrant", "Pinecone"],
|
147 |
+
label="Vector database type",
|
148 |
+
value="ChromaDB",
|
149 |
+
type="value",
|
150 |
+
info="Choose your vector database",
|
151 |
+
)
|
152 |
+
with gr.Accordion("Advanced options - Document text splitter", open=False):
|
153 |
+
with gr.Row():
|
154 |
+
slider_chunk_size = gr.Slider(
|
155 |
+
minimum=100,
|
156 |
+
maximum=1000,
|
157 |
+
value=600,
|
158 |
+
step=20,
|
159 |
+
label="Chunk size",
|
160 |
+
info="Chunk size",
|
161 |
+
interactive=True,
|
162 |
+
)
|
163 |
+
with gr.Row():
|
164 |
+
slider_chunk_overlap = gr.Slider(
|
165 |
+
minimum=10,
|
166 |
+
maximum=200,
|
167 |
+
value=40,
|
168 |
+
step=10,
|
169 |
+
label="Chunk overlap",
|
170 |
+
info="Chunk overlap",
|
171 |
+
interactive=True,
|
172 |
+
)
|
173 |
+
with gr.Row():
|
174 |
+
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
175 |
+
with gr.Row():
|
176 |
+
db_btn = gr.Button("Generate vector database")
|
177 |
+
|
178 |
+
with gr.Tab("Step 3 - Initialize QA chain"):
|
179 |
+
with gr.Row():
|
180 |
+
llm_btn = gr.Radio(
|
181 |
+
list_llm_simple,
|
182 |
+
label="LLM models",
|
183 |
+
value=list_llm_simple[0],
|
184 |
+
type="index",
|
185 |
+
info="Choose your LLM model",
|
186 |
+
)
|
187 |
+
with gr.Accordion("Advanced options - LLM model", open=False):
|
188 |
+
with gr.Row():
|
189 |
+
slider_temperature = gr.Slider(
|
190 |
+
minimum=0.01,
|
191 |
+
maximum=1.0,
|
192 |
+
value=0.7,
|
193 |
+
step=0.1,
|
194 |
+
label="Temperature",
|
195 |
+
info="Model temperature",
|
196 |
+
interactive=True,
|
197 |
+
)
|
198 |
+
with gr.Row():
|
199 |
+
slider_maxtokens = gr.Slider(
|
200 |
+
minimum=224,
|
201 |
+
maximum=4096,
|
202 |
+
value=1024,
|
203 |
+
step=32,
|
204 |
+
label="Max Tokens",
|
205 |
+
info="Model max tokens",
|
206 |
+
interactive=True,
|
207 |
+
)
|
208 |
+
with gr.Row():
|
209 |
+
slider_topk = gr.Slider(
|
210 |
+
minimum=1,
|
211 |
+
maximum=10,
|
212 |
+
value=3,
|
213 |
+
step=1,
|
214 |
+
label="top-k samples",
|
215 |
+
info="Model top-k samples",
|
216 |
+
interactive=True,
|
217 |
+
)
|
218 |
+
with gr.Row():
|
219 |
+
llm_progress = gr.Textbox(value="None", label="QA chain initialization")
|
220 |
+
with gr.Row():
|
221 |
+
qachain_btn = gr.Button("Initialize Question Answering chain")
|
222 |
+
|
223 |
+
with gr.Tab("Step 4 - Chatbot"):
|
224 |
+
chatbot = gr.Chatbot(height=300)
|
225 |
+
with gr.Accordion("Advanced - Document references", open=False):
|
226 |
+
with gr.Row():
|
227 |
+
doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
|
228 |
+
source1_page = gr.Number(label="Page", scale=1)
|
229 |
+
with gr.Row():
|
230 |
+
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
231 |
+
source2_page = gr.Number(label="Page", scale=1)
|
232 |
+
with gr.Row():
|
233 |
+
doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
|
234 |
+
source3_page = gr.Number(label="Page", scale=1)
|
235 |
+
with gr.Row():
|
236 |
+
msg = gr.Textbox(
|
237 |
+
placeholder="Type message (e.g. 'Can you summarize this document in one paragraph?')",
|
238 |
+
container=True,
|
239 |
+
)
|
240 |
+
with gr.Row():
|
241 |
+
submit_btn = gr.Button("Submit message")
|
242 |
+
clear_btn = gr.ClearButton(components=[msg, chatbot], value="Clear conversation")
|
243 |
+
|
244 |
+
# Preprocessing events
|
245 |
+
db_btn.click(
|
246 |
+
initialize_database,
|
247 |
+
inputs=[document, db_type_selector, slider_chunk_size, slider_chunk_overlap],
|
248 |
+
outputs=[vector_db, collection_name, db_progress],
|
249 |
+
)
|
250 |
+
qachain_btn.click(
|
251 |
+
initialize_llm,
|
252 |
+
inputs=[
|
253 |
+
llm_btn,
|
254 |
+
slider_temperature,
|
255 |
+
slider_maxtokens,
|
256 |
+
slider_topk,
|
257 |
+
vector_db,
|
258 |
+
],
|
259 |
+
outputs=[qa_chain, llm_progress],
|
260 |
+
).then(
|
261 |
+
lambda: [None, "", 0, "", 0, "", 0],
|
262 |
+
inputs=None,
|
263 |
+
outputs=[
|
264 |
+
chatbot,
|
265 |
+
doc_source1,
|
266 |
+
source1_page,
|
267 |
+
doc_source2,
|
268 |
+
source2_page,
|
269 |
+
doc_source3,
|
270 |
+
source3_page,
|
271 |
+
],
|
272 |
+
queue=False,
|
273 |
+
)
|
274 |
+
|
275 |
+
# Chatbot events
|
276 |
+
msg.submit(
|
277 |
+
conversation,
|
278 |
+
inputs=[qa_chain, msg, chatbot],
|
279 |
+
outputs=[
|
280 |
+
qa_chain,
|
281 |
+
msg,
|
282 |
+
chatbot,
|
283 |
+
doc_source1,
|
284 |
+
source1_page,
|
285 |
+
doc_source2,
|
286 |
+
source2_page,
|
287 |
+
doc_source3,
|
288 |
+
source3_page,
|
289 |
+
],
|
290 |
+
queue=False,
|
291 |
+
)
|
292 |
+
submit_btn.click(
|
293 |
+
conversation,
|
294 |
+
inputs=[qa_chain, msg, chatbot],
|
295 |
+
outputs=[
|
296 |
+
qa_chain,
|
297 |
+
msg,
|
298 |
+
chatbot,
|
299 |
+
doc_source1,
|
300 |
+
source1_page,
|
301 |
+
doc_source2,
|
302 |
+
source2_page,
|
303 |
+
doc_source3,
|
304 |
+
source3_page,
|
305 |
+
],
|
306 |
+
queue=False,
|
307 |
+
)
|
308 |
+
clear_btn.click(
|
309 |
+
lambda: [None, "", 0, "", 0, "", 0],
|
310 |
+
inputs=None,
|
311 |
+
outputs=[
|
312 |
+
chatbot,
|
313 |
+
doc_source1,
|
314 |
+
source1_page,
|
315 |
+
doc_source2,
|
316 |
+
source2_page,
|
317 |
+
doc_source3,
|
318 |
+
source3_page,
|
319 |
+
],
|
320 |
+
queue=False,
|
321 |
+
)
|
322 |
+
demo.queue().launch(debug=True)
|
323 |
+
|
324 |
+
|
325 |
+
if __name__ == "__main__":
|
326 |
+
retrieve_api()
|
327 |
+
gradio_ui()
|
indexing.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Indexing with vector database - updated for Weaviate, FAISS, Qdrant, Pinecone
|
3 |
+
Compatible with latest LangChain and HuggingFaceEmbeddings
|
4 |
+
"""
|
5 |
+
|
6 |
+
from pathlib import Path
|
7 |
+
import re
|
8 |
+
import
|
9 |
+
from unidecode import unidecode
|
10 |
+
|
11 |
+
from langchain_community.document_loaders import PyPDFLoader
|
12 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
13 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
14 |
+
|
15 |
+
|
16 |
+
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
17 |
+
loaders = [PyPDFLoader(x) for x in list_file_path]
|
18 |
+
pages = []
|
19 |
+
for loader in loaders:
|
20 |
+
pages.extend(loader.load())
|
21 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
22 |
+
doc_splits = text_splitter.split_documents(pages)
|
23 |
+
return doc_splits
|
24 |
+
|
25 |
+
|
26 |
+
def create_collection_name(filepath):
|
27 |
+
collection_name = Path(filepath).stem
|
28 |
+
collection_name = collection_name.replace(" ", "-")
|
29 |
+
collection_name = unidecode(collection_name)
|
30 |
+
collection_name = re.sub("[^A-Za-z0-9]+", "-", collection_name)
|
31 |
+
collection_name = collection_name[:50]
|
32 |
+
if len(collection_name) < 3:
|
33 |
+
collection_name += "xyz"
|
34 |
+
if not collection_name[0].isalnum():
|
35 |
+
collection_name = "A" + collection_name[1:]
|
36 |
+
if not collection_name[-1].isalnum():
|
37 |
+
collection_name = collection_name[:-1] + "Z"
|
38 |
+
print("\n\nFilepath:", filepath)
|
39 |
+
print("Collection name:", collection_name)
|
40 |
+
return collection_name
|
41 |
+
|
42 |
+
|
43 |
+
def create_db(splits, collection_name, db_type="ChromaDB"):
|
44 |
+
embedding = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-mpnet-base-v2")
|
45 |
+
|
46 |
+
if db_type == "ChromaDB":
|
47 |
+
import chromadb
|
48 |
+
from langchain_chroma import Chroma
|
49 |
+
|
50 |
+
chromadb.api.client.SharedSystemClient.clear_system_cache()
|
51 |
+
vectordb = Chroma.from_documents(
|
52 |
+
documents=splits,
|
53 |
+
embedding=embedding,
|
54 |
+
client=chromadb.EphemeralClient(),
|
55 |
+
collection_name=collection_name,
|
56 |
+
)
|
57 |
+
return vectordb
|
58 |
+
|
59 |
+
elif db_type == "Weaviate":
|
60 |
+
import weaviate
|
61 |
+
from langchain_weaviate.vectorstores import WeaviateVectorStore
|
62 |
+
|
63 |
+
client = weaviate.connect_to_local("http://localhost:8080",
|
64 |
+
grpc_port=50051)
|
65 |
+
vectordb = WeaviateVectorStore.from_documents(
|
66 |
+
splits,
|
67 |
+
embedding,
|
68 |
+
client=client,
|
69 |
+
index_name=collection_name,
|
70 |
+
text_key="text"
|
71 |
+
)
|
72 |
+
return vectordb
|
73 |
+
|
74 |
+
elif db_type == "FAISS":
|
75 |
+
from langchain.vectorstores import FAISS
|
76 |
+
|
77 |
+
vectordb = FAISS.from_documents(splits, embedding)
|
78 |
+
vectordb.save_local(f"{collection_name}_index")
|
79 |
+
return vectordb
|
80 |
+
|
81 |
+
elif db_type == "Qdrant":
|
82 |
+
from qdrant_client import QdrantClient
|
83 |
+
from langchain.vectorstores import Qdrant
|
84 |
+
|
85 |
+
client = QdrantClient("::memory::")
|
86 |
+
vectordb = Qdrant.from_documents(splits, embedding, client=client, collection_name=collection_name)
|
87 |
+
return vectordb
|
88 |
+
|
89 |
+
elif db_type == "Pinecone":
|
90 |
+
import pinecone
|
91 |
+
from langchain_pinecone import PineconeVectorStore
|
92 |
+
|
93 |
+
pinecone_api_key = os.environ.get("PINECONE_API_KEY")
|
94 |
+
pc = pinecone.Pinecone(api_key=pinecone_api_key)
|
95 |
+
|
96 |
+
index_name = collection_name
|
97 |
+
dim = len(embedding.embed_query("test"))
|
98 |
+
if index_name not in [i.name for i in pc.list_indexes()]:
|
99 |
+
pc.create_index(name=index_name, dimension=dim, metric="cosine")
|
100 |
+
|
101 |
+
index = pc.Index(index_name)
|
102 |
+
vectordb = PineconeVectorStore.from_documents(docs=splits, index=index, embedding=embedding)
|
103 |
+
return vectordb
|
104 |
+
|
105 |
+
else:
|
106 |
+
raise ValueError(f"Unsupported vector DB type: {db_type}")
|
prompt_template.json
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"title": "System prompt",
|
3 |
+
"prompt": "You are an assistant for question-answering tasks. Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. Keep the answer concise. Question: {question} \\n Context: {context} \\n Helpful Answer:"
|
4 |
+
}
|
5 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
transformers[torch]
|
2 |
+
sentence-transformers
|
3 |
+
langchain
|
4 |
+
langchain-community
|
5 |
+
langchain-huggingface
|
6 |
+
langchain-chroma
|
7 |
+
huggingface-hub
|
8 |
+
tqdm
|
9 |
+
accelerate
|
10 |
+
pypdf
|
11 |
+
chromadb
|
12 |
+
unidecode
|
13 |
+
gradio
|
14 |
+
python-dotenv
|
15 |
+
pinecone
|
16 |
+
pinecone-client
|
17 |
+
qdrant_client
|
18 |
+
weaviate
|
19 |
+
qdrant
|
retrieval.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
LLM chain retrieval
|
3 |
+
"""
|
4 |
+
|
5 |
+
import json
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
from langchain.chains.conversational_retrieval.base import ConversationalRetrievalChain
|
9 |
+
from langchain.memory import ConversationBufferMemory
|
10 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
11 |
+
from langchain_core.prompts import PromptTemplate
|
12 |
+
|
13 |
+
|
14 |
+
# Add system template for RAG application
|
15 |
+
PROMPT_TEMPLATE = """
|
16 |
+
You are an assistant for question-answering tasks. Use the following pieces of context to answer the question at the end.
|
17 |
+
If you don't know the answer, just say that you don't know, don't try to make up an answer. Keep the answer concise.
|
18 |
+
Question: {question}
|
19 |
+
Context: {context}
|
20 |
+
Helpful Answer:
|
21 |
+
"""
|
22 |
+
|
23 |
+
|
24 |
+
# Initialize langchain LLM chain
|
25 |
+
def initialize_llmchain(
|
26 |
+
llm_model,
|
27 |
+
huggingfacehub_api_token,
|
28 |
+
temperature,
|
29 |
+
max_tokens,
|
30 |
+
top_k,
|
31 |
+
vector_db,
|
32 |
+
progress=gr.Progress(),
|
33 |
+
):
|
34 |
+
"""Initialize Langchain LLM chain"""
|
35 |
+
|
36 |
+
progress(0.1, desc="Initializing HF tokenizer...")
|
37 |
+
# HuggingFaceHub uses HF inference endpoints
|
38 |
+
progress(0.5, desc="Initializing HF Hub...")
|
39 |
+
# Use of trust_remote_code as model_kwargs
|
40 |
+
# Warning: langchain issue
|
41 |
+
# URL: https://github.com/langchain-ai/langchain/issues/6080
|
42 |
+
|
43 |
+
llm = HuggingFaceEndpoint(
|
44 |
+
repo_id=llm_model,
|
45 |
+
task="text-generation",
|
46 |
+
temperature=temperature,
|
47 |
+
max_new_tokens=max_tokens,
|
48 |
+
top_k=top_k,
|
49 |
+
huggingfacehub_api_token=huggingfacehub_api_token,
|
50 |
+
)
|
51 |
+
|
52 |
+
progress(0.75, desc="Defining buffer memory...")
|
53 |
+
memory = ConversationBufferMemory(memory_key="chat_history", output_key="answer", return_messages=True)
|
54 |
+
# retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
|
55 |
+
retriever = vector_db.as_retriever()
|
56 |
+
|
57 |
+
progress(0.8, desc="Defining retrieval chain...")
|
58 |
+
with open("prompt_template.json", "r") as file:
|
59 |
+
system_prompt = json.load(file)
|
60 |
+
prompt_template = system_prompt["prompt"]
|
61 |
+
rag_prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
62 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
63 |
+
llm,
|
64 |
+
retriever=retriever,
|
65 |
+
chain_type="stuff",
|
66 |
+
memory=memory,
|
67 |
+
combine_docs_chain_kwargs={"prompt": rag_prompt},
|
68 |
+
return_source_documents=True,
|
69 |
+
# return_generated_question=False,
|
70 |
+
verbose=False,
|
71 |
+
)
|
72 |
+
progress(0.9, desc="Done!")
|
73 |
+
|
74 |
+
return qa_chain
|
75 |
+
|
76 |
+
|
77 |
+
def format_chat_history(message, chat_history):
|
78 |
+
"""Format chat history for llm chain"""
|
79 |
+
|
80 |
+
formatted_chat_history = []
|
81 |
+
for user_message, bot_message in chat_history:
|
82 |
+
formatted_chat_history.append(f"User: {user_message}")
|
83 |
+
formatted_chat_history.append(f"Assistant: {bot_message}")
|
84 |
+
return formatted_chat_history
|
85 |
+
|
86 |
+
|
87 |
+
def invoke_qa_chain(qa_chain, message, history):
|
88 |
+
"""Invoke question-answering chain"""
|
89 |
+
|
90 |
+
formatted_chat_history = format_chat_history(message, history)
|
91 |
+
# print("formatted_chat_history",formatted_chat_history)
|
92 |
+
|
93 |
+
# Generate response using QA chain
|
94 |
+
response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
|
95 |
+
|
96 |
+
response_sources = response["source_documents"]
|
97 |
+
|
98 |
+
response_answer = response["answer"]
|
99 |
+
if response_answer.find("Helpful Answer:") != -1:
|
100 |
+
response_answer = response_answer.split("Helpful Answer:")[-1]
|
101 |
+
|
102 |
+
# Append user message and response to chat history
|
103 |
+
new_history = history + [(message, response_answer)]
|
104 |
+
|
105 |
+
# print ('chat response: ', response_answer)
|
106 |
+
# print('DB source', response_sources)
|
107 |
+
|
108 |
+
return qa_chain, new_history, response_sources
|