Shreyas094 commited on
Commit
e45d4fc
·
verified ·
1 Parent(s): b0ca421

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -823
app.py CHANGED
@@ -1,27 +1,10 @@
1
  import os
2
  import json
3
- import re
4
  import gradio as gr
5
- import requests
6
  from duckduckgo_search import DDGS
7
  from typing import List, Dict
8
- from pydantic import BaseModel, Field
9
- from tempfile import NamedTemporaryFile
10
- from langchain_community.vectorstores import FAISS
11
- from langchain_core.vectorstores import VectorStore
12
- from langchain_core.documents import Document
13
- from langchain_community.document_loaders import PyPDFLoader
14
- from langchain_community.embeddings import HuggingFaceEmbeddings
15
- from llama_parse import LlamaParse
16
- from huggingface_hub import InferenceClient
17
- import inspect
18
- import logging
19
- import shutil
20
- import pandas as pd
21
- from docx import Document as DocxDocument
22
- import google.generativeai as genai
23
-
24
-
25
  from huggingface_hub import InferenceClient
26
 
27
  # Set up basic configuration for logging
@@ -29,272 +12,16 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(
29
 
30
  # Environment variables and configurations
31
  huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
32
- llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")
33
- ACCOUNT_ID = os.environ.get("CLOUDFARE_ACCOUNT_ID")
34
- API_TOKEN = os.environ.get("CLOUDFLARE_AUTH_TOKEN")
35
- API_BASE_URL = "https://api.cloudflare.com/client/v4/accounts/a17f03e0f049ccae0c15cdcf3b9737ce/ai/run/"
36
-
37
- print(f"ACCOUNT_ID: {ACCOUNT_ID}")
38
- print(f"CLOUDFLARE_AUTH_TOKEN: {API_TOKEN[:5]}..." if API_TOKEN else "Not set")
39
-
40
 
41
  MODELS = [
42
  "mistralai/Mistral-7B-Instruct-v0.3",
43
  "mistralai/Mixtral-8x7B-Instruct-v0.1",
44
- "@cf/meta/llama-3.1-8b-instruct",
45
- "mistralai/Mistral-Nemo-Instruct-2407",
46
- "mistralai/Mathstral-7B-v0.1",
47
- "meta-llama/Meta-Llama-3.1-8B-Instruct",
48
- "meta-llama/Meta-Llama-3.1-70B-Instruct",
49
- "mattshumer/Reflection-Llama-3.1-70B",
50
- "gemini-1.5-flash",
51
  "duckduckgo/gpt-4o-mini",
52
  "duckduckgo/claude-3-haiku",
53
  "duckduckgo/llama-3.1-70b",
54
  "duckduckgo/mixtral-8x7b"
55
  ]
56
 
57
- # Initialize LlamaParse
58
- llama_parser = LlamaParse(
59
- api_key=llama_cloud_api_key,
60
- result_type="markdown",
61
- num_workers=4,
62
- verbose=True,
63
- language="en",
64
- )
65
-
66
- def load_office_document(file: NamedTemporaryFile) -> List[Document]:
67
- file_extension = os.path.splitext(file.name)[1].lower()
68
- documents = []
69
-
70
- if file_extension in ['.xlsx', '.xls']:
71
- df = pd.read_excel(file.name)
72
- for _, row in df.iterrows():
73
- content = ' '.join(str(cell) for cell in row if pd.notna(cell))
74
- documents.append(Document(page_content=content, metadata={"source": file.name}))
75
- elif file_extension == '.docx':
76
- doc = Document(file.name)
77
- for para in doc.paragraphs:
78
- if para.text.strip():
79
- documents.append(Document(page_content=para.text, metadata={"source": file.name}))
80
-
81
- return documents
82
-
83
- def load_document(file: NamedTemporaryFile, parser: str = "llamaparse") -> List[Document]:
84
- """Loads and splits the document into pages."""
85
- if parser == "pypdf":
86
- loader = PyPDFLoader(file.name)
87
- return loader.load_and_split()
88
- elif parser == "llamaparse":
89
- try:
90
- documents = llama_parser.load_data(file.name)
91
- return [Document(page_content=doc.text, metadata={"source": file.name}) for doc in documents]
92
- except Exception as e:
93
- print(f"Error using Llama Parse: {str(e)}")
94
- print("Falling back to PyPDF parser")
95
- loader = PyPDFLoader(file.name)
96
- return loader.load_and_split()
97
- else:
98
- raise ValueError("Invalid parser specified. Use 'pypdf' or 'llamaparse'.")
99
-
100
- def get_embeddings():
101
- return HuggingFaceEmbeddings(model_name="avsolatorio/GIST-Embedding-v0")
102
-
103
- # Add this at the beginning of your script, after imports
104
- DOCUMENTS_FILE = "uploaded_documents.json"
105
-
106
- def load_documents():
107
- if os.path.exists(DOCUMENTS_FILE):
108
- with open(DOCUMENTS_FILE, "r") as f:
109
- return json.load(f)
110
- return []
111
-
112
- def save_documents(documents):
113
- with open(DOCUMENTS_FILE, "w") as f:
114
- json.dump(documents, f)
115
-
116
- # Replace the global uploaded_documents with this
117
- uploaded_documents = load_documents()
118
-
119
- # Modify the update_vectors function
120
- def update_vectors(files, parser):
121
- global uploaded_documents
122
- logging.info(f"Entering update_vectors with {len(files)} files and parser: {parser}")
123
-
124
- if not files:
125
- logging.warning("No files provided for update_vectors")
126
- return "Please upload at least one file.", display_documents()
127
-
128
- embed = get_embeddings()
129
- total_chunks = 0
130
-
131
- all_data = []
132
- for file in files:
133
- logging.info(f"Processing file: {file.name}")
134
- try:
135
- file_extension = os.path.splitext(file.name)[1].lower()
136
-
137
- if file_extension in ['.xlsx', '.xls', '.docx']:
138
- if parser != "office":
139
- logging.warning(f"Using office parser for {file.name} regardless of selected parser")
140
- data = load_office_document(file)
141
- elif file_extension == '.pdf':
142
- if parser == "office":
143
- logging.warning(f"Cannot use office parser for PDF file {file.name}. Using llamaparse.")
144
- data = load_document(file, "llamaparse")
145
- else:
146
- data = load_document(file, parser)
147
- else:
148
- logging.warning(f"Unsupported file type: {file_extension}")
149
- continue
150
-
151
- if not data:
152
- logging.warning(f"No chunks loaded from {file.name}")
153
- continue
154
- logging.info(f"Loaded {len(data)} chunks from {file.name}")
155
- all_data.extend(data)
156
- total_chunks += len(data)
157
- if not any(doc["name"] == file.name for doc in uploaded_documents):
158
- uploaded_documents.append({"name": file.name, "selected": True})
159
- logging.info(f"Added new document to uploaded_documents: {file.name}")
160
- else:
161
- logging.info(f"Document already exists in uploaded_documents: {file.name}")
162
- except Exception as e:
163
- logging.error(f"Error processing file {file.name}: {str(e)}")
164
-
165
- logging.info(f"Total chunks processed: {total_chunks}")
166
-
167
- if not all_data:
168
- logging.warning("No valid data extracted from uploaded files")
169
- return "No valid data could be extracted from the uploaded files. Please check the file contents and try again.", display_documents()
170
-
171
- try:
172
- # Update the appropriate vector store based on file type
173
- pdf_data = [doc for doc in all_data if doc.metadata["source"].lower().endswith('.pdf')]
174
- office_data = [doc for doc in all_data if not doc.metadata["source"].lower().endswith('.pdf')]
175
-
176
- if pdf_data:
177
- if os.path.exists("faiss_database"):
178
- pdf_database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
179
- pdf_database.add_documents(pdf_data)
180
- else:
181
- pdf_database = FAISS.from_documents(pdf_data, embed)
182
- pdf_database.save_local("faiss_database")
183
- logging.info("PDF FAISS database updated and saved")
184
-
185
- if office_data:
186
- if os.path.exists("office_faiss_database"):
187
- office_database = FAISS.load_local("office_faiss_database", embed, allow_dangerous_deserialization=True)
188
- office_database.add_documents(office_data)
189
- else:
190
- office_database = FAISS.from_documents(office_data, embed)
191
- office_database.save_local("office_faiss_database")
192
- logging.info("Office FAISS database updated and saved")
193
-
194
- except Exception as e:
195
- logging.error(f"Error updating FAISS database: {str(e)}")
196
- return f"Error updating vector store: {str(e)}", display_documents()
197
-
198
- # Save the updated list of documents
199
- save_documents(uploaded_documents)
200
-
201
- # Return a tuple with the status message and the updated document list
202
- return f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files.", display_documents()
203
-
204
-
205
- def delete_documents(selected_docs):
206
- global uploaded_documents
207
-
208
- if not selected_docs:
209
- return "No documents selected for deletion.", display_documents()
210
-
211
- embed = get_embeddings()
212
- database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
213
-
214
- deleted_docs = []
215
- docs_to_keep = []
216
- for doc in database.docstore._dict.values():
217
- if doc.metadata.get("source") not in selected_docs:
218
- docs_to_keep.append(doc)
219
- else:
220
- deleted_docs.append(doc.metadata.get("source", "Unknown"))
221
-
222
- # Print debugging information
223
- logging.info(f"Total documents before deletion: {len(database.docstore._dict)}")
224
- logging.info(f"Documents to keep: {len(docs_to_keep)}")
225
- logging.info(f"Documents to delete: {len(deleted_docs)}")
226
-
227
- if not docs_to_keep:
228
- # If all documents are deleted, remove the FAISS database directory
229
- if os.path.exists("faiss_database"):
230
- shutil.rmtree("faiss_database")
231
- logging.info("All documents deleted. Removed FAISS database directory.")
232
- else:
233
- # Create new FAISS index with remaining documents
234
- new_database = FAISS.from_documents(docs_to_keep, embed)
235
- new_database.save_local("faiss_database")
236
- logging.info(f"Created new FAISS index with {len(docs_to_keep)} documents.")
237
-
238
- # Update uploaded_documents list
239
- uploaded_documents = [doc for doc in uploaded_documents if doc["name"] not in deleted_docs]
240
- save_documents(uploaded_documents)
241
-
242
- return f"Deleted documents: {', '.join(deleted_docs)}", display_documents()
243
-
244
- def chatbot_interface(message, history, model, temperature, num_calls):
245
- if not message.strip():
246
- return "", history
247
-
248
- history = history + [(message, "")]
249
-
250
- try:
251
- for response in respond(message, history, model, temperature, num_calls):
252
- history[-1] = (message, response)
253
- yield history
254
- except gr.CancelledError:
255
- yield history
256
- except Exception as e:
257
- logging.error(f"Unexpected error in chatbot_interface: {str(e)}")
258
- history[-1] = (message, f"An unexpected error occurred: {str(e)}")
259
- yield history
260
-
261
- def retry_last_response(history, model, temperature, num_calls):
262
- if not history:
263
- return history
264
-
265
- last_user_msg = history[-1][0]
266
- history = history[:-1] # Remove the last response
267
-
268
- return chatbot_interface(last_user_msg, history, model, temperature, num_calls)
269
-
270
- def truncate_context(context, max_length=16000):
271
- """Truncate the context to a maximum length."""
272
- if len(context) <= max_length:
273
- return context
274
- return context[:max_length] + "..."
275
-
276
- def get_response_from_duckduckgo(query, model, context, num_calls=1, temperature=0.2):
277
- logging.info(f"Using DuckDuckGo chat with model: {model}")
278
- ddg_model = model.split('/')[-1] # Extract the model name from the full string
279
-
280
- # Truncate the context to avoid exceeding input limits
281
- truncated_context = truncate_context(context)
282
-
283
- full_response = ""
284
- for _ in range(num_calls):
285
- try:
286
- # Include truncated context in the query
287
- contextualized_query = f"Using the following context:\n{truncated_context}\n\nUser question: {query}"
288
- results = DDGS().chat(contextualized_query, model=ddg_model)
289
- full_response += results + "\n"
290
- logging.info(f"DuckDuckGo API response received. Length: {len(results)}")
291
- except Exception as e:
292
- logging.error(f"Error in generating response from DuckDuckGo: {str(e)}")
293
- yield f"An error occurred with the {model} model: {str(e)}. Please try again."
294
- return
295
-
296
- yield full_response.strip()
297
-
298
  class ConversationManager:
299
  def __init__(self):
300
  self.history = []
@@ -360,233 +87,9 @@ def summarize_web_results(query: str, search_results: List[Dict[str, str]], conv
360
  except Exception as e:
361
  return f"An error occurred during summarization: {str(e)}"
362
 
363
- def get_response_from_gemini(query, model, selected_docs, file_type, num_calls=1, temperature=0.2):
364
- # Configure the Gemini API
365
- genai.configure(api_key=os.environ["GEMINI_API_KEY"])
366
-
367
- # Define the model
368
- gemini_model = genai.GenerativeModel(
369
- model_name="gemini-1.5-flash",
370
- generation_config={
371
- "temperature": temperature,
372
- "top_p": 1,
373
- "top_k": 1,
374
- "max_output_tokens": 20000,
375
- },
376
- )
377
-
378
- if file_type == "excel":
379
- # Excel functionality remains the same
380
-
381
- system_instruction = """You are a highly specialized Python programmer with deep expertise in data analysis and visualization using Excel spreadsheets.
382
- Your primary goal is to generate accurate and efficient Python code to perform calculations or create visualizations based on the user's requests.
383
- Strictly use the data provided to write code that identifies key metrics, trends, and significant details relevant to the query.
384
- Do not make assumptions or include any information that is not explicitly supported by the dataset.
385
- If the user requests a calculation, provide the appropriate Python code to execute it, and if a visualization is needed, generate code using the matplotlib library to create the chart.
386
- Based on the following data extracted from Excel spreadsheets:\n{context}\n\nPlease provide the Python code needed to execute the following task: '{query}'.
387
- Ensure that the code is derived directly from the dataset.
388
- If a chart is requested, use the matplotlib library to generate the appropriate visualization."""
389
-
390
- full_prompt = f"{system_instruction}\n\nContext:\n{selected_docs}\n\nUser query: {query}"
391
-
392
- elif file_type == "pdf":
393
- # PDF functionality similar to get_response_from_pdf
394
- embed = get_embeddings()
395
- if os.path.exists("faiss_database"):
396
- database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
397
- else:
398
- yield "No documents available. Please upload PDF documents to answer questions."
399
- return
400
-
401
- # Pre-filter the documents
402
- filtered_docs = [doc for doc_id, doc in database.docstore._dict.items()
403
- if isinstance(doc, Document) and doc.metadata.get("source") in selected_docs]
404
-
405
- if not filtered_docs:
406
- yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
407
- return
408
-
409
- # Create a new FAISS index with only the selected documents
410
- filtered_db = FAISS.from_documents(filtered_docs, embed)
411
-
412
- retriever = filtered_db.as_retriever(search_kwargs={"k": 10})
413
- relevant_docs = retriever.get_relevant_documents(query)
414
-
415
- context_str = "\n".join([doc.page_content for doc in relevant_docs])
416
-
417
- system_instruction = """You are a highly specialized financial analyst assistant with expertise in analyzing and summarizing financial documents.
418
- Your goal is to provide accurate, detailed, and precise summaries based on the context provided.
419
- Avoid making assumptions or adding information that is not explicitly supported by the context from the PDF documents.
420
- Using the following context from the PDF documents:\n{context_str}\n\nPlease generate a step-by-step reasoning before arriving at a comprehensive and accurate summary addressing the following question: '{query}'.
421
- Ensure your response is strictly based on the provided context, highlighting key financial metrics, trends, and significant details relevant to the query.
422
- Avoid any speculative or unverified information."""
423
-
424
- full_prompt = f"{system_instruction}\n\nContext:\n{context_str}\n\nUser query: {query}\n\nPlease generate a step-by-step reasoning before arriving at a comprehensive and accurate summary addressing the question. Ensure your response is strictly based on the provided context, highlighting key metrics, trends, and significant details relevant to the query. Avoid any speculative or unverified information."
425
-
426
- else:
427
- raise ValueError("Invalid file type. Use 'excel' or 'pdf'.")
428
-
429
- full_response = ""
430
- for _ in range(num_calls):
431
- try:
432
- # Generate content with streaming enabled
433
- response = gemini_model.generate_content(full_prompt, stream=True)
434
- for chunk in response:
435
- if chunk.text:
436
- full_response += chunk.text
437
- yield full_response # Yield the accumulated response so far
438
- except Exception as e:
439
- yield f"An error occurred with the Gemini model: {str(e)}. Please try again."
440
-
441
- if not full_response:
442
- yield "No response generated from the Gemini model."
443
-
444
- def get_response_from_excel(query, model, context, num_calls=3, temperature=0.2):
445
- logging.info(f"Getting response from Excel using model: {model}")
446
-
447
- messages = [
448
- {"role": "system", "content": "You are a highly specialized Python programmer with deep expertise in data analysis and visualization using Excel spreadsheets. Your primary goal is to generate accurate and efficient Python code to perform calculations or create visualizations based on the user's requests. Strictly use the data provided to write code that identifies key metrics, trends, and significant details relevant to the query. Do not make assumptions or include any information that is not explicitly supported by the dataset. If the user requests a calculation, provide the appropriate Python code to execute it, and if a visualization is needed, generate code using the matplotlib library to create the chart."},
449
- {"role": "user", "content": f"Based on the following data extracted from Excel spreadsheets:\n{context}\n\nPlease provide the Python code needed to execute the following task: '{query}'. Ensure that the code is derived directly from the dataset. If a chart is requested, use the matplotlib library to generate the appropriate visualization."}
450
- ]
451
-
452
- if model.startswith("duckduckgo/"):
453
- # Use DuckDuckGo chat with context
454
- return get_response_from_duckduckgo(query, model, context, num_calls, temperature)
455
- elif model == "@cf/meta/llama-3.1-8b-instruct":
456
- # Use Cloudflare API
457
- return get_response_from_cloudflare(prompt="", context=context, query=query, num_calls=num_calls, temperature=temperature, search_type="excel")
458
- else:
459
- # Use Hugging Face API
460
- client = InferenceClient(model, token=huggingface_token)
461
-
462
- response = ""
463
- for i in range(num_calls):
464
- logging.info(f"API call {i+1}/{num_calls}")
465
- for message in client.chat_completion(
466
- messages=messages,
467
- max_tokens=20000,
468
- temperature=temperature,
469
- stream=True,
470
- top_p=0.2,
471
- ):
472
- if message.choices and message.choices[0].delta and message.choices[0].delta.content:
473
- chunk = message.choices[0].delta.content
474
- response += chunk
475
- yield response # Yield partial response
476
-
477
- logging.info("Finished generating response for Excel data")
478
-
479
- def truncate_context(context, max_chars=10000):
480
- """Truncate context to a maximum number of characters."""
481
- if len(context) <= max_chars:
482
- return context
483
- return context[:max_chars] + "..."
484
-
485
- def get_response_from_llama(query, model, selected_docs, file_type, num_calls=1, temperature=0.2):
486
- logging.info(f"Getting response from Llama using model: {model}")
487
-
488
- # Initialize the Hugging Face client
489
- client = InferenceClient(model, token=huggingface_token)
490
-
491
- if file_type == "excel":
492
- # Excel functionality
493
- system_instruction = """You are a highly specialized Python programmer with deep expertise in data analysis and visualization using Excel spreadsheets.
494
- Your primary goal is to generate accurate and efficient Python code to perform calculations or create visualizations based on the user's requests.
495
- Strictly use the data provided to write code that identifies key metrics, trends, and significant details relevant to the query.
496
- Do not make assumptions or include any information that is not explicitly supported by the dataset.
497
- If the user requests a calculation, provide the appropriate Python code to execute it, and if a visualization is needed, generate code using the matplotlib library to create the chart."""
498
-
499
- # Get the context from selected Excel documents
500
- embed = get_embeddings()
501
- office_database = FAISS.load_local("office_faiss_database", embed, allow_dangerous_deserialization=True)
502
- retriever = office_database.as_retriever(search_kwargs={"k": 20})
503
- relevant_docs = retriever.get_relevant_documents(query)
504
- context = "\n".join([doc.page_content for doc in relevant_docs if doc.metadata["source"] in selected_docs])
505
-
506
- # Truncate context
507
- context = truncate_context(context)
508
-
509
- messages = [
510
- {"role": "system", "content": system_instruction},
511
- {"role": "user", "content": f"Based on the following data extracted from Excel spreadsheets:\n{context}\n\nPlease provide the Python code needed to execute the following task: '{query}'. Ensure that the code is derived directly from the dataset. If a chart is requested, use the matplotlib library to generate the appropriate visualization."}
512
- ]
513
-
514
- elif file_type == "pdf":
515
- # PDF functionality
516
- embed = get_embeddings()
517
- pdf_database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
518
-
519
- retriever = pdf_database.as_retriever(search_kwargs={"k": 10})
520
- relevant_docs = retriever.get_relevant_documents(query)
521
-
522
- context_str = "\n".join([doc.page_content for doc in relevant_docs if doc.metadata["source"] in selected_docs])
523
-
524
- # Truncate context
525
- context_str = truncate_context(context_str)
526
-
527
- system_instruction = """You are an AI assistant designed to provide detailed, step-by-step responses. Your outputs should follow this structure:
528
-
529
- 1. Begin with a <thinking> section. Everything in this section is invisible to the user.
530
- 2. Inside the thinking section:
531
- a. Briefly analyze the question and outline your approach.
532
- b. Present a clear plan of steps to solve the problem.
533
- c. Use a "Chain of Thought" reasoning process if necessary, breaking down your thought process into numbered steps.
534
- 3. Include a <reflection> section for each idea where you:
535
- a. Review your reasoning.
536
- b. Check for potential errors or oversights.
537
- c. Confirm or adjust your conclusion if necessary.
538
- 4. Be sure to close all reflection sections.
539
- 5. Close the thinking section with </thinking>.
540
- 6. Provide your final answer in an <output> section.
541
-
542
- Always use these tags in your responses. Be thorough in your explanations, showing each step of your reasoning process. Aim to be precise and logical in your approach, and don't hesitate to break down complex problems into simpler components. Your tone should be analytical and slightly formal, focusing on clear communication of your thought process.
543
-
544
- Remember: Both <thinking> and <reflection> MUST be tags and must be closed at their conclusion
545
-
546
- Make sure all <tags> are on separate lines with no other text. Do not include other text on a line containing a tag."""
547
-
548
- messages = [
549
- {"role": "system", "content": system_instruction},
550
- {"role": "user", "content": f"Using the following context from the PDF documents:\n{context_str}\n\nPlease generate a step-by-step reasoning before arriving at a comprehensive and accurate summary addressing the following question: '{query}'. Ensure your response is strictly based on the provided context, highlighting key metrics, trends, and significant details relevant to the query. Avoid any speculative or unverified information."}
551
- ]
552
-
553
- else:
554
- raise ValueError("Invalid file type. Use 'excel' or 'pdf'.")
555
-
556
- full_response = ""
557
- for _ in range(num_calls):
558
- try:
559
- # Generate content with streaming enabled
560
- for response in client.chat_completion(
561
- messages=messages, # Pass messages in the required format
562
- max_tokens=3000, # Reduced to ensure we stay within token limits
563
- temperature=temperature,
564
- stream=True,
565
- top_p=0.9,
566
- ):
567
- # Check the structure of the response object
568
- if isinstance(response, dict) and "choices" in response:
569
- for choice in response["choices"]:
570
- if "delta" in choice and "content" in choice["delta"]:
571
- chunk = choice["delta"]["content"]
572
- full_response += chunk
573
- yield full_response # Yield the accumulated response so far
574
- else:
575
- logging.error("Unexpected response format or missing attributes in the response object.")
576
- break
577
- except Exception as e:
578
- logging.error(f"Error during API call: {str(e)}")
579
- yield f"An error occurred with the Llama model: {str(e)}. Please try again."
580
-
581
- if not full_response:
582
- logging.warning("No response generated from the Llama model")
583
- yield "No response generated from the Llama model."
584
-
585
- # Modify the existing respond function to handle both PDF and web search
586
- def respond(message, history, model, temperature, num_calls, use_web_search, selected_docs):
587
  logging.info(f"User Query: {message}")
588
  logging.info(f"Model Used: {model}")
589
- logging.info(f"Selected Documents: {selected_docs}")
590
  logging.info(f"Use Web Search: {use_web_search}")
591
 
592
  if use_web_search:
@@ -612,243 +115,7 @@ def respond(message, history, model, temperature, num_calls, use_web_search, sel
612
  else:
613
  yield "Unable to generate a response. Please try a different query."
614
  else:
615
- try:
616
- embed = get_embeddings()
617
- pdf_database = None
618
- office_database = None
619
-
620
- if os.path.exists("faiss_database"):
621
- pdf_database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
622
-
623
- if os.path.exists("office_faiss_database"):
624
- office_database = FAISS.load_local("office_faiss_database", embed, allow_dangerous_deserialization=True)
625
-
626
- if not pdf_database and not office_database:
627
- yield "No documents available. Please upload documents to answer questions."
628
- return
629
-
630
- all_relevant_docs = []
631
- if pdf_database:
632
- pdf_retriever = pdf_database.as_retriever(search_kwargs={"k": 10})
633
- all_relevant_docs.extend(pdf_retriever.get_relevant_documents(message))
634
-
635
- if office_database:
636
- office_retriever = office_database.as_retriever(search_kwargs={"k": 10})
637
- all_relevant_docs.extend(office_retriever.get_relevant_documents(message))
638
-
639
- relevant_docs = [doc for doc in all_relevant_docs if doc.metadata["source"] in selected_docs]
640
-
641
- if not relevant_docs:
642
- yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
643
- return
644
-
645
- # Separate Excel documents from others
646
- excel_docs = [doc for doc in relevant_docs if doc.metadata["source"].lower().endswith(('.xlsx', '.xls'))]
647
- other_docs = [doc for doc in relevant_docs if not doc.metadata["source"].lower().endswith(('.xlsx', '.xls'))]
648
-
649
- excel_context = "\n".join([doc.page_content for doc in excel_docs])
650
- other_context = "\n".join([doc.page_content for doc in other_docs])
651
-
652
- logging.info(f"Excel context length: {len(excel_context)}")
653
- logging.info(f"Other context length: {len(other_context)}")
654
-
655
- # Process Excel documents
656
- if excel_docs:
657
- file_type = "excel"
658
- if model == "gemini-1.5-flash":
659
- for chunk in get_response_from_gemini(message, model, selected_docs, file_type, num_calls, temperature):
660
- yield chunk
661
- elif "llama" in model.lower():
662
- for chunk in get_response_from_llama(message, model, selected_docs, file_type, num_calls, temperature):
663
- yield chunk
664
- else:
665
- for response in get_response_from_excel(message, model, excel_context, num_calls, temperature):
666
- yield response
667
-
668
- # Process other documents (PDF, Word)
669
- if other_docs:
670
- file_type = "pdf"
671
- if model == "gemini-1.5-flash":
672
- for chunk in get_response_from_gemini(message, model, selected_docs, file_type, num_calls, temperature):
673
- yield chunk
674
- elif model == "@cf/meta/llama-3.1-8b-instruct":
675
- for response in get_response_from_cloudflare(prompt="", context=other_context, query=message, num_calls=num_calls, temperature=temperature, search_type="document"):
676
- yield response
677
- elif "llama" in model.lower():
678
- for chunk in get_response_from_llama(message, model, selected_docs, file_type, num_calls, temperature):
679
- yield chunk
680
- else:
681
- for response in get_response_from_pdf(message, model, selected_docs, num_calls, temperature):
682
- yield response
683
-
684
- except Exception as e:
685
- logging.error(f"Error with {model}: {str(e)}")
686
- if "microsoft/Phi-3-mini-4k-instruct" in model:
687
- logging.info("Falling back to Mistral model due to Phi-3 error")
688
- fallback_model = "mistralai/Mistral-7B-Instruct-v0.3"
689
- yield from respond(message, history, fallback_model, temperature, num_calls, use_web_search, selected_docs)
690
- else:
691
- yield f"An error occurred with the {model} model: {str(e)}. Please try again or select a different model."
692
-
693
- logging.basicConfig(level=logging.DEBUG)
694
-
695
- def get_response_from_cloudflare(prompt, context, query, num_calls=3, temperature=0.2, search_type="pdf"):
696
- headers = {
697
- "Authorization": f"Bearer {API_TOKEN}",
698
- "Content-Type": "application/json"
699
- }
700
- model = "@cf/meta/llama-3.1-8b-instruct"
701
-
702
- if search_type == "pdf":
703
- instruction = f"""Using the following context from the PDF documents:
704
- {context}
705
- Write a detailed and complete response that answers the following user question: '{query}'"""
706
- else: # web search
707
- instruction = f"""Using the following context:
708
- {context}
709
- Write a detailed and complete research document that fulfills the following user request: '{query}'
710
- After writing the document, please provide a list of sources used in your response."""
711
-
712
- inputs = [
713
- {"role": "system", "content": instruction},
714
- {"role": "user", "content": query}
715
- ]
716
-
717
- payload = {
718
- "messages": inputs,
719
- "stream": True,
720
- "temperature": temperature,
721
- "max_tokens": 32000
722
- }
723
-
724
- full_response = ""
725
- for i in range(num_calls):
726
- try:
727
- with requests.post(f"{API_BASE_URL}{model}", headers=headers, json=payload, stream=True) as response:
728
- if response.status_code == 200:
729
- for line in response.iter_lines():
730
- if line:
731
- try:
732
- json_response = json.loads(line.decode('utf-8').split('data: ')[1])
733
- if 'response' in json_response:
734
- chunk = json_response['response']
735
- full_response += chunk
736
- yield full_response
737
- except (json.JSONDecodeError, IndexError) as e:
738
- logging.error(f"Error parsing streaming response: {str(e)}")
739
- continue
740
- else:
741
- logging.error(f"HTTP Error: {response.status_code}, Response: {response.text}")
742
- yield f"I apologize, but I encountered an HTTP error: {response.status_code}. Please try again later."
743
- except Exception as e:
744
- logging.error(f"Error in generating response from Cloudflare: {str(e)}")
745
- yield f"I apologize, but an error occurred: {str(e)}. Please try again later."
746
-
747
- if not full_response:
748
- yield "I apologize, but I couldn't generate a response at this time. Please try again later."
749
-
750
- def create_web_search_vectors(search_results):
751
- embed = get_embeddings()
752
-
753
- documents = []
754
- for result in search_results:
755
- if 'body' in result:
756
- content = f"{result['title']}\n{result['body']}\nSource: {result['href']}"
757
- documents.append(Document(page_content=content, metadata={"source": result['href']}))
758
-
759
- return FAISS.from_documents(documents, embed)
760
-
761
- def get_response_from_pdf(query, model, selected_docs, num_calls=3, temperature=0.2):
762
- logging.info(f"Entering get_response_from_pdf with query: {query}, model: {model}, selected_docs: {selected_docs}")
763
-
764
- embed = get_embeddings()
765
- if os.path.exists("faiss_database"):
766
- logging.info("Loading FAISS database")
767
- database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
768
- else:
769
- logging.warning("No FAISS database found")
770
- yield "No documents available. Please upload PDF documents to answer questions."
771
- return
772
-
773
- # Pre-filter the documents
774
- filtered_docs = []
775
- for doc_id, doc in database.docstore._dict.items():
776
- if isinstance(doc, Document) and doc.metadata.get("source") in selected_docs:
777
- filtered_docs.append(doc)
778
-
779
- logging.info(f"Number of documents after pre-filtering: {len(filtered_docs)}")
780
-
781
- if not filtered_docs:
782
- logging.warning(f"No documents found for the selected sources: {selected_docs}")
783
- yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
784
- return
785
-
786
- # Create a new FAISS index with only the selected documents
787
- filtered_db = FAISS.from_documents(filtered_docs, embed)
788
-
789
- retriever = filtered_db.as_retriever(search_kwargs={"k": 10})
790
- logging.info(f"Retrieving relevant documents for query: {query}")
791
- relevant_docs = retriever.get_relevant_documents(query)
792
- logging.info(f"Number of relevant documents retrieved: {len(relevant_docs)}")
793
-
794
- for doc in relevant_docs:
795
- logging.info(f"Document source: {doc.metadata['source']}")
796
- logging.info(f"Document content preview: {doc.page_content[:100]}...") # Log first 100 characters of each document
797
-
798
- context_str = "\n".join([doc.page_content for doc in relevant_docs])
799
- logging.info(f"Total context length: {len(context_str)}")
800
-
801
- if model == "@cf/meta/llama-3.1-8b-instruct":
802
- logging.info("Using Cloudflare API")
803
- # Use Cloudflare API with the retrieved context
804
- for response in get_response_from_cloudflare(prompt="", context=context_str, query=query, num_calls=num_calls, temperature=temperature, search_type="pdf"):
805
- yield response
806
- else:
807
- logging.info("Using Hugging Face API")
808
- # Use Hugging Face API
809
- messages = [
810
- {"role": "system", "content": """You are an AI assistant designed to provide detailed, step-by-step responses. Your outputs should follow this structure:
811
-
812
- 1. Begin with a <thinking> section. Everything in this section is invisible to the user.
813
- 2. Inside the thinking section:
814
- a. Briefly analyze the question and outline your approach.
815
- b. Present a clear plan of steps to solve the problem.
816
- c. Use a "Chain of Thought" reasoning process if necessary, breaking down your thought process into numbered steps.
817
- 3. Include a <reflection> section for each idea where you:
818
- a. Review your reasoning.
819
- b. Check for potential errors or oversights.
820
- c. Confirm or adjust your conclusion if necessary.
821
- 4. Be sure to close all reflection sections.
822
- 5. Close the thinking section with </thinking>.
823
- 6. Provide your final answer in an <output> section.
824
-
825
- Always use these tags in your responses. Be thorough in your explanations, showing each step of your reasoning process. Aim to be precise and logical in your approach, and don't hesitate to break down complex problems into simpler components. Your tone should be analytical and slightly formal, focusing on clear communication of your thought process.
826
-
827
- Remember: Both <thinking> and <reflection> MUST be tags and must be closed at their conclusion
828
-
829
- Make sure all <tags> are on separate lines with no other text. Do not include other text on a line containing a tag."""},
830
-
831
- {"role": "user", "content": f"Using the following context from the PDF documents:\n{context_str}\n\nPlease generate a step-by-step reasoning before arriving at a comprehensive and accurate summary addressing the following question: '{query}'. Ensure your response is strictly based on the provided context, highlighting key financial metrics, trends, and significant details relevant to the query. Avoid any speculative or unverified information."}
832
- ]
833
-
834
- client = InferenceClient(model, token=huggingface_token)
835
-
836
- response = ""
837
- for i in range(num_calls):
838
- logging.info(f"API call {i+1}/{num_calls}")
839
- for message in client.chat_completion(
840
- messages=messages,
841
- max_tokens=20000,
842
- temperature=temperature,
843
- stream=True,
844
- top_p=0.8,
845
- ):
846
- if message.choices and message.choices[0].delta and message.choices[0].delta.content:
847
- chunk = message.choices[0].delta.content
848
- response += chunk
849
- yield response # Yield partial response
850
-
851
- logging.info("Finished generating response")
852
 
853
  def vote(data: gr.LikeData):
854
  if data.liked:
@@ -868,62 +135,37 @@ css = """
868
  }
869
  """
870
 
871
- uploaded_documents = []
872
-
873
- def display_documents():
874
- return gr.CheckboxGroup(
875
- choices=[doc["name"] for doc in uploaded_documents],
876
- value=[doc["name"] for doc in uploaded_documents if doc["selected"]],
877
- label="Select documents to query or delete"
878
- )
879
-
880
  def initial_conversation():
881
  return [
882
- (None, "Welcome! I'm your AI assistant for web search and PDF analysis. Here's how you can use me:\n\n"
883
- "1. Set the toggle for Web Search and PDF Search from the checkbox in Additional Inputs drop down window\n"
884
- "2. Use web search to find information\n"
885
- "3. Upload the documents and ask questions about uploaded PDF documents by selecting your respective document\n"
886
- "4. For any queries feel free to reach out @[email protected] or discord - shreyas094\n\n"
887
- "To get started, upload some PDFs or ask me a question!")
888
  ]
889
- # Add this new function
890
- def refresh_documents():
891
- global uploaded_documents
892
- uploaded_documents = load_documents()
893
- return display_documents()
894
-
895
- # Define the checkbox outside the demo block
896
- document_selector = gr.CheckboxGroup(label="Select documents to query")
897
-
898
- use_web_search = gr.Checkbox(label="Use Web Search", value=False)
899
 
900
- custom_placeholder = "Ask a question (Note: You can toggle between Web Search and PDF Chat in Additional Inputs below)"
901
-
902
- # Update the demo interface
903
- # Update the Gradio interface
904
  demo = gr.ChatInterface(
905
  respond,
906
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=True, render=False),
907
  additional_inputs=[
908
- gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[3]),
909
  gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),
910
  gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),
911
- gr.Checkbox(label="Use Web Search", value=True),
912
- gr.CheckboxGroup(label="Select documents to query")
913
  ],
914
- title="AI-powered PDF Chat and Web Search Assistant",
915
- description="Chat with your PDFs or use web search to answer questions.",
916
  theme=gr.Theme.from_hub("allenai/gradio-theme"),
917
  css=css,
918
  examples=[
919
- ["Tell me about the contents of the uploaded PDFs."],
920
- ["What are the main topics discussed in the documents?"],
921
- ["Can you summarize the key points from the PDFs?"],
922
- ["What's the latest news about artificial intelligence?"]
923
  ],
924
  cache_examples=False,
925
  analytics_enabled=False,
926
- textbox=gr.Textbox(placeholder="Ask a question about the uploaded PDFs or any topic", container=False, scale=7),
927
  chatbot = gr.Chatbot(
928
  show_copy_button=True,
929
  likeable=True,
@@ -933,51 +175,5 @@ demo = gr.ChatInterface(
933
  )
934
  )
935
 
936
- # Add file upload functionality
937
- with demo:
938
- gr.Markdown("## Upload and Manage PDF Documents")
939
- with gr.Row():
940
- file_input = gr.Files(label="Upload your documents", file_types=[".pdf", ".docx", ".xlsx", ".xls"])
941
- parser_dropdown = gr.Dropdown(choices=["pypdf", "llamaparse", "office"], label="Select PDF Parser", value="llamaparse")
942
- update_button = gr.Button("Upload Document")
943
- refresh_button = gr.Button("Refresh Document List")
944
-
945
- update_output = gr.Textbox(label="Update Status")
946
- delete_button = gr.Button("Delete Selected Documents")
947
-
948
- # Update both the output text and the document selector
949
- update_button.click(
950
- update_vectors,
951
- inputs=[file_input, parser_dropdown],
952
- outputs=[update_output, demo.additional_inputs[-1]] # Use the CheckboxGroup from additional_inputs
953
- )
954
-
955
- # Add the refresh button functionality
956
- refresh_button.click(
957
- refresh_documents,
958
- inputs=[],
959
- outputs=[demo.additional_inputs[-1]] # Use the CheckboxGroup from additional_inputs
960
- )
961
-
962
- # Add the delete button functionality
963
- delete_button.click(
964
- delete_documents,
965
- inputs=[demo.additional_inputs[-1]], # Use the CheckboxGroup from additional_inputs
966
- outputs=[update_output, demo.additional_inputs[-1]]
967
- )
968
-
969
- gr.Markdown(
970
- """
971
- ## How to use
972
- 1. Upload PDF documents using the file input at the top.
973
- 2. Select the PDF parser (pypdf or llamaparse) and click "Upload Document" to update the vector store.
974
- 3. Select the documents you want to query using the checkboxes.
975
- 4. Ask questions in the chat interface.
976
- 5. Toggle "Use Web Search" to switch between PDF chat and web search.
977
- 6. Adjust Temperature and Number of API Calls to fine-tune the response generation.
978
- 7. Use the provided examples or ask your own questions.
979
- """
980
- )
981
-
982
  if __name__ == "__main__":
983
  demo.launch(share=True)
 
1
  import os
2
  import json
3
+ import logging
4
  import gradio as gr
 
5
  from duckduckgo_search import DDGS
6
  from typing import List, Dict
7
+ from pydantic import BaseModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from huggingface_hub import InferenceClient
9
 
10
  # Set up basic configuration for logging
 
12
 
13
  # Environment variables and configurations
14
  huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
 
 
 
 
 
 
 
 
15
 
16
  MODELS = [
17
  "mistralai/Mistral-7B-Instruct-v0.3",
18
  "mistralai/Mixtral-8x7B-Instruct-v0.1",
 
 
 
 
 
 
 
19
  "duckduckgo/gpt-4o-mini",
20
  "duckduckgo/claude-3-haiku",
21
  "duckduckgo/llama-3.1-70b",
22
  "duckduckgo/mixtral-8x7b"
23
  ]
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  class ConversationManager:
26
  def __init__(self):
27
  self.history = []
 
87
  except Exception as e:
88
  return f"An error occurred during summarization: {str(e)}"
89
 
90
+ def respond(message, history, model, temperature, num_calls, use_web_search):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  logging.info(f"User Query: {message}")
92
  logging.info(f"Model Used: {model}")
 
93
  logging.info(f"Use Web Search: {use_web_search}")
94
 
95
  if use_web_search:
 
115
  else:
116
  yield "Unable to generate a response. Please try a different query."
117
  else:
118
+ yield "Web search is not enabled. Please enable web search to use this feature."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  def vote(data: gr.LikeData):
121
  if data.liked:
 
135
  }
136
  """
137
 
 
 
 
 
 
 
 
 
 
138
  def initial_conversation():
139
  return [
140
+ (None, "Welcome! I'm your AI assistant for web search. Here's how you can use me:\n\n"
141
+ "1. Make sure the 'Use Web Search' checkbox is enabled in the Additional Inputs section.\n"
142
+ "2. Ask me any question, and I'll search the web for the most relevant and up-to-date information.\n"
143
+ "3. You can adjust the model, temperature, and number of API calls in the Additional Inputs section to fine-tune your results.\n\n"
144
+ "To get started, just ask me a question!")
 
145
  ]
 
 
 
 
 
 
 
 
 
 
146
 
147
+ # Create the Gradio interface
 
 
 
148
  demo = gr.ChatInterface(
149
  respond,
 
150
  additional_inputs=[
151
+ gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[0]),
152
  gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),
153
  gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),
154
+ gr.Checkbox(label="Use Web Search", value=True)
 
155
  ],
156
+ title="AI-powered Web Search Assistant",
157
+ description="Ask questions and get answers from the latest web information.",
158
  theme=gr.Theme.from_hub("allenai/gradio-theme"),
159
  css=css,
160
  examples=[
161
+ ["What's the latest news about artificial intelligence?"],
162
+ ["Summarize the current global economic situation."],
163
+ ["What are the top environmental concerns right now?"],
164
+ ["What are the recent breakthroughs in quantum computing?"]
165
  ],
166
  cache_examples=False,
167
  analytics_enabled=False,
168
+ textbox=gr.Textbox(placeholder="Ask any question", container=False, scale=7),
169
  chatbot = gr.Chatbot(
170
  show_copy_button=True,
171
  likeable=True,
 
175
  )
176
  )
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  if __name__ == "__main__":
179
  demo.launch(share=True)