Himanshu kumar Vishwakrma commited on
Commit
c61fa90
Β·
1 Parent(s): e268ac6

Deploy RAG Chatbot with Hhugging face Gemma 3

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +41 -40
src/streamlit_app.py CHANGED
@@ -1,5 +1,4 @@
1
  import streamlit as st
2
- import ollama
3
  from pypdf import PdfReader
4
  from docx import Document
5
  import os
@@ -7,6 +6,8 @@ import time
7
  import chromadb
8
  from chromadb.utils import embedding_functions
9
  from typing import List, Tuple
 
 
10
 
11
  # Initialize ChromaDB
12
  client = chromadb.PersistentClient(path="./chroma_db")
@@ -17,6 +18,20 @@ try:
17
  except:
18
  collection = client.create_collection(name="documents", embedding_function=sentence_transformer_ef)
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def chunk_text(text: str, chunk_size: int = 1000) -> List[str]:
21
  """Split text into chunks of approximately chunk_size characters"""
22
  chunks = []
@@ -105,8 +120,8 @@ def retrieve_relevant_chunks(query: str, k: int = 5) -> Tuple[List[str], List[st
105
  return results['documents'][0], results['metadatas'][0]
106
 
107
  @st.cache_data(ttl=60, show_spinner=False) # Cache for 1 minute
108
- def generate_response(query: str, context: str, temp: float = 0.7, model: str = "gemma3") -> str:
109
- """Generate response using Ollama with RAG context and caching"""
110
  prompt = f"""Use the following context to answer the question. If you don't know the answer, say you don't know.
111
 
112
  Context:
@@ -116,17 +131,26 @@ Question: {query}
116
 
117
  Answer:"""
118
 
119
- # Add optimization options
120
- response = ollama.generate(
121
- model=model,
122
- prompt=prompt,
123
- options={
124
- 'temperature': temp,
125
- 'num_predict': 512, # Limit token generation for faster responses
126
- 'num_ctx': 2048 # Set context window
127
- }
128
- )
129
- return response['response']
 
 
 
 
 
 
 
 
 
130
 
131
  # Initialize session states
132
  if "messages" not in st.session_state:
@@ -157,11 +181,9 @@ with st.sidebar:
157
  st.markdown("---")
158
  st.header("Settings")
159
  temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
160
- model_name = st.selectbox("Model", ["gemma3"], index=0)
161
  st.markdown("ℹ️ All processing happens locally")
162
 
163
  if uploaded_files and st.button("Process Documents", use_container_width=True):
164
- # Create a modal-like container for progress tracking
165
  progress_container = st.container()
166
 
167
  with progress_container:
@@ -169,7 +191,6 @@ with st.sidebar:
169
  progress_bar = st.progress(0)
170
  status_text = st.empty()
171
 
172
- # Use a single column layout for metrics in the sidebar
173
  st.markdown("**Progress Metrics**")
174
  metric_col1, metric_col2 = st.columns(2)
175
  total_chunks_metric = metric_col1.empty()
@@ -183,12 +204,10 @@ with st.sidebar:
183
  if uploaded_file.name not in st.session_state.uploaded_files:
184
  status_text.text(f"Starting to process {uploaded_file.name}...")
185
 
186
- # Process the document with progress tracking
187
  chunks_count = process_document(uploaded_file, progress_bar, status_text)
188
  total_chunks += chunks_count
189
  files_processed += 1
190
 
191
- # Calculate and display metrics
192
  elapsed = time.time() - start_time
193
  eta = (elapsed / files_processed) * (len(uploaded_files) - files_processed) if files_processed > 0 else 0
194
  total_chunks_metric.metric("Chunks Created", f"{total_chunks}")
@@ -196,13 +215,11 @@ with st.sidebar:
196
 
197
  st.session_state.uploaded_files.append(uploaded_file.name)
198
 
199
- # Final status update
200
  progress_bar.progress(1.0)
201
  status_text.text("βœ… Processing completed!")
202
 
203
- # Show completion message with stats
204
  st.success(f"Successfully processed {files_processed} document(s) into {total_chunks} searchable chunks.")
205
- st.balloons() # Add a celebratory effect
206
  st.markdown("### πŸŽ‰ Your documents are now ready!")
207
  st.markdown("You can start asking questions about your documents in the chat below.")
208
 
@@ -221,68 +238,52 @@ with st.sidebar:
221
 
222
  # Chat input
223
  if prompt := st.chat_input("Ask about your documents..."):
224
- # Start timing the query response
225
  query_start_time = time.time()
226
 
227
- # Add user message to chat history
228
  st.session_state.messages.append({"role": "user", "content": prompt})
229
 
230
- # Display user message
231
  with st.chat_message("user"):
232
  st.markdown(prompt)
233
 
234
- # Display assistant response
235
  with st.chat_message("assistant"):
236
  message_placeholder = st.empty()
237
  full_response = ""
238
 
239
- # Add loading indicator
240
  with st.status("Searching documents for relevant information...", expanded=True) as status:
241
- # Retrieve relevant context with improved k value
242
  st.write("πŸ” Finding relevant information...")
243
  chunks, metadata = retrieve_relevant_chunks(prompt)
244
  context = "\n\n".join(chunks)
245
 
246
- # Show found sources
247
  sources = list(set([m['source'] for m in metadata]))
248
  st.write(f"πŸ“š Found information in {len(sources)} document(s)")
249
 
250
- # Generate response with context
251
  st.write("πŸ’­ Generating response...")
252
- response = generate_response(prompt, context, temp=temperature, model=model_name)
253
  status.update(label="βœ… Answer ready!", state="complete", expanded=False)
254
 
255
- # Stream the response more efficiently with batch updates
256
  words = response.split()
257
  total_words = len(words)
258
- update_frequency = max(1, total_words // 20) # Update about 20 times total
259
 
260
  for i in range(0, total_words, update_frequency):
261
  end_idx = min(i + update_frequency, total_words)
262
  full_response += " ".join(words[i:end_idx]) + " "
263
  message_placeholder.markdown(full_response + "β–Œ")
264
- # Use a much shorter sleep time for faster updates
265
  time.sleep(0.01)
266
 
267
- # Add sources
268
- sources = list(set([m['source'] for m in metadata]))
269
  if sources:
270
  full_response += f"\n\nSources: {', '.join(sources)}"
271
 
272
  message_placeholder.markdown(full_response)
273
 
274
- # Add assistant response to chat history
275
  st.session_state.messages.append({"role": "assistant", "content": full_response})
276
 
277
- # Update performance metrics
278
  end_time = time.time()
279
  query_time = end_time - query_start_time
280
 
281
- # Update metrics
282
  st.session_state.performance_metrics["total_queries"] += 1
283
  st.session_state.performance_metrics["last_response_time"] = query_time
284
 
285
- # Calculate running average
286
  prev_avg = st.session_state.performance_metrics["avg_response_time"]
287
  prev_count = st.session_state.performance_metrics["total_queries"] - 1
288
 
 
1
  import streamlit as st
 
2
  from pypdf import PdfReader
3
  from docx import Document
4
  import os
 
6
  import chromadb
7
  from chromadb.utils import embedding_functions
8
  from typing import List, Tuple
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ import torch
11
 
12
  # Initialize ChromaDB
13
  client = chromadb.PersistentClient(path="./chroma_db")
 
18
  except:
19
  collection = client.create_collection(name="documents", embedding_function=sentence_transformer_ef)
20
 
21
+ # Initialize Hugging Face model and tokenizer
22
+ @st.cache_resource
23
+ def load_model():
24
+ model_name = "google/gemma-1.1-7b-it" # Using the 7B instruct-tuned version
25
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
26
+ model = AutoModelForCausalLM.from_pretrained(
27
+ model_name,
28
+ device_map="auto",
29
+ torch_dtype=torch.float16
30
+ )
31
+ return model, tokenizer
32
+
33
+ model, tokenizer = load_model()
34
+
35
  def chunk_text(text: str, chunk_size: int = 1000) -> List[str]:
36
  """Split text into chunks of approximately chunk_size characters"""
37
  chunks = []
 
120
  return results['documents'][0], results['metadatas'][0]
121
 
122
  @st.cache_data(ttl=60, show_spinner=False) # Cache for 1 minute
123
+ def generate_response(query: str, context: str, temp: float = 0.7) -> str:
124
+ """Generate response using Hugging Face Gemma with RAG context and caching"""
125
  prompt = f"""Use the following context to answer the question. If you don't know the answer, say you don't know.
126
 
127
  Context:
 
131
 
132
  Answer:"""
133
 
134
+ # Tokenize the input
135
+ input_ids = tokenizer(prompt, return_tensors="pt").to(model.device)
136
+
137
+ # Generate response
138
+ with torch.no_grad():
139
+ outputs = model.generate(
140
+ **input_ids,
141
+ max_new_tokens=512,
142
+ temperature=temp,
143
+ do_sample=True if temp > 0 else False,
144
+ top_k=50,
145
+ top_p=0.95
146
+ )
147
+
148
+ # Decode the response
149
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
150
+
151
+ # Remove the input prompt from the response
152
+ response = response[len(prompt):].strip()
153
+ return response
154
 
155
  # Initialize session states
156
  if "messages" not in st.session_state:
 
181
  st.markdown("---")
182
  st.header("Settings")
183
  temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
 
184
  st.markdown("ℹ️ All processing happens locally")
185
 
186
  if uploaded_files and st.button("Process Documents", use_container_width=True):
 
187
  progress_container = st.container()
188
 
189
  with progress_container:
 
191
  progress_bar = st.progress(0)
192
  status_text = st.empty()
193
 
 
194
  st.markdown("**Progress Metrics**")
195
  metric_col1, metric_col2 = st.columns(2)
196
  total_chunks_metric = metric_col1.empty()
 
204
  if uploaded_file.name not in st.session_state.uploaded_files:
205
  status_text.text(f"Starting to process {uploaded_file.name}...")
206
 
 
207
  chunks_count = process_document(uploaded_file, progress_bar, status_text)
208
  total_chunks += chunks_count
209
  files_processed += 1
210
 
 
211
  elapsed = time.time() - start_time
212
  eta = (elapsed / files_processed) * (len(uploaded_files) - files_processed) if files_processed > 0 else 0
213
  total_chunks_metric.metric("Chunks Created", f"{total_chunks}")
 
215
 
216
  st.session_state.uploaded_files.append(uploaded_file.name)
217
 
 
218
  progress_bar.progress(1.0)
219
  status_text.text("βœ… Processing completed!")
220
 
 
221
  st.success(f"Successfully processed {files_processed} document(s) into {total_chunks} searchable chunks.")
222
+ st.balloons()
223
  st.markdown("### πŸŽ‰ Your documents are now ready!")
224
  st.markdown("You can start asking questions about your documents in the chat below.")
225
 
 
238
 
239
  # Chat input
240
  if prompt := st.chat_input("Ask about your documents..."):
 
241
  query_start_time = time.time()
242
 
 
243
  st.session_state.messages.append({"role": "user", "content": prompt})
244
 
 
245
  with st.chat_message("user"):
246
  st.markdown(prompt)
247
 
 
248
  with st.chat_message("assistant"):
249
  message_placeholder = st.empty()
250
  full_response = ""
251
 
 
252
  with st.status("Searching documents for relevant information...", expanded=True) as status:
 
253
  st.write("πŸ” Finding relevant information...")
254
  chunks, metadata = retrieve_relevant_chunks(prompt)
255
  context = "\n\n".join(chunks)
256
 
 
257
  sources = list(set([m['source'] for m in metadata]))
258
  st.write(f"πŸ“š Found information in {len(sources)} document(s)")
259
 
 
260
  st.write("πŸ’­ Generating response...")
261
+ response = generate_response(prompt, context, temp=temperature)
262
  status.update(label="βœ… Answer ready!", state="complete", expanded=False)
263
 
 
264
  words = response.split()
265
  total_words = len(words)
266
+ update_frequency = max(1, total_words // 20)
267
 
268
  for i in range(0, total_words, update_frequency):
269
  end_idx = min(i + update_frequency, total_words)
270
  full_response += " ".join(words[i:end_idx]) + " "
271
  message_placeholder.markdown(full_response + "β–Œ")
 
272
  time.sleep(0.01)
273
 
 
 
274
  if sources:
275
  full_response += f"\n\nSources: {', '.join(sources)}"
276
 
277
  message_placeholder.markdown(full_response)
278
 
 
279
  st.session_state.messages.append({"role": "assistant", "content": full_response})
280
 
 
281
  end_time = time.time()
282
  query_time = end_time - query_start_time
283
 
 
284
  st.session_state.performance_metrics["total_queries"] += 1
285
  st.session_state.performance_metrics["last_response_time"] = query_time
286
 
 
287
  prev_avg = st.session_state.performance_metrics["avg_response_time"]
288
  prev_count = st.session_state.performance_metrics["total_queries"] - 1
289