Zahid0123 commited on
Commit
356d291
ยท
verified ยท
1 Parent(s): 992ab7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -30
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - FULLY WORKING AI RESEARCH AGENT WITH GROQ CLIENT
2
  import os
3
  import re
4
  import logging
@@ -32,19 +32,8 @@ groq_client = None
32
  if GROQ_OK:
33
  try:
34
  print("DEBUG โ†’ Initializing Groq client...")
35
- # Initialize with just api_key - most compatible approach
36
  groq_client = Groq(api_key=GROQ_API_KEY)
37
  print("โœ… DEBUG โ†’ Groq client initialized successfully!")
38
- except TypeError as te:
39
- # Fallback for version compatibility issues
40
- print(f"โš ๏ธ TypeError during init: {te}")
41
- try:
42
- print("๐Ÿ”„ Attempting fallback initialization...")
43
- groq_client = Groq(api_key=GROQ_API_KEY)
44
- print("โœ… Fallback initialization successful!")
45
- except Exception as e:
46
- groq_client = None
47
- print(f"โŒ Groq initialization failed: {e}")
48
  except Exception as e:
49
  groq_client = None
50
  print(f"โŒ Groq initialization error: {e}")
@@ -56,7 +45,22 @@ class AgenticRAGAgent:
56
  self.chunks = []
57
  self.index = None
58
  self.embedder = SentenceTransformer('all-MiniLM-L6-v2')
59
- print("โœ… AgenticRAGAgent initialized with SentenceTransformer")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  def remove_emojis(self, text: str) -> str:
62
  """Remove emojis from text for clean voice output"""
@@ -130,14 +134,13 @@ class AgenticRAGAgent:
130
  continue
131
 
132
  if text.strip():
133
- chunks = [text[i:i+500] for i in range(0, len(text), 450)]
134
  all_chunks.extend([{"content": c.strip()} for c in chunks if c.strip()])
135
  count += 1
136
 
137
  if not all_chunks:
138
  return "No readable text found in the PDFs."
139
 
140
- # Create embeddings and FAISS index
141
  print(f"Creating embeddings for {len(all_chunks)} chunks...")
142
  vecs = self.embedder.encode([c["content"] for c in all_chunks], show_progress_bar=True)
143
  vecs = vecs / np.linalg.norm(vecs, axis=1, keepdims=True)
@@ -176,7 +179,7 @@ class AgenticRAGAgent:
176
  # Retrieve relevant chunks
177
  q_vec = self.embedder.encode([question])
178
  q_vec = q_vec / np.linalg.norm(q_vec)
179
- D, I = self.index.search(q_vec.astype('float32'), k=6)
180
  context = "\n\n".join([self.chunks[i]["content"] for i in I[0] if i < len(self.chunks)])
181
 
182
  prompt = f"Context from documents:\n{context}\n\nQuestion: {question}\nAnswer clearly and accurately:"
@@ -190,8 +193,8 @@ class AgenticRAGAgent:
190
  resp = groq_client.chat.completions.create(
191
  model="llama-3.3-70b-versatile",
192
  messages=[{"role": "user", "content": prompt}],
193
- temperature=0.3,
194
- max_tokens=700
195
  )
196
  reply = resp.choices[0].message.content.strip()
197
  print(f"โœ… Received response from Groq API")
@@ -202,9 +205,32 @@ class AgenticRAGAgent:
202
  history.append([question, reply])
203
  return history, self.generate_voice(reply)
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
  # =========================================
207
- # GRADIO UI
208
  # =========================================
209
  def create_interface():
210
  agent = AgenticRAGAgent()
@@ -212,15 +238,16 @@ def create_interface():
212
  with gr.Blocks(title="AI Research Agent", theme=gr.themes.Soft()) as interface:
213
  gr.HTML("""
214
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px;">
215
- <h1 style="color: white; margin: 0;">AI Research Agent - Agentic RAG</h1>
216
- <p style="color: white; margin: 10px 0;">Advanced Multi-Tool Research Assistant with Voice Support</p>
217
  </div>
218
  """)
219
 
220
  with gr.Row():
221
  with gr.Column(scale=2):
 
222
  chatbot = gr.Chatbot(
223
- label="Chat",
224
  height=500,
225
  type="tuples"
226
  )
@@ -232,31 +259,123 @@ def create_interface():
232
  scale=4,
233
  lines=1
234
  )
235
- submit_btn = gr.Button("Send", variant="primary", scale=1)
236
 
237
  with gr.Row():
238
- clear_btn = gr.Button("Clear Chat", variant="secondary")
239
 
 
240
  audio_output = gr.Audio(
241
- label="Voice Response",
242
  autoplay=True,
243
  interactive=False
244
  )
245
 
 
246
  with gr.Column(scale=1):
 
247
  with gr.Group():
248
- gr.HTML("<h3 style='text-align: center;'>Upload Documents</h3>")
249
  file_upload = gr.Files(
250
  label="",
251
  file_types=[".pdf"],
252
  file_count="multiple"
253
  )
254
  upload_status = gr.Textbox(
255
- label="Status",
256
  interactive=False,
257
  max_lines=10
258
  )
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  def respond(message, history):
261
  """Handle user message"""
262
  new_hist, audio_file = agent.ask(message, history)
@@ -264,7 +383,7 @@ def create_interface():
264
 
265
  def clear_chat():
266
  """Clear chat history"""
267
- return [], None
268
 
269
  # Connect events
270
  submit_btn.click(
@@ -272,26 +391,48 @@ def create_interface():
272
  inputs=[msg, chatbot],
273
  outputs=[msg, chatbot, audio_output]
274
  )
 
275
  msg.submit(
276
  respond,
277
  inputs=[msg, chatbot],
278
  outputs=[msg, chatbot, audio_output]
279
  )
 
280
  clear_btn.click(
281
  clear_chat,
282
- outputs=[chatbot, audio_output]
283
  )
 
284
  file_upload.change(
285
  agent.upload_pdfs,
286
  inputs=[file_upload],
287
  outputs=[upload_status]
288
  )
 
 
 
 
 
 
 
 
 
 
289
 
290
  return interface
291
 
292
 
293
  if __name__ == "__main__":
294
- print("๐Ÿš€ Starting AI Research Agent...")
 
 
 
 
 
 
 
 
 
295
  app = create_interface()
296
  app.launch(
297
  server_name="0.0.0.0",
 
1
+ # app.py - FULLY WORKING AI RESEARCH AGENT WITH COMPLETE UI
2
  import os
3
  import re
4
  import logging
 
32
  if GROQ_OK:
33
  try:
34
  print("DEBUG โ†’ Initializing Groq client...")
 
35
  groq_client = Groq(api_key=GROQ_API_KEY)
36
  print("โœ… DEBUG โ†’ Groq client initialized successfully!")
 
 
 
 
 
 
 
 
 
 
37
  except Exception as e:
38
  groq_client = None
39
  print(f"โŒ Groq initialization error: {e}")
 
45
  self.chunks = []
46
  self.index = None
47
  self.embedder = SentenceTransformer('all-MiniLM-L6-v2')
48
+ self.conversation_history = []
49
+
50
+ # UI Settings
51
+ self.temperature = 0.3
52
+ self.max_tokens = 500
53
+ self.chunk_size = 512
54
+ self.chunk_overlap = 50
55
+ self.retrieval_k = 8
56
+
57
+ # Feature toggles
58
+ self.enable_web_search = True
59
+ self.enable_calculations = True
60
+ self.enable_fact_checking = True
61
+ self.enable_analysis = True
62
+
63
+ print("โœ… AgenticRAGAgent initialized")
64
 
65
  def remove_emojis(self, text: str) -> str:
66
  """Remove emojis from text for clean voice output"""
 
134
  continue
135
 
136
  if text.strip():
137
+ chunks = [text[i:i+self.chunk_size] for i in range(0, len(text), self.chunk_size - self.chunk_overlap)]
138
  all_chunks.extend([{"content": c.strip()} for c in chunks if c.strip()])
139
  count += 1
140
 
141
  if not all_chunks:
142
  return "No readable text found in the PDFs."
143
 
 
144
  print(f"Creating embeddings for {len(all_chunks)} chunks...")
145
  vecs = self.embedder.encode([c["content"] for c in all_chunks], show_progress_bar=True)
146
  vecs = vecs / np.linalg.norm(vecs, axis=1, keepdims=True)
 
179
  # Retrieve relevant chunks
180
  q_vec = self.embedder.encode([question])
181
  q_vec = q_vec / np.linalg.norm(q_vec)
182
+ D, I = self.index.search(q_vec.astype('float32'), k=self.retrieval_k)
183
  context = "\n\n".join([self.chunks[i]["content"] for i in I[0] if i < len(self.chunks)])
184
 
185
  prompt = f"Context from documents:\n{context}\n\nQuestion: {question}\nAnswer clearly and accurately:"
 
193
  resp = groq_client.chat.completions.create(
194
  model="llama-3.3-70b-versatile",
195
  messages=[{"role": "user", "content": prompt}],
196
+ temperature=self.temperature,
197
+ max_tokens=self.max_tokens
198
  )
199
  reply = resp.choices[0].message.content.strip()
200
  print(f"โœ… Received response from Groq API")
 
205
  history.append([question, reply])
206
  return history, self.generate_voice(reply)
207
 
208
+ def update_settings(self, temp, tokens, chunk_size, overlap, k, web, calc, fact, analysis):
209
+ """Update agent settings"""
210
+ self.temperature = temp
211
+ self.max_tokens = tokens
212
+ self.chunk_size = chunk_size
213
+ self.chunk_overlap = overlap
214
+ self.retrieval_k = k
215
+ self.enable_web_search = web
216
+ self.enable_calculations = calc
217
+ self.enable_fact_checking = fact
218
+ self.enable_analysis = analysis
219
+
220
+ return f"""โš™๏ธ Settings Updated:
221
+ โ€ข Temperature: {temp}
222
+ โ€ข Max Tokens: {tokens}
223
+ โ€ข Chunk Size: {chunk_size}
224
+ โ€ข Chunk Overlap: {overlap}
225
+ โ€ข Retrieved Chunks: {k}
226
+ โ€ข Web Search: {'โœ…' if web else 'โŒ'}
227
+ โ€ข Calculator: {'โœ…' if calc else 'โŒ'}
228
+ โ€ข Fact Check: {'โœ…' if fact else 'โŒ'}
229
+ โ€ข Analysis: {'โœ…' if analysis else 'โŒ'}"""
230
+
231
 
232
  # =========================================
233
+ # GRADIO UI WITH FULL SETTINGS
234
  # =========================================
235
  def create_interface():
236
  agent = AgenticRAGAgent()
 
238
  with gr.Blocks(title="AI Research Agent", theme=gr.themes.Soft()) as interface:
239
  gr.HTML("""
240
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px;">
241
+ <h1 style="color: white; margin: 0;">๐Ÿค– AI Research Agent - Agentic RAG</h1>
242
+ <p style="color: white; margin: 10px 0;">Advanced Multi-Tool Research Assistant with Voice Support ๐ŸŽค๐Ÿ”Š</p>
243
  </div>
244
  """)
245
 
246
  with gr.Row():
247
  with gr.Column(scale=2):
248
+ # Chat Interface
249
  chatbot = gr.Chatbot(
250
+ label="๐Ÿ’ฌ Chat",
251
  height=500,
252
  type="tuples"
253
  )
 
259
  scale=4,
260
  lines=1
261
  )
262
+ submit_btn = gr.Button("๐Ÿš€ Send", variant="primary", scale=1)
263
 
264
  with gr.Row():
265
+ clear_btn = gr.Button("๐Ÿ—‘๏ธ Clear Chat", variant="secondary")
266
 
267
+ # Voice Output
268
  audio_output = gr.Audio(
269
+ label="๐Ÿ”Š Voice Response",
270
  autoplay=True,
271
  interactive=False
272
  )
273
 
274
+ # ===== SIDEBAR WITH SETTINGS =====
275
  with gr.Column(scale=1):
276
+ # Document Upload Section
277
  with gr.Group():
278
+ gr.HTML("<h3 style='text-align: center;'>๐Ÿ“„ Upload Documents</h3>")
279
  file_upload = gr.Files(
280
  label="",
281
  file_types=[".pdf"],
282
  file_count="multiple"
283
  )
284
  upload_status = gr.Textbox(
285
+ label="๐Ÿ“Š Status",
286
  interactive=False,
287
  max_lines=10
288
  )
289
 
290
+ # ===== AI PARAMETERS SETTINGS =====
291
+ with gr.Accordion("โš™๏ธ AI Parameters", open=False):
292
+ gr.HTML("<h4 style='margin-bottom: 10px;'>๐Ÿง  Model Settings</h4>")
293
+
294
+ temperature_slider = gr.Slider(
295
+ 0.0, 1.0,
296
+ value=0.3,
297
+ step=0.1,
298
+ label="๐ŸŒก๏ธ Temperature",
299
+ info="Higher = more creative"
300
+ )
301
+
302
+ max_tokens_slider = gr.Slider(
303
+ 100, 2000,
304
+ value=500,
305
+ step=50,
306
+ label="๐Ÿ“ Max Tokens",
307
+ info="Response length"
308
+ )
309
+
310
+ # ===== DOCUMENT PROCESSING SETTINGS =====
311
+ with gr.Accordion("๐Ÿ“„ Document Processing", open=False):
312
+ gr.HTML("<h4 style='margin-bottom: 10px;'>๐Ÿ“ฆ Chunking Strategy</h4>")
313
+
314
+ chunk_size_slider = gr.Slider(
315
+ 256, 1024,
316
+ value=512,
317
+ step=64,
318
+ label="๐Ÿ“„ Chunk Size",
319
+ info="Text segment size"
320
+ )
321
+
322
+ chunk_overlap_slider = gr.Slider(
323
+ 0, 200,
324
+ value=50,
325
+ step=10,
326
+ label="๐Ÿ”— Chunk Overlap",
327
+ info="Overlap between chunks"
328
+ )
329
+
330
+ retrieval_k_slider = gr.Slider(
331
+ 3, 15,
332
+ value=8,
333
+ step=1,
334
+ label="๐Ÿ” Retrieved Chunks",
335
+ info="Documents to retrieve"
336
+ )
337
+
338
+ # ===== AGENTIC TOOLS SETTINGS =====
339
+ with gr.Accordion("๐Ÿ› ๏ธ Agentic Tools", open=False):
340
+ gr.HTML("<h4 style='margin-bottom: 10px;'>โšก Enable/Disable Tools</h4>")
341
+
342
+ with gr.Row():
343
+ enable_web = gr.Checkbox(
344
+ value=True,
345
+ label="๐ŸŒ Web Search"
346
+ )
347
+ enable_calc = gr.Checkbox(
348
+ value=True,
349
+ label="๐Ÿงฎ Calculator"
350
+ )
351
+
352
+ with gr.Row():
353
+ enable_fact = gr.Checkbox(
354
+ value=True,
355
+ label="โœ… Fact Check"
356
+ )
357
+ enable_analysis = gr.Checkbox(
358
+ value=True,
359
+ label="๐Ÿ“Š Analysis"
360
+ )
361
+
362
+ # Apply Settings Button
363
+ apply_btn = gr.Button(
364
+ "โšก Apply Settings",
365
+ variant="primary",
366
+ size="lg",
367
+ full_width=True
368
+ )
369
+
370
+ # Settings Status
371
+ settings_status = gr.Textbox(
372
+ label="โš™๏ธ Settings Status",
373
+ interactive=False,
374
+ max_lines=10,
375
+ value="Settings ready. Adjust and click 'Apply Settings'"
376
+ )
377
+
378
+ # ===== EVENT HANDLERS =====
379
  def respond(message, history):
380
  """Handle user message"""
381
  new_hist, audio_file = agent.ask(message, history)
 
383
 
384
  def clear_chat():
385
  """Clear chat history"""
386
+ return []
387
 
388
  # Connect events
389
  submit_btn.click(
 
391
  inputs=[msg, chatbot],
392
  outputs=[msg, chatbot, audio_output]
393
  )
394
+
395
  msg.submit(
396
  respond,
397
  inputs=[msg, chatbot],
398
  outputs=[msg, chatbot, audio_output]
399
  )
400
+
401
  clear_btn.click(
402
  clear_chat,
403
+ outputs=[chatbot]
404
  )
405
+
406
  file_upload.change(
407
  agent.upload_pdfs,
408
  inputs=[file_upload],
409
  outputs=[upload_status]
410
  )
411
+
412
+ apply_btn.click(
413
+ agent.update_settings,
414
+ inputs=[
415
+ temperature_slider, max_tokens_slider, chunk_size_slider,
416
+ chunk_overlap_slider, retrieval_k_slider, enable_web,
417
+ enable_calc, enable_fact, enable_analysis
418
+ ],
419
+ outputs=[settings_status]
420
+ )
421
 
422
  return interface
423
 
424
 
425
  if __name__ == "__main__":
426
+ print("๐Ÿš€ Starting AI Research Agent with Full UI...")
427
+ print("โœจ Features:")
428
+ print(" โ€ข Document Upload (PDF)")
429
+ print(" โ€ข Semantic Search")
430
+ print(" โ€ข Groq LLM Integration")
431
+ print(" โ€ข Voice Output (gTTS)")
432
+ print(" โ€ข AI Parameter Controls")
433
+ print(" โ€ข Document Processing Settings")
434
+ print(" โ€ข Agentic Tools Toggle")
435
+
436
  app = create_interface()
437
  app.launch(
438
  server_name="0.0.0.0",