import os
import json
import re
import gradio as gr
import requests
from duckduckgo_search import DDGS
from typing import List, Dict
from pydantic import BaseModel, Field
from tempfile import NamedTemporaryFile
from langchain_community.vectorstores import FAISS
from langchain_core.vectorstores import VectorStore
from langchain_core.documents import Document
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.embeddings import HuggingFaceEmbeddings
from llama_parse import LlamaParse
from huggingface_hub import InferenceClient
import inspect
import logging
import shutil
import pandas as pd
from docx import Document as DocxDocument
import google.generativeai as genai
from huggingface_hub import InferenceClient
# Set up basic configuration for logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Environment variables and configurations
huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")
ACCOUNT_ID = os.environ.get("CLOUDFARE_ACCOUNT_ID")
API_TOKEN = os.environ.get("CLOUDFLARE_AUTH_TOKEN")
API_BASE_URL = "https://api.cloudflare.com/client/v4/accounts/a17f03e0f049ccae0c15cdcf3b9737ce/ai/run/"
print(f"ACCOUNT_ID: {ACCOUNT_ID}")
print(f"CLOUDFLARE_AUTH_TOKEN: {API_TOKEN[:5]}..." if API_TOKEN else "Not set")
MODELS = [
"mistralai/Mistral-7B-Instruct-v0.3",
"mistralai/Mixtral-8x7B-Instruct-v0.1",
"@cf/meta/llama-3.1-8b-instruct",
"mistralai/Mistral-Nemo-Instruct-2407",
"mistralai/Mathstral-7B-v0.1",
"meta-llama/Meta-Llama-3.1-8B-Instruct",
"meta-llama/Meta-Llama-3.1-70B-Instruct",
"mattshumer/Reflection-Llama-3.1-70B",
"gemini-1.5-flash",
"duckduckgo/gpt-4o-mini",
"duckduckgo/claude-3-haiku",
"duckduckgo/llama-3.1-70b",
"duckduckgo/mixtral-8x7b"
]
# Initialize LlamaParse
llama_parser = LlamaParse(
api_key=llama_cloud_api_key,
result_type="markdown",
num_workers=4,
verbose=True,
language="en",
)
def load_office_document(file: NamedTemporaryFile) -> List[Document]:
file_extension = os.path.splitext(file.name)[1].lower()
documents = []
if file_extension in ['.xlsx', '.xls']:
df = pd.read_excel(file.name)
for _, row in df.iterrows():
content = ' '.join(str(cell) for cell in row if pd.notna(cell))
documents.append(Document(page_content=content, metadata={"source": file.name}))
elif file_extension == '.docx':
doc = Document(file.name)
for para in doc.paragraphs:
if para.text.strip():
documents.append(Document(page_content=para.text, metadata={"source": file.name}))
return documents
def load_document(file: NamedTemporaryFile, parser: str = "llamaparse") -> List[Document]:
"""Loads and splits the document into pages."""
if parser == "pypdf":
loader = PyPDFLoader(file.name)
return loader.load_and_split()
elif parser == "llamaparse":
try:
documents = llama_parser.load_data(file.name)
return [Document(page_content=doc.text, metadata={"source": file.name}) for doc in documents]
except Exception as e:
print(f"Error using Llama Parse: {str(e)}")
print("Falling back to PyPDF parser")
loader = PyPDFLoader(file.name)
return loader.load_and_split()
else:
raise ValueError("Invalid parser specified. Use 'pypdf' or 'llamaparse'.")
def get_embeddings():
return HuggingFaceEmbeddings(model_name="avsolatorio/GIST-Embedding-v0")
# Add this at the beginning of your script, after imports
DOCUMENTS_FILE = "uploaded_documents.json"
def load_documents():
if os.path.exists(DOCUMENTS_FILE):
with open(DOCUMENTS_FILE, "r") as f:
return json.load(f)
return []
def save_documents(documents):
with open(DOCUMENTS_FILE, "w") as f:
json.dump(documents, f)
# Replace the global uploaded_documents with this
uploaded_documents = load_documents()
# Modify the update_vectors function
def update_vectors(files, parser):
global uploaded_documents
logging.info(f"Entering update_vectors with {len(files)} files and parser: {parser}")
if not files:
logging.warning("No files provided for update_vectors")
return "Please upload at least one file.", display_documents()
embed = get_embeddings()
total_chunks = 0
all_data = []
for file in files:
logging.info(f"Processing file: {file.name}")
try:
file_extension = os.path.splitext(file.name)[1].lower()
if file_extension in ['.xlsx', '.xls', '.docx']:
if parser != "office":
logging.warning(f"Using office parser for {file.name} regardless of selected parser")
data = load_office_document(file)
elif file_extension == '.pdf':
if parser == "office":
logging.warning(f"Cannot use office parser for PDF file {file.name}. Using llamaparse.")
data = load_document(file, "llamaparse")
else:
data = load_document(file, parser)
else:
logging.warning(f"Unsupported file type: {file_extension}")
continue
if not data:
logging.warning(f"No chunks loaded from {file.name}")
continue
logging.info(f"Loaded {len(data)} chunks from {file.name}")
all_data.extend(data)
total_chunks += len(data)
if not any(doc["name"] == file.name for doc in uploaded_documents):
uploaded_documents.append({"name": file.name, "selected": True})
logging.info(f"Added new document to uploaded_documents: {file.name}")
else:
logging.info(f"Document already exists in uploaded_documents: {file.name}")
except Exception as e:
logging.error(f"Error processing file {file.name}: {str(e)}")
logging.info(f"Total chunks processed: {total_chunks}")
if not all_data:
logging.warning("No valid data extracted from uploaded files")
return "No valid data could be extracted from the uploaded files. Please check the file contents and try again.", display_documents()
try:
# Update the appropriate vector store based on file type
pdf_data = [doc for doc in all_data if doc.metadata["source"].lower().endswith('.pdf')]
office_data = [doc for doc in all_data if not doc.metadata["source"].lower().endswith('.pdf')]
if pdf_data:
if os.path.exists("faiss_database"):
pdf_database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
pdf_database.add_documents(pdf_data)
else:
pdf_database = FAISS.from_documents(pdf_data, embed)
pdf_database.save_local("faiss_database")
logging.info("PDF FAISS database updated and saved")
if office_data:
if os.path.exists("office_faiss_database"):
office_database = FAISS.load_local("office_faiss_database", embed, allow_dangerous_deserialization=True)
office_database.add_documents(office_data)
else:
office_database = FAISS.from_documents(office_data, embed)
office_database.save_local("office_faiss_database")
logging.info("Office FAISS database updated and saved")
except Exception as e:
logging.error(f"Error updating FAISS database: {str(e)}")
return f"Error updating vector store: {str(e)}", display_documents()
# Save the updated list of documents
save_documents(uploaded_documents)
# Return a tuple with the status message and the updated document list
return f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files.", display_documents()
def delete_documents(selected_docs):
global uploaded_documents
if not selected_docs:
return "No documents selected for deletion.", display_documents()
embed = get_embeddings()
database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
deleted_docs = []
docs_to_keep = []
for doc in database.docstore._dict.values():
if doc.metadata.get("source") not in selected_docs:
docs_to_keep.append(doc)
else:
deleted_docs.append(doc.metadata.get("source", "Unknown"))
# Print debugging information
logging.info(f"Total documents before deletion: {len(database.docstore._dict)}")
logging.info(f"Documents to keep: {len(docs_to_keep)}")
logging.info(f"Documents to delete: {len(deleted_docs)}")
if not docs_to_keep:
# If all documents are deleted, remove the FAISS database directory
if os.path.exists("faiss_database"):
shutil.rmtree("faiss_database")
logging.info("All documents deleted. Removed FAISS database directory.")
else:
# Create new FAISS index with remaining documents
new_database = FAISS.from_documents(docs_to_keep, embed)
new_database.save_local("faiss_database")
logging.info(f"Created new FAISS index with {len(docs_to_keep)} documents.")
# Update uploaded_documents list
uploaded_documents = [doc for doc in uploaded_documents if doc["name"] not in deleted_docs]
save_documents(uploaded_documents)
return f"Deleted documents: {', '.join(deleted_docs)}", display_documents()
def chatbot_interface(message, history, model, temperature, num_calls):
if not message.strip():
return "", history
history = history + [(message, "")]
try:
for response in respond(message, history, model, temperature, num_calls):
history[-1] = (message, response)
yield history
except gr.CancelledError:
yield history
except Exception as e:
logging.error(f"Unexpected error in chatbot_interface: {str(e)}")
history[-1] = (message, f"An unexpected error occurred: {str(e)}")
yield history
def retry_last_response(history, model, temperature, num_calls):
if not history:
return history
last_user_msg = history[-1][0]
history = history[:-1] # Remove the last response
return chatbot_interface(last_user_msg, history, model, temperature, num_calls)
def truncate_context(context, max_length=16000):
"""Truncate the context to a maximum length."""
if len(context) <= max_length:
return context
return context[:max_length] + "..."
def get_response_from_duckduckgo(query, model, context, num_calls=1, temperature=0.2):
logging.info(f"Using DuckDuckGo chat with model: {model}")
ddg_model = model.split('/')[-1] # Extract the model name from the full string
# Truncate the context to avoid exceeding input limits
truncated_context = truncate_context(context)
full_response = ""
for _ in range(num_calls):
try:
# Include truncated context in the query
contextualized_query = f"Using the following context:\n{truncated_context}\n\nUser question: {query}"
results = DDGS().chat(contextualized_query, model=ddg_model)
full_response += results + "\n"
logging.info(f"DuckDuckGo API response received. Length: {len(results)}")
except Exception as e:
logging.error(f"Error in generating response from DuckDuckGo: {str(e)}")
yield f"An error occurred with the {model} model: {str(e)}. Please try again."
return
yield full_response.strip()
class ConversationManager:
def __init__(self):
self.history = []
self.current_context = None
def add_interaction(self, query, response):
self.history.append((query, response))
self.current_context = f"Previous query: {query}\nPrevious response summary: {response[:200]}..."
def get_context(self):
return self.current_context
conversation_manager = ConversationManager()
def get_web_search_results(query: str, max_results: int = 10) -> List[Dict[str, str]]:
try:
results = list(DDGS().text(query, max_results=max_results))
if not results:
print(f"No results found for query: {query}")
return results
except Exception as e:
print(f"An error occurred during web search: {str(e)}")
return [{"error": f"An error occurred during web search: {str(e)}"}]
def rephrase_query(original_query: str, conversation_manager: ConversationManager) -> str:
context = conversation_manager.get_context()
if context:
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:
1. Determine if the new query is a continuation of the previous conversation or an entirely new topic.
2. If it's a continuation, rephrase the query by incorporating relevant information from the context to make it more specific and contextual.
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.
4. Provide ONLY the rephrased query without any additional explanation or reasoning.
Context: {context}
New query: {original_query}
Rephrased query:"""
response = DDGS().chat(prompt, model="llama-3.1-70b")
rephrased_query = response.split('\n')[0].strip()
return rephrased_query
return original_query
def summarize_web_results(query: str, search_results: List[Dict[str, str]], conversation_manager: ConversationManager) -> str:
try:
context = conversation_manager.get_context()
search_context = "\n\n".join([f"Title: {result['title']}\nContent: {result['body']}" for result in search_results])
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},
You have to create a comprehensive news summary FOCUSING on the context provided to you.
Include key facts, relevant statistics, and expert opinions if available.
Ensure the article is well-structured with an introduction, main body, and conclusion, IF NECESSARY.
Address the query in the context of the ongoing conversation IF APPLICABLE.
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:
{search_context}
Article:"""
summary = DDGS().chat(prompt, model="llama-3.1-70b")
return summary
except Exception as e:
return f"An error occurred during summarization: {str(e)}"
def get_response_from_gemini(query, model, selected_docs, file_type, num_calls=1, temperature=0.2):
# Configure the Gemini API
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
# Define the model
gemini_model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config={
"temperature": temperature,
"top_p": 1,
"top_k": 1,
"max_output_tokens": 20000,
},
)
if file_type == "excel":
# Excel functionality remains the same
system_instruction = """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.
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."""
full_prompt = f"{system_instruction}\n\nContext:\n{selected_docs}\n\nUser query: {query}"
elif file_type == "pdf":
# PDF functionality similar to get_response_from_pdf
embed = get_embeddings()
if os.path.exists("faiss_database"):
database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
else:
yield "No documents available. Please upload PDF documents to answer questions."
return
# Pre-filter the documents
filtered_docs = [doc for doc_id, doc in database.docstore._dict.items()
if isinstance(doc, Document) and doc.metadata.get("source") in selected_docs]
if not filtered_docs:
yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."
return
# Create a new FAISS index with only the selected documents
filtered_db = FAISS.from_documents(filtered_docs, embed)
retriever = filtered_db.as_retriever(search_kwargs={"k": 10})
relevant_docs = retriever.get_relevant_documents(query)
context_str = "\n".join([doc.page_content for doc in relevant_docs])
system_instruction = """You are a highly specialized financial analyst assistant with expertise in analyzing and summarizing financial documents.
Your goal is to provide accurate, detailed, and precise summaries based on the context provided.
Avoid making assumptions or adding information that is not explicitly supported by the context from the PDF documents.
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."""
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."
else:
raise ValueError("Invalid file type. Use 'excel' or 'pdf'.")
full_response = ""
for _ in range(num_calls):
try:
# Generate content with streaming enabled
response = gemini_model.generate_content(full_prompt, stream=True)
for chunk in response:
if chunk.text:
full_response += chunk.text
yield full_response # Yield the accumulated response so far
except Exception as e:
yield f"An error occurred with the Gemini model: {str(e)}. Please try again."
if not full_response:
yield "No response generated from the Gemini model."
def get_response_from_excel(query, model, context, num_calls=3, temperature=0.2):
logging.info(f"Getting response from Excel using model: {model}")
messages = [
{"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."},
{"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."}
]
if model.startswith("duckduckgo/"):
# Use DuckDuckGo chat with context
return get_response_from_duckduckgo(query, model, context, num_calls, temperature)
elif model == "@cf/meta/llama-3.1-8b-instruct":
# Use Cloudflare API
return get_response_from_cloudflare(prompt="", context=context, query=query, num_calls=num_calls, temperature=temperature, search_type="excel")
else:
# Use Hugging Face API
client = InferenceClient(model, token=huggingface_token)
response = ""
for i in range(num_calls):
logging.info(f"API call {i+1}/{num_calls}")
for message in client.chat_completion(
messages=messages,
max_tokens=20000,
temperature=temperature,
stream=True,
top_p=0.2,
):
if message.choices and message.choices[0].delta and message.choices[0].delta.content:
chunk = message.choices[0].delta.content
response += chunk
yield response # Yield partial response
logging.info("Finished generating response for Excel data")
def truncate_context(context, max_chars=10000):
"""Truncate context to a maximum number of characters."""
if len(context) <= max_chars:
return context
return context[:max_chars] + "..."
def get_response_from_llama(query, model, selected_docs, file_type, num_calls=1, temperature=0.2):
logging.info(f"Getting response from Llama using model: {model}")
# Initialize the Hugging Face client
client = InferenceClient(model, token=huggingface_token)
if file_type == "excel":
# Excel functionality
system_instruction = """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."""
# Get the context from selected Excel documents
embed = get_embeddings()
office_database = FAISS.load_local("office_faiss_database", embed, allow_dangerous_deserialization=True)
retriever = office_database.as_retriever(search_kwargs={"k": 20})
relevant_docs = retriever.get_relevant_documents(query)
context = "\n".join([doc.page_content for doc in relevant_docs if doc.metadata["source"] in selected_docs])
# Truncate context
context = truncate_context(context)
messages = [
{"role": "system", "content": system_instruction},
{"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."}
]
elif file_type == "pdf":
# PDF functionality
embed = get_embeddings()
pdf_database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)
retriever = pdf_database.as_retriever(search_kwargs={"k": 10})
relevant_docs = retriever.get_relevant_documents(query)
context_str = "\n".join([doc.page_content for doc in relevant_docs if doc.metadata["source"] in selected_docs])
# Truncate context
context_str = truncate_context(context_str)
system_instruction = """You are an AI assistant designed to provide detailed, step-by-step responses. Your outputs should follow this structure:
1. Begin with a section. Everything in this section is invisible to the user.
2. Inside the thinking section:
a. Briefly analyze the question and outline your approach.
b. Present a clear plan of steps to solve the problem.
c. Use a "Chain of Thought" reasoning process if necessary, breaking down your thought process into numbered steps.
3. Include a section for each idea where you:
a. Review your reasoning.
b. Check for potential errors or oversights.
c. Confirm or adjust your conclusion if necessary.
4. Be sure to close all reflection sections.
5. Close the thinking section with .
6. Provide your final answer in an