Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,6 +14,8 @@ import shutil
|
|
| 14 |
import logging
|
| 15 |
import chromadb
|
| 16 |
import tempfile
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Set up logging
|
| 19 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -26,8 +28,8 @@ if os.environ["HUGGINGFACEHUB_API_TOKEN"] == "default-token":
|
|
| 26 |
|
| 27 |
# Model and embedding options
|
| 28 |
LLM_MODELS = {
|
| 29 |
-
"Lightweight (Gemma-2B)": "google/gemma-2b-it",
|
| 30 |
"Balanced (Mixtral-8x7B)": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
|
|
|
| 31 |
"High Accuracy (Llama-3-8B)": "meta-llama/Llama-3-8b-hf"
|
| 32 |
}
|
| 33 |
|
|
@@ -133,13 +135,12 @@ def process_documents(files, chunk_size, chunk_overlap, embedding_model):
|
|
| 133 |
|
| 134 |
# Create vector store
|
| 135 |
try:
|
| 136 |
-
# Use
|
| 137 |
collection_name = f"doctalk_collection_{int(time.time())}"
|
| 138 |
-
client = chromadb.
|
| 139 |
vector_store = Chroma.from_documents(
|
| 140 |
documents=doc_splits,
|
| 141 |
embedding=embeddings,
|
| 142 |
-
persist_directory=PERSIST_DIRECTORY,
|
| 143 |
collection_name=collection_name
|
| 144 |
)
|
| 145 |
return f"Processed {len(documents)} documents into {len(doc_splits)} chunks.", None
|
|
@@ -147,7 +148,12 @@ def process_documents(files, chunk_size, chunk_overlap, embedding_model):
|
|
| 147 |
logger.error(f"Error creating vector store: {str(e)}")
|
| 148 |
return f"Error creating vector store: {str(e)}", None
|
| 149 |
|
| 150 |
-
# Function to initialize QA chain
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
def initialize_qa_chain(llm_model, temperature):
|
| 152 |
global qa_chain
|
| 153 |
if not vector_store:
|
|
@@ -159,20 +165,37 @@ def initialize_qa_chain(llm_model, temperature):
|
|
| 159 |
task="text-generation",
|
| 160 |
temperature=float(temperature),
|
| 161 |
max_new_tokens=512,
|
| 162 |
-
huggingfacehub_api_token=os.environ["HUGGINGFACEHUB_API_TOKEN"]
|
|
|
|
| 163 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 165 |
llm=llm,
|
| 166 |
-
retriever=vector_store.as_retriever(search_kwargs={"k":
|
| 167 |
memory=memory
|
| 168 |
)
|
| 169 |
-
logger.info(f"Initialized QA chain with {llm_model}.")
|
| 170 |
return "QA Doctor: QA chain initialized successfully.", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
except Exception as e:
|
| 172 |
logger.error(f"Error initializing QA chain for {llm_model}: {str(e)}")
|
| 173 |
return f"Error initializing QA chain: {str(e)}. Ensure your HF token has access to {llm_model}.", None
|
| 174 |
|
| 175 |
-
# Function to handle user query
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
def answer_question(question, llm_model, embedding_model, temperature, chunk_size, chunk_overlap):
|
| 177 |
global chat_history
|
| 178 |
if not vector_store:
|
|
@@ -183,11 +206,18 @@ def answer_question(question, llm_model, embedding_model, temperature, chunk_siz
|
|
| 183 |
return "Please enter a valid question.", chat_history
|
| 184 |
|
| 185 |
try:
|
| 186 |
-
response = qa_chain({"question": question})["answer"]
|
| 187 |
chat_history.append({"role": "user", "content": question})
|
| 188 |
chat_history.append({"role": "assistant", "content": response})
|
| 189 |
logger.info(f"Answered question: {question}")
|
| 190 |
return response, chat_history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
except Exception as e:
|
| 192 |
logger.error(f"Error answering question: {str(e)}")
|
| 193 |
return f"Error answering question: {str(e)}", chat_history
|
|
@@ -242,7 +272,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="DocTalk: Document Q&A Chatbot") as
|
|
| 242 |
status = gr.Textbox(label="Status", interactive=False)
|
| 243 |
|
| 244 |
with gr.Column(scale=1):
|
| 245 |
-
llm_model = gr.Dropdown(choices=list(LLM_MODELS.keys()), label="Select LLM Model", value="
|
| 246 |
embedding_model = gr.Dropdown(choices=list(EMBEDDING_MODELS.keys()), label="Select Embedding Model", value="Lightweight (MiniLM-L6)")
|
| 247 |
temperature = gr.Slider(minimum=0.1, maximum=1.0, step=0.1, value=0.7, label="Temperature")
|
| 248 |
chunk_size = gr.Slider(minimum=500, maximum=2000, step=100, value=1000, label="Chunk Size")
|
|
|
|
| 14 |
import logging
|
| 15 |
import chromadb
|
| 16 |
import tempfile
|
| 17 |
+
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
|
| 18 |
+
import requests
|
| 19 |
|
| 20 |
# Set up logging
|
| 21 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 28 |
|
| 29 |
# Model and embedding options
|
| 30 |
LLM_MODELS = {
|
|
|
|
| 31 |
"Balanced (Mixtral-8x7B)": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 32 |
+
"Lightweight (Gemma-2B)": "google/gemma-2b-it",
|
| 33 |
"High Accuracy (Llama-3-8B)": "meta-llama/Llama-3-8b-hf"
|
| 34 |
}
|
| 35 |
|
|
|
|
| 135 |
|
| 136 |
# Create vector store
|
| 137 |
try:
|
| 138 |
+
# Use in-memory Chroma client to avoid filesystem issues
|
| 139 |
collection_name = f"doctalk_collection_{int(time.time())}"
|
| 140 |
+
client = chromadb.Client()
|
| 141 |
vector_store = Chroma.from_documents(
|
| 142 |
documents=doc_splits,
|
| 143 |
embedding=embeddings,
|
|
|
|
| 144 |
collection_name=collection_name
|
| 145 |
)
|
| 146 |
return f"Processed {len(documents)} documents into {len(doc_splits)} chunks.", None
|
|
|
|
| 148 |
logger.error(f"Error creating vector store: {str(e)}")
|
| 149 |
return f"Error creating vector store: {str(e)}", None
|
| 150 |
|
| 151 |
+
# Function to initialize QA chain with retry logic
|
| 152 |
+
@retry(
|
| 153 |
+
stop=stop_after_attempt(3),
|
| 154 |
+
wait=wait_exponential(multiplier=1, min=4, max=10),
|
| 155 |
+
retry=retry_if_exception_type((requests.exceptions.HTTPError, requests.exceptions.ConnectionError))
|
| 156 |
+
)
|
| 157 |
def initialize_qa_chain(llm_model, temperature):
|
| 158 |
global qa_chain
|
| 159 |
if not vector_store:
|
|
|
|
| 165 |
task="text-generation",
|
| 166 |
temperature=float(temperature),
|
| 167 |
max_new_tokens=512,
|
| 168 |
+
huggingfacehub_api_token=os.environ["HUGGINGFACEHUB_API_TOKEN"],
|
| 169 |
+
timeout=30
|
| 170 |
)
|
| 171 |
+
# Dynamically set k based on vector store size
|
| 172 |
+
collection = vector_store._collection
|
| 173 |
+
doc_count = collection.count()
|
| 174 |
+
k = min(3, doc_count) if doc_count > 0 else 1
|
| 175 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 176 |
llm=llm,
|
| 177 |
+
retriever=vector_store.as_retriever(search_kwargs={"k": k}),
|
| 178 |
memory=memory
|
| 179 |
)
|
| 180 |
+
logger.info(f"Initialized QA chain with {llm_model} and k={k}.")
|
| 181 |
return "QA Doctor: QA chain initialized successfully.", None
|
| 182 |
+
except requests.exceptions.HTTPError as e:
|
| 183 |
+
logger.error(f"HTTP error initializing QA chain for {llm_model}: {str(e)}")
|
| 184 |
+
if "503" in str(e):
|
| 185 |
+
return f"Error: Hugging Face API temporarily unavailable for {llm_model}. Try 'Balanced (Mixtral-8x7B)' or wait and retry.", None
|
| 186 |
+
elif "403" in str(e):
|
| 187 |
+
return f"Error: Access denied for {llm_model}. Ensure your HF token has access.", None
|
| 188 |
+
return f"Error initializing QA chain: {str(e)}.", None
|
| 189 |
except Exception as e:
|
| 190 |
logger.error(f"Error initializing QA chain for {llm_model}: {str(e)}")
|
| 191 |
return f"Error initializing QA chain: {str(e)}. Ensure your HF token has access to {llm_model}.", None
|
| 192 |
|
| 193 |
+
# Function to handle user query with retry logic
|
| 194 |
+
@retry(
|
| 195 |
+
stop=stop_after_attempt(3),
|
| 196 |
+
wait=wait_exponential(multiplier=1, min=4, max=10),
|
| 197 |
+
retry=retry_if_exception_type((requests.exceptions.HTTPError, requests.exceptions.ConnectionError))
|
| 198 |
+
)
|
| 199 |
def answer_question(question, llm_model, embedding_model, temperature, chunk_size, chunk_overlap):
|
| 200 |
global chat_history
|
| 201 |
if not vector_store:
|
|
|
|
| 206 |
return "Please enter a valid question.", chat_history
|
| 207 |
|
| 208 |
try:
|
| 209 |
+
response = qa_chain.invoke({"question": question})["answer"]
|
| 210 |
chat_history.append({"role": "user", "content": question})
|
| 211 |
chat_history.append({"role": "assistant", "content": response})
|
| 212 |
logger.info(f"Answered question: {question}")
|
| 213 |
return response, chat_history
|
| 214 |
+
except requests.exceptions.HTTPError as e:
|
| 215 |
+
logger.error(f"HTTP error answering question: {str(e)}")
|
| 216 |
+
if "503" in str(e):
|
| 217 |
+
return f"Error: Hugging Face API temporarily unavailable for {llm_model}. Try 'Balanced (Mixtral-8x7B)' or wait and retry.", chat_history
|
| 218 |
+
elif "403" in str(e):
|
| 219 |
+
return f"Error: Access denied for {llm_model}. Ensure your HF token has access.", chat_history
|
| 220 |
+
return f"Error answering question: {str(e)}", chat_history
|
| 221 |
except Exception as e:
|
| 222 |
logger.error(f"Error answering question: {str(e)}")
|
| 223 |
return f"Error answering question: {str(e)}", chat_history
|
|
|
|
| 272 |
status = gr.Textbox(label="Status", interactive=False)
|
| 273 |
|
| 274 |
with gr.Column(scale=1):
|
| 275 |
+
llm_model = gr.Dropdown(choices=list(LLM_MODELS.keys()), label="Select LLM Model", value="Balanced (Mixtral-8x7B)")
|
| 276 |
embedding_model = gr.Dropdown(choices=list(EMBEDDING_MODELS.keys()), label="Select Embedding Model", value="Lightweight (MiniLM-L6)")
|
| 277 |
temperature = gr.Slider(minimum=0.1, maximum=1.0, step=0.1, value=0.7, label="Temperature")
|
| 278 |
chunk_size = gr.Slider(minimum=500, maximum=2000, step=100, value=1000, label="Chunk Size")
|