Shreyas094 commited on
Commit
7d20787
1 Parent(s): d56e797

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +737 -67
app.py CHANGED
@@ -1,88 +1,758 @@
1
  import os
2
- import shutil
 
3
  import gradio as gr
4
- from transformers import ReactCodeAgent, HfEngine, Tool
5
- import pandas as pd
6
- import PyPDF2
7
- import io
8
- from openpyxl import Workbook
9
- from gradio import Chatbot
10
- from transformers.agents import stream_to_gradio
11
- from huggingface_hub import login
12
-
13
- # Ensure you have set the HUGGINGFACEHUB_API_TOKEN environment variable
14
- login(os.getenv("HUGGINGFACEHUB_API_TOKEN"))
15
-
16
- llm_engine = HfEngine("meta-llama/Meta-Llama-3.1-70B-Instruct")
17
-
18
- # Define tools for the agent
19
- tools = [
20
- Tool("numpy", "NumPy library for numerical computing"),
21
- Tool("pandas", "Pandas library for data manipulation and analysis"),
22
- Tool("matplotlib", "Matplotlib library for creating visualizations"),
23
- Tool("openpyxl", "OpenPyXL library for working with Excel files"),
24
- Tool("PyPDF2", "PyPDF2 library for working with PDF files"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  ]
26
 
27
- agent = ReactCodeAgent(
28
- tools=tools,
29
- llm_engine=llm_engine,
30
- additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "openpyxl", "PyPDF2"],
31
- max_iterations=15,
 
 
32
  )
33
 
34
- base_prompt = """You are an expert financial data analyst. Your task is to analyze the provided financial PDF document and perform the following:
35
- 1. Accurately locate the financial statements such as the Balance Sheet, Income Statement, and Cash Flow Statement within the PDF.
36
- 2. Extract only the relevant pages containing these financial statements into a pandas DataFrame using tools that are available in the current environment.
37
- 3. Save the DataFrame into an Excel file using the `openpyxl` library, ensuring that no restricted functions like `open()` are used.
38
- 4. Provide the path to the saved Excel file and display a preview of the data extracted by showing the first few rows of the DataFrame with `df.head()`.
39
- Ensure that the code is correctly structured to handle the identification, extraction, processing, and saving of the data into an Excel file, while adhering to the execution environment's constraints.
40
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- def interact_with_agent(file_input):
43
- if os.path.exists("./output"):
44
- shutil.rmtree("./output")
45
- os.makedirs("./output")
46
 
47
- pdf_content = file_input.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- prompt = base_prompt + f"\n\nThe PDF file has been loaded and is available as 'pdf_content' (a bytes object). Use PyPDF2 to read and process this content."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- messages = [gr.ChatMessage(role="user", content=prompt)]
52
- yield messages + [
53
- gr.ChatMessage(role="assistant", content="⏳ _Starting analysis of the financial PDF..._")
 
 
 
 
 
 
 
 
 
 
54
  ]
55
 
56
- excel_file_path = None
57
- for msg in stream_to_gradio(agent, prompt, pdf_content=pdf_content):
58
- messages.append(msg)
59
- if isinstance(msg.content, str) and msg.content.startswith("The Excel file has been saved"):
60
- excel_file_path = msg.content.split(": ")[-1].strip()
61
- yield messages + [
62
- gr.ChatMessage(role="assistant", content="⏳ _Still processing..._")
63
- ]
64
-
65
- if excel_file_path and os.path.exists(excel_file_path):
66
- download_button = gr.File.update(value=excel_file_path, visible=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  else:
68
- download_button = gr.File.update(visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- yield messages, download_button
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- with gr.Blocks(theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue)) as demo:
73
- gr.Markdown("""# Financial Statement Analyzer 📊💼
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- Upload a financial PDF document (like 10-Q or 10-K), and the AI will extract the financial statements into an Excel file!""")
 
 
 
 
 
 
 
 
76
 
77
- file_input = gr.File(label="Upload your financial PDF document")
78
- submit = gr.Button("Analyze Financial Statements", variant="primary")
79
- chatbot = gr.Chatbot(
80
- label="Financial Analyst Agent",
81
- avatar_images=(None, "https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  )
83
- download_output = gr.File(label="Download Excel File", visible=False)
84
 
85
- submit.click(interact_with_agent, inputs=[file_input], outputs=[chatbot, download_output])
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  if __name__ == "__main__":
88
- demo.launch()
 
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
+
21
+
22
+ # Set up basic configuration for logging
23
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
24
+
25
+ # Environment variables and configurations
26
+ huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
27
+ llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")
28
+ ACCOUNT_ID = os.environ.get("CLOUDFARE_ACCOUNT_ID")
29
+ API_TOKEN = os.environ.get("CLOUDFLARE_AUTH_TOKEN")
30
+ API_BASE_URL = "https://api.cloudflare.com/client/v4/accounts/a17f03e0f049ccae0c15cdcf3b9737ce/ai/run/"
31
+
32
+ print(f"ACCOUNT_ID: {ACCOUNT_ID}")
33
+ print(f"CLOUDFLARE_AUTH_TOKEN: {API_TOKEN[:5]}..." if API_TOKEN else "Not set")
34
+
35
+ MODELS = [
36
+ "mistralai/Mistral-7B-Instruct-v0.3",
37
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
38
+ "@cf/meta/llama-3.1-8b-instruct",
39
+ "mistralai/Mistral-Nemo-Instruct-2407",
40
+ "meta-llama/Meta-Llama-3.1-8B-Instruct",
41
+ "duckduckgo/gpt-4o-mini",
42
+ "duckduckgo/claude-3-haiku",
43
+ "duckduckgo/llama-3.1-70b",
44
+ "duckduckgo/mixtral-8x7b"
45
  ]
46
 
47
+ # Initialize LlamaParse
48
+ llama_parser = LlamaParse(
49
+ api_key=llama_cloud_api_key,
50
+ result_type="markdown",
51
+ num_workers=4,
52
+ verbose=True,
53
+ language="en",
54
  )
55
 
56
+ def load_document(file: NamedTemporaryFile, parser: str = "llamaparse") -> List[Document]:
57
+ """Loads and splits the document into pages."""
58
+ if parser == "pypdf":
59
+ loader = PyPDFLoader(file.name)
60
+ return loader.load_and_split()
61
+ elif parser == "llamaparse":
62
+ try:
63
+ documents = llama_parser.load_data(file.name)
64
+ return [Document(page_content=doc.text, metadata={"source": file.name}) for doc in documents]
65
+ except Exception as e:
66
+ print(f"Error using Llama Parse: {str(e)}")
67
+ print("Falling back to PyPDF parser")
68
+ loader = PyPDFLoader(file.name)
69
+ return loader.load_and_split()
70
+ else:
71
+ raise ValueError("Invalid parser specified. Use 'pypdf' or 'llamaparse'.")
72
+
73
+ def get_embeddings():
74
+ return HuggingFaceEmbeddings(model_name="avsolatorio/GIST-Embedding-v0")
75
+
76
+ # Add this at the beginning of your script, after imports
77
+ DOCUMENTS_FILE = "uploaded_documents.json"
78
+
79
+ def load_documents():
80
+ if os.path.exists(DOCUMENTS_FILE):
81
+ with open(DOCUMENTS_FILE, "r") as f:
82
+ return json.load(f)
83
+ return []
84
+
85
+ def save_documents(documents):
86
+ with open(DOCUMENTS_FILE, "w") as f:
87
+ json.dump(documents, f)
88
+
89
+ # Replace the global uploaded_documents with this
90
+ uploaded_documents = load_documents()
91
+
92
+ # Modify the update_vectors function
93
+ def update_vectors(files, parser):
94
+ global uploaded_documents
95
+ logging.info(f"Entering update_vectors with {len(files)} files and parser: {parser}")
96
+
97
+ if not files:
98
+ logging.warning("No files provided for update_vectors")
99
+ return "Please upload at least one PDF file.", display_documents()
100
+
101
+ embed = get_embeddings()
102
+ total_chunks = 0
103
+
104
+ all_data = []
105
+ for file in files:
106
+ logging.info(f"Processing file: {file.name}")
107
+ try:
108
+ data = load_document(file, parser)
109
+ if not data:
110
+ logging.warning(f"No chunks loaded from {file.name}")
111
+ continue
112
+ logging.info(f"Loaded {len(data)} chunks from {file.name}")
113
+ all_data.extend(data)
114
+ total_chunks += len(data)
115
+ if not any(doc["name"] == file.name for doc in uploaded_documents):
116
+ uploaded_documents.append({"name": file.name, "selected": True})
117
+ logging.info(f"Added new document to uploaded_documents: {file.name}")
118
+ else:
119
+ logging.info(f"Document already exists in uploaded_documents: {file.name}")
120
+ except Exception as e:
121
+ logging.error(f"Error processing file {file.name}: {str(e)}")
122
+
123
+ logging.info(f"Total chunks processed: {total_chunks}")
124
+
125
+ if not all_data:
126
+ logging.warning("No valid data extracted from uploaded files")
127
+ return "No valid data could be extracted from the uploaded files. Please check the file contents and try again.", display_documents()
128
+
129
+ try:
130
+ if os.path.exists("faiss_database"):
131
+ logging.info("Updating existing FAISS database")
132
+ database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
133
+ database.add_documents(all_data)
134
+ else:
135
+ logging.info("Creating new FAISS database")
136
+ database = FAISS.from_documents(all_data, embed)
137
+
138
+ database.save_local("faiss_database")
139
+ logging.info("FAISS database saved")
140
+ except Exception as e:
141
+ logging.error(f"Error updating FAISS database: {str(e)}")
142
+ return f"Error updating vector store: {str(e)}", display_documents()
143
+
144
+ # Save the updated list of documents
145
+ save_documents(uploaded_documents)
146
+
147
+ # Return a tuple with the status message and the updated document list
148
+ return f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files using {parser}.", display_documents()
149
+
150
+
151
+ def delete_documents(selected_docs):
152
+ global uploaded_documents
153
+
154
+ if not selected_docs:
155
+ return "No documents selected for deletion.", display_documents()
156
+
157
+ embed = get_embeddings()
158
+ database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
159
+
160
+ deleted_docs = []
161
+ docs_to_keep = []
162
+ for doc in database.docstore._dict.values():
163
+ if doc.metadata.get("source") not in selected_docs:
164
+ docs_to_keep.append(doc)
165
+ else:
166
+ deleted_docs.append(doc.metadata.get("source", "Unknown"))
167
+
168
+ # Print debugging information
169
+ logging.info(f"Total documents before deletion: {len(database.docstore._dict)}")
170
+ logging.info(f"Documents to keep: {len(docs_to_keep)}")
171
+ logging.info(f"Documents to delete: {len(deleted_docs)}")
172
+
173
+ if not docs_to_keep:
174
+ # If all documents are deleted, remove the FAISS database directory
175
+ if os.path.exists("faiss_database"):
176
+ shutil.rmtree("faiss_database")
177
+ logging.info("All documents deleted. Removed FAISS database directory.")
178
+ else:
179
+ # Create new FAISS index with remaining documents
180
+ new_database = FAISS.from_documents(docs_to_keep, embed)
181
+ new_database.save_local("faiss_database")
182
+ logging.info(f"Created new FAISS index with {len(docs_to_keep)} documents.")
183
+
184
+ # Update uploaded_documents list
185
+ uploaded_documents = [doc for doc in uploaded_documents if doc["name"] not in deleted_docs]
186
+ save_documents(uploaded_documents)
187
+
188
+ return f"Deleted documents: {', '.join(deleted_docs)}", display_documents()
189
+
190
+ def generate_chunked_response(prompt, model, max_tokens=10000, num_calls=3, temperature=0.2, should_stop=False):
191
+ print(f"Starting generate_chunked_response with {num_calls} calls")
192
+ full_response = ""
193
+ messages = [{"role": "user", "content": prompt}]
194
+
195
+ if model == "@cf/meta/llama-3.1-8b-instruct":
196
+ # Cloudflare API
197
+ for i in range(num_calls):
198
+ print(f"Starting Cloudflare API call {i+1}")
199
+ if should_stop:
200
+ print("Stop clicked, breaking loop")
201
+ break
202
+ try:
203
+ response = requests.post(
204
+ f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/meta/llama-3.1-8b-instruct",
205
+ headers={"Authorization": f"Bearer {API_TOKEN}"},
206
+ json={
207
+ "stream": true,
208
+ "messages": [
209
+ {"role": "system", "content": "You are a friendly assistant"},
210
+ {"role": "user", "content": prompt}
211
+ ],
212
+ "max_tokens": max_tokens,
213
+ "temperature": temperature
214
+ },
215
+ stream=true
216
+ )
217
+
218
+ for line in response.iter_lines():
219
+ if should_stop:
220
+ print("Stop clicked during streaming, breaking")
221
+ break
222
+ if line:
223
+ try:
224
+ json_data = json.loads(line.decode('utf-8').split('data: ')[1])
225
+ chunk = json_data['response']
226
+ full_response += chunk
227
+ except json.JSONDecodeError:
228
+ continue
229
+ print(f"Cloudflare API call {i+1} completed")
230
+ except Exception as e:
231
+ print(f"Error in generating response from Cloudflare: {str(e)}")
232
+ else:
233
+ # Original Hugging Face API logic
234
+ client = InferenceClient(model, token=huggingface_token)
235
+
236
+ for i in range(num_calls):
237
+ print(f"Starting Hugging Face API call {i+1}")
238
+ if should_stop:
239
+ print("Stop clicked, breaking loop")
240
+ break
241
+ try:
242
+ for message in client.chat_completion(
243
+ messages=messages,
244
+ max_tokens=max_tokens,
245
+ temperature=temperature,
246
+ stream=True,
247
+ ):
248
+ if should_stop:
249
+ print("Stop clicked during streaming, breaking")
250
+ break
251
+ if message.choices and message.choices[0].delta and message.choices[0].delta.content:
252
+ chunk = message.choices[0].delta.content
253
+ full_response += chunk
254
+ print(f"Hugging Face API call {i+1} completed")
255
+ except Exception as e:
256
+ print(f"Error in generating response from Hugging Face: {str(e)}")
257
+
258
+ # Clean up the response
259
+ clean_response = re.sub(r'<s>\[INST\].*?\[/INST\]\s*', '', full_response, flags=re.DOTALL)
260
+ clean_response = clean_response.replace("Using the following context:", "").strip()
261
+ clean_response = clean_response.replace("Using the following context from the PDF documents:", "").strip()
262
+
263
+ # Remove duplicate paragraphs and sentences
264
+ paragraphs = clean_response.split('\n\n')
265
+ unique_paragraphs = []
266
+ for paragraph in paragraphs:
267
+ if paragraph not in unique_paragraphs:
268
+ sentences = paragraph.split('. ')
269
+ unique_sentences = []
270
+ for sentence in sentences:
271
+ if sentence not in unique_sentences:
272
+ unique_sentences.append(sentence)
273
+ unique_paragraphs.append('. '.join(unique_sentences))
274
+
275
+ final_response = '\n\n'.join(unique_paragraphs)
276
+
277
+ print(f"Final clean response: {final_response[:100]}...")
278
+ return final_response
279
+
280
+ def chatbot_interface(message, history, model, temperature, num_calls):
281
+ if not message.strip():
282
+ return "", history
283
+
284
+ history = history + [(message, "")]
285
+
286
+ try:
287
+ for response in respond(message, history, model, temperature, num_calls):
288
+ history[-1] = (message, response)
289
+ yield history
290
+ except gr.CancelledError:
291
+ yield history
292
+ except Exception as e:
293
+ logging.error(f"Unexpected error in chatbot_interface: {str(e)}")
294
+ history[-1] = (message, f"An unexpected error occurred: {str(e)}")
295
+ yield history
296
+
297
+ def retry_last_response(history, model, temperature, num_calls):
298
+ if not history:
299
+ return history
300
+
301
+ last_user_msg = history[-1][0]
302
+ history = history[:-1] # Remove the last response
303
+
304
+ return chatbot_interface(last_user_msg, history, model, temperature, num_calls)
305
+
306
+ def truncate_context(context, max_length=16000):
307
+ """Truncate the context to a maximum length."""
308
+ if len(context) <= max_length:
309
+ return context
310
+ return context[:max_length] + "..."
311
+
312
+ def get_response_from_duckduckgo(query, model, context, num_calls=1, temperature=0.2):
313
+ logging.info(f"Using DuckDuckGo chat with model: {model}")
314
+ ddg_model = model.split('/')[-1] # Extract the model name from the full string
315
+
316
+ # Truncate the context to avoid exceeding input limits
317
+ truncated_context = truncate_context(context)
318
+
319
+ full_response = ""
320
+ for _ in range(num_calls):
321
+ try:
322
+ # Include truncated context in the query
323
+ contextualized_query = f"Using the following context:\n{truncated_context}\n\nUser question: {query}"
324
+ results = DDGS().chat(contextualized_query, model=ddg_model)
325
+ full_response += results + "\n"
326
+ logging.info(f"DuckDuckGo API response received. Length: {len(results)}")
327
+ except Exception as e:
328
+ logging.error(f"Error in generating response from DuckDuckGo: {str(e)}")
329
+ yield f"An error occurred with the {model} model: {str(e)}. Please try again."
330
+ return
331
+
332
+ yield full_response.strip()
333
+
334
+ class ConversationManager:
335
+ def __init__(self):
336
+ self.history = []
337
+ self.current_context = None
338
 
339
+ def add_interaction(self, query, response):
340
+ self.history.append((query, response))
341
+ self.current_context = f"Previous query: {query}\nPrevious response summary: {response[:200]}..."
 
342
 
343
+ def get_context(self):
344
+ return self.current_context
345
+
346
+ conversation_manager = ConversationManager()
347
+
348
+ def get_web_search_results(query: str, max_results: int = 10) -> List[Dict[str, str]]:
349
+ try:
350
+ results = list(DDGS().text(query, max_results=max_results))
351
+ if not results:
352
+ print(f"No results found for query: {query}")
353
+ return results
354
+ except Exception as e:
355
+ print(f"An error occurred during web search: {str(e)}")
356
+ return [{"error": f"An error occurred during web search: {str(e)}"}]
357
+
358
+ def rephrase_query(original_query: str, conversation_manager: ConversationManager) -> str:
359
+ context = conversation_manager.get_context()
360
+ if context:
361
+ prompt = f"""You are a highly intelligent conversational chatbot. Your task is to analyze the given context and new query, then decide whether to rephrase the query with or without incorporating the context. Follow these steps:
362
+
363
+ 1. Determine if the new query is a continuation of the previous conversation or an entirely new topic.
364
+ 2. If it's a continuation, rephrase the query by incorporating relevant information from the context to make it more specific and contextual.
365
+ 3. If it's a new topic, rephrase the query to make it more appropriate for a web search, focusing on clarity and accuracy without using the previous context.
366
+ 4. Provide ONLY the rephrased query without any additional explanation or reasoning.
367
+
368
+ Context: {context}
369
+
370
+ New query: {original_query}
371
+
372
+ Rephrased query:"""
373
+ response = DDGS().chat(prompt, model="llama-3.1-70b")
374
+ rephrased_query = response.split('\n')[0].strip()
375
+ return rephrased_query
376
+ return original_query
377
+
378
+ def summarize_web_results(query: str, search_results: List[Dict[str, str]], conversation_manager: ConversationManager) -> str:
379
+ try:
380
+ context = conversation_manager.get_context()
381
+ search_context = "\n\n".join([f"Title: {result['title']}\nContent: {result['body']}" for result in search_results])
382
+
383
+ prompt = f"""You are a highly intelligent & expert analyst and your job is to skillfully articulate the web search results about '{query}' and considering the context: {context},
384
+ You have to create a comprehensive news summary FOCUSING on the context provided to you.
385
+ Include key facts, relevant statistics, and expert opinions if available.
386
+ Ensure the article is well-structured with an introduction, main body, and conclusion, IF NECESSARY.
387
+ Address the query in the context of the ongoing conversation IF APPLICABLE.
388
+ Cite sources directly within the generated text and not at the end of the generated text, integrating URLs where appropriate to support the information provided:
389
+
390
+ {search_context}
391
+
392
+ Article:"""
393
+
394
+ summary = DDGS().chat(prompt, model="llama-3.1-70b")
395
+ return summary
396
+ except Exception as e:
397
+ return f"An error occurred during summarization: {str(e)}"
398
+
399
+ # Modify the existing respond function to handle both PDF and web search
400
+ def respond(message, history, model, temperature, num_calls, use_web_search, selected_docs):
401
+ logging.info(f"User Query: {message}")
402
+ logging.info(f"Model Used: {model}")
403
+ logging.info(f"Selected Documents: {selected_docs}")
404
+ logging.info(f"Use Web Search: {use_web_search}")
405
+
406
+ if use_web_search:
407
+ original_query = message
408
+ rephrased_query = rephrase_query(message, conversation_manager)
409
+ logging.info(f"Original query: {original_query}")
410
+ logging.info(f"Rephrased query: {rephrased_query}")
411
+
412
+ final_summary = ""
413
+ for _ in range(num_calls):
414
+ search_results = get_web_search_results(rephrased_query)
415
+ if not search_results:
416
+ final_summary += f"No search results found for the query: {rephrased_query}\n\n"
417
+ elif "error" in search_results[0]:
418
+ final_summary += search_results[0]["error"] + "\n\n"
419
+ else:
420
+ summary = summarize_web_results(rephrased_query, search_results, conversation_manager)
421
+ final_summary += summary + "\n\n"
422
+
423
+ if final_summary:
424
+ conversation_manager.add_interaction(original_query, final_summary)
425
+ yield final_summary
426
+ else:
427
+ yield "Unable to generate a response. Please try a different query."
428
+ else:
429
+ # Existing PDF search logic
430
+ try:
431
+ embed = get_embeddings()
432
+ if os.path.exists("faiss_database"):
433
+ database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
434
+ retriever = database.as_retriever(search_kwargs={"k": 20})
435
+
436
+ all_relevant_docs = retriever.get_relevant_documents(message)
437
+ relevant_docs = [doc for doc in all_relevant_docs if doc.metadata["source"] in selected_docs]
438
+
439
+ if not relevant_docs:
440
+ yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
441
+ return
442
 
443
+ context_str = "\n".join([doc.page_content for doc in relevant_docs])
444
+ logging.info(f"Context length: {len(context_str)}")
445
+ else:
446
+ context_str = "No documents available."
447
+ yield "No documents available. Please upload PDF documents to answer questions."
448
+ return
449
+
450
+ if model.startswith("duckduckgo/"):
451
+ # Use DuckDuckGo chat with context
452
+ for partial_response in get_response_from_duckduckgo(message, model, context_str, num_calls, temperature):
453
+ yield partial_response
454
+ elif model == "@cf/meta/llama-3.1-8b-instruct":
455
+ # Use Cloudflare API
456
+ for partial_response in get_response_from_cloudflare(prompt="", context=context_str, query=message, num_calls=num_calls, temperature=temperature, search_type="pdf"):
457
+ yield partial_response
458
+ else:
459
+ # Use Hugging Face API
460
+ for partial_response in get_response_from_pdf(message, model, selected_docs, num_calls=num_calls, temperature=temperature):
461
+ yield partial_response
462
+ except Exception as e:
463
+ logging.error(f"Error with {model}: {str(e)}")
464
+ if "microsoft/Phi-3-mini-4k-instruct" in model:
465
+ logging.info("Falling back to Mistral model due to Phi-3 error")
466
+ fallback_model = "mistralai/Mistral-7B-Instruct-v0.3"
467
+ yield from respond(message, history, fallback_model, temperature, num_calls, selected_docs)
468
+ else:
469
+ yield f"An error occurred with the {model} model: {str(e)}. Please try again or select a different model."
470
+
471
+ logging.basicConfig(level=logging.DEBUG)
472
+
473
+ def get_response_from_cloudflare(prompt, context, query, num_calls=3, temperature=0.2, search_type="pdf"):
474
+ headers = {
475
+ "Authorization": f"Bearer {API_TOKEN}",
476
+ "Content-Type": "application/json"
477
+ }
478
+ model = "@cf/meta/llama-3.1-8b-instruct"
479
 
480
+ if search_type == "pdf":
481
+ instruction = f"""Using the following context from the PDF documents:
482
+ {context}
483
+ Write a detailed and complete response that answers the following user question: '{query}'"""
484
+ else: # web search
485
+ instruction = f"""Using the following context:
486
+ {context}
487
+ Write a detailed and complete research document that fulfills the following user request: '{query}'
488
+ After writing the document, please provide a list of sources used in your response."""
489
+
490
+ inputs = [
491
+ {"role": "system", "content": instruction},
492
+ {"role": "user", "content": query}
493
  ]
494
 
495
+ payload = {
496
+ "messages": inputs,
497
+ "stream": True,
498
+ "temperature": temperature,
499
+ "max_tokens": 32000
500
+ }
501
+
502
+ full_response = ""
503
+ for i in range(num_calls):
504
+ try:
505
+ with requests.post(f"{API_BASE_URL}{model}", headers=headers, json=payload, stream=True) as response:
506
+ if response.status_code == 200:
507
+ for line in response.iter_lines():
508
+ if line:
509
+ try:
510
+ json_response = json.loads(line.decode('utf-8').split('data: ')[1])
511
+ if 'response' in json_response:
512
+ chunk = json_response['response']
513
+ full_response += chunk
514
+ yield full_response
515
+ except (json.JSONDecodeError, IndexError) as e:
516
+ logging.error(f"Error parsing streaming response: {str(e)}")
517
+ continue
518
+ else:
519
+ logging.error(f"HTTP Error: {response.status_code}, Response: {response.text}")
520
+ yield f"I apologize, but I encountered an HTTP error: {response.status_code}. Please try again later."
521
+ except Exception as e:
522
+ logging.error(f"Error in generating response from Cloudflare: {str(e)}")
523
+ yield f"I apologize, but an error occurred: {str(e)}. Please try again later."
524
+
525
+ if not full_response:
526
+ yield "I apologize, but I couldn't generate a response at this time. Please try again later."
527
+
528
+ def create_web_search_vectors(search_results):
529
+ embed = get_embeddings()
530
+
531
+ documents = []
532
+ for result in search_results:
533
+ if 'body' in result:
534
+ content = f"{result['title']}\n{result['body']}\nSource: {result['href']}"
535
+ documents.append(Document(page_content=content, metadata={"source": result['href']}))
536
+
537
+ return FAISS.from_documents(documents, embed)
538
+
539
+ def get_response_from_pdf(query, model, selected_docs, num_calls=3, temperature=0.2):
540
+ logging.info(f"Entering get_response_from_pdf with query: {query}, model: {model}, selected_docs: {selected_docs}")
541
+
542
+ embed = get_embeddings()
543
+ if os.path.exists("faiss_database"):
544
+ logging.info("Loading FAISS database")
545
+ database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
546
  else:
547
+ logging.warning("No FAISS database found")
548
+ yield "No documents available. Please upload PDF documents to answer questions."
549
+ return
550
+
551
+ # Pre-filter the documents
552
+ filtered_docs = []
553
+ for doc_id, doc in database.docstore._dict.items():
554
+ if isinstance(doc, Document) and doc.metadata.get("source") in selected_docs:
555
+ filtered_docs.append(doc)
556
+
557
+ logging.info(f"Number of documents after pre-filtering: {len(filtered_docs)}")
558
+
559
+ if not filtered_docs:
560
+ logging.warning(f"No documents found for the selected sources: {selected_docs}")
561
+ yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
562
+ return
563
+
564
+ # Create a new FAISS index with only the selected documents
565
+ filtered_db = FAISS.from_documents(filtered_docs, embed)
566
 
567
+ retriever = filtered_db.as_retriever(search_kwargs={"k": 10})
568
+ logging.info(f"Retrieving relevant documents for query: {query}")
569
+ relevant_docs = retriever.get_relevant_documents(query)
570
+ logging.info(f"Number of relevant documents retrieved: {len(relevant_docs)}")
571
+
572
+ for doc in relevant_docs:
573
+ logging.info(f"Document source: {doc.metadata['source']}")
574
+ logging.info(f"Document content preview: {doc.page_content[:100]}...") # Log first 100 characters of each document
575
+
576
+ context_str = "\n".join([doc.page_content for doc in relevant_docs])
577
+ logging.info(f"Total context length: {len(context_str)}")
578
+
579
+ if model == "@cf/meta/llama-3.1-8b-instruct":
580
+ logging.info("Using Cloudflare API")
581
+ # Use Cloudflare API with the retrieved context
582
+ for response in get_response_from_cloudflare(prompt="", context=context_str, query=query, num_calls=num_calls, temperature=temperature, search_type="pdf"):
583
+ yield response
584
+ else:
585
+ logging.info("Using Hugging Face API")
586
+ # Use Hugging Face API
587
+ prompt = f"""Using the following context from the PDF documents:
588
+ {context_str}
589
+ Write a detailed and complete response that answers the following user question: '{query}'"""
590
+
591
+ client = InferenceClient(model, token=huggingface_token)
592
+
593
+ response = ""
594
+ for i in range(num_calls):
595
+ logging.info(f"API call {i+1}/{num_calls}")
596
+ for message in client.chat_completion(
597
+ messages=[{"role": "user", "content": prompt}],
598
+ max_tokens=20000,
599
+ temperature=temperature,
600
+ stream=True,
601
+ ):
602
+ if message.choices and message.choices[0].delta and message.choices[0].delta.content:
603
+ chunk = message.choices[0].delta.content
604
+ response += chunk
605
+ yield response # Yield partial response
606
+
607
+ logging.info("Finished generating response")
608
+
609
+ def vote(data: gr.LikeData):
610
+ if data.liked:
611
+ print(f"You upvoted this response: {data.value}")
612
+ else:
613
+ print(f"You downvoted this response: {data.value}")
614
+
615
+ css = """
616
+ /* Fine-tune chatbox size */
617
+ .chatbot-container {
618
+ height: 600px !important;
619
+ width: 100% !important;
620
+ }
621
+ .chatbot-container > div {
622
+ height: 100%;
623
+ width: 100%;
624
+ }
625
+ """
626
+
627
+ uploaded_documents = []
628
+
629
+ def display_documents():
630
+ return gr.CheckboxGroup(
631
+ choices=[doc["name"] for doc in uploaded_documents],
632
+ value=[doc["name"] for doc in uploaded_documents if doc["selected"]],
633
+ label="Select documents to query or delete"
634
+ )
635
+
636
 
637
+ def initial_conversation():
638
+ return [
639
+ (None, "Welcome! I'm your AI assistant for web search and PDF analysis. Here's how you can use me:\n\n"
640
+ "1. Set the toggle for Web Search and PDF Search from the checkbox in Additional Inputs drop down window\n"
641
+ "2. Use web search to find information\n"
642
+ "3. Upload the documents and ask questions about uploaded PDF documents by selecting your respective document\n"
643
+ "4. For any queries feel free to reach out @desai.shreyas94@gmail.com or discord - shreyas094\n\n"
644
+ "To get started, upload some PDFs or ask me a question!")
645
+ ]
646
+ # Add this new function
647
+ def refresh_documents():
648
+ global uploaded_documents
649
+ uploaded_documents = load_documents()
650
+ return display_documents()
651
+
652
+ # Define the checkbox outside the demo block
653
+ document_selector = gr.CheckboxGroup(label="Select documents to query")
654
+
655
+ use_web_search = gr.Checkbox(label="Use Web Search", value=False)
656
+
657
+ custom_placeholder = "Ask a question (Note: You can toggle between Web Search and PDF Chat in Additional Inputs below)"
658
+
659
+ # Update the demo interface
660
+ # Update the Gradio interface
661
+ demo = gr.ChatInterface(
662
+ respond,
663
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=True, render=False),
664
+ additional_inputs=[
665
+ gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[3]),
666
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),
667
+ gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),
668
+ gr.Checkbox(label="Use Web Search", value=True),
669
+ gr.CheckboxGroup(label="Select documents to query")
670
+ ],
671
+ title="AI-powered PDF Chat and Web Search Assistant",
672
+ description="Chat with your PDFs or use web search to answer questions.",
673
+ theme=gr.themes.Soft(
674
+ primary_hue="orange",
675
+ secondary_hue="amber",
676
+ neutral_hue="gray",
677
+ font=[gr.themes.GoogleFont("Exo"), "ui-sans-serif", "system-ui", "sans-serif"]
678
+ ).set(
679
+ body_background_fill_dark="#0c0505",
680
+ block_background_fill_dark="#0c0505",
681
+ block_border_width="1px",
682
+ block_title_background_fill_dark="#1b0f0f",
683
+ input_background_fill_dark="#140b0b",
684
+ button_secondary_background_fill_dark="#140b0b",
685
+ border_color_accent_dark="#1b0f0f",
686
+ border_color_primary_dark="#1b0f0f",
687
+ background_fill_secondary_dark="#0c0505",
688
+ color_accent_soft_dark="transparent",
689
+ code_background_fill_dark="#140b0b"
690
+ ),
691
+ css=css,
692
+ examples=[
693
+ ["Tell me about the contents of the uploaded PDFs."],
694
+ ["What are the main topics discussed in the documents?"],
695
+ ["Can you summarize the key points from the PDFs?"],
696
+ ["What's the latest news about artificial intelligence?"]
697
+ ],
698
+ cache_examples=False,
699
+ analytics_enabled=False,
700
+ textbox=gr.Textbox(placeholder="Ask a question about the uploaded PDFs or any topic", container=False, scale=7),
701
+ chatbot = gr.Chatbot(
702
+ show_copy_button=True,
703
+ likeable=True,
704
+ layout="bubble",
705
+ height=400,
706
+ value=initial_conversation()
707
+ )
708
+ )
709
 
710
+ # Add file upload functionality
711
+ # Add file upload functionality
712
+ with demo:
713
+ gr.Markdown("## Upload and Manage PDF Documents")
714
+ with gr.Row():
715
+ file_input = gr.Files(label="Upload your PDF documents", file_types=[".pdf"])
716
+ parser_dropdown = gr.Dropdown(choices=["pypdf", "llamaparse"], label="Select PDF Parser", value="llamaparse")
717
+ update_button = gr.Button("Upload Document")
718
+ refresh_button = gr.Button("Refresh Document List")
719
 
720
+ update_output = gr.Textbox(label="Update Status")
721
+ delete_button = gr.Button("Delete Selected Documents")
722
+
723
+ # Update both the output text and the document selector
724
+ update_button.click(
725
+ update_vectors,
726
+ inputs=[file_input, parser_dropdown],
727
+ outputs=[update_output, demo.additional_inputs[-1]] # Use the CheckboxGroup from additional_inputs
728
+ )
729
+
730
+ # Add the refresh button functionality
731
+ refresh_button.click(
732
+ refresh_documents,
733
+ inputs=[],
734
+ outputs=[demo.additional_inputs[-1]] # Use the CheckboxGroup from additional_inputs
735
+ )
736
+
737
+ # Add the delete button functionality
738
+ delete_button.click(
739
+ delete_documents,
740
+ inputs=[demo.additional_inputs[-1]], # Use the CheckboxGroup from additional_inputs
741
+ outputs=[update_output, demo.additional_inputs[-1]]
742
  )
 
743
 
744
+ gr.Markdown(
745
+ """
746
+ ## How to use
747
+ 1. Upload PDF documents using the file input at the top.
748
+ 2. Select the PDF parser (pypdf or llamaparse) and click "Upload Document" to update the vector store.
749
+ 3. Select the documents you want to query using the checkboxes.
750
+ 4. Ask questions in the chat interface.
751
+ 5. Toggle "Use Web Search" to switch between PDF chat and web search.
752
+ 6. Adjust Temperature and Number of API Calls to fine-tune the response generation.
753
+ 7. Use the provided examples or ask your own questions.
754
+ """
755
+ )
756
 
757
  if __name__ == "__main__":
758
+ demo.launch(share=True)