File size: 21,442 Bytes
19739ea c39d038 19739ea 14e0c9e 19739ea 14e0c9e 19739ea 27ce43c 19739ea 95ca499 1e7a57d 95ca499 c947ea7 5ec7b71 1e7a57d 892745c 1e7a57d c947ea7 1e7a57d c947ea7 1e7a57d c947ea7 892745c 1e7a57d 892745c 1e7a57d 1c73b9c 1e7a57d 741a8ce 1b5e3e9 741a8ce 1e7a57d 741a8ce 1e7a57d 741a8ce 1b5e3e9 741a8ce 1c73b9c 1e7a57d 892745c 1e7a57d 95ca499 c947ea7 19739ea |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# app.py
import os
import pandas as pd
import chardet
import logging
import gradio as gr
import json
import hashlib
import numpy as np # ADDED for easy array handling
from typing import Optional, List, Tuple, ClassVar, Dict
from sentence_transformers import SentenceTransformer, util, CrossEncoder
from langchain.llms.base import LLM
import google.generativeai as genai
# Import smolagents components
from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool, ManagedAgent, HfApiModel
###############################################################################
# 1) Logging Setup
###############################################################################
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("Daily Wellness AI")
###############################################################################
# 2) API Key Handling and Enhanced GeminiLLM Class
###############################################################################
def clean_api_key(key: str) -> str:
"""Remove non-ASCII characters and strip whitespace from the API key."""
return ''.join(c for c in key if ord(c) < 128).strip()
# Load the GEMINI API key from environment variables
gemini_api_key = os.environ.get("GEMINI_API_KEY")
if not gemini_api_key:
logger.error("GEMINI_API_KEY environment variable not set.")
raise EnvironmentError("Please set the GEMINI_API_KEY environment variable.")
gemini_api_key = clean_api_key(gemini_api_key)
logger.info("GEMINI API Key loaded successfully.")
# Configure Google Generative AI
try:
genai.configure(api_key=gemini_api_key)
logger.info("Configured Google Generative AI with provided API key.")
except Exception as e:
logger.error(f"Failed to configure Google Generative AI: {e}")
raise e
class GeminiLLM(LLM):
model_name: ClassVar[str] = "gemini-2.0-flash-exp"
temperature: float = 0.7
top_p: float = 0.95
top_k: int = 40
max_tokens: int = 2048
@property
def _llm_type(self) -> str:
return "custom_gemini"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
generation_config = {
"temperature": self.temperature,
"top_p": self.top_p,
"top_k": self.top_k,
"max_output_tokens": self.max_tokens,
}
try:
logger.debug(f"Initializing GenerativeModel with config: {generation_config}")
model = genai.GenerativeModel(
model_name=self.model_name,
generation_config=generation_config,
)
logger.debug("GenerativeModel initialized successfully.")
chat_session = model.start_chat(history=[])
logger.debug("Chat session started.")
# Send the prompt as plain text
response = chat_session.send_message(prompt)
logger.debug(f"Prompt sent to model: {prompt}")
logger.debug(f"Raw response received: {response.text}")
return response.text
except Exception as e:
logger.error(f"Error generating response with GeminiLLM: {e}")
logger.debug("Exception details:", exc_info=True)
raise e
# Instantiate the GeminiLLM globally
llm = GeminiLLM()
###############################################################################
# 3) CSV Loading and Processing
###############################################################################
def load_csv(file_path: str):
try:
if not os.path.isfile(file_path):
logger.error(f"CSV file does not exist: {file_path}")
return [], []
with open(file_path, 'rb') as f:
result = chardet.detect(f.read())
encoding = result['encoding']
data = pd.read_csv(file_path, encoding=encoding)
if 'Question' not in data.columns or 'Answers' not in data.columns:
raise ValueError("CSV must contain 'Question' and 'Answers' columns.")
data = data.dropna(subset=['Question', 'Answers'])
logger.info(f"Loaded {len(data)} entries from {file_path}")
return data['Question'].tolist(), data['Answers'].tolist()
except Exception as e:
logger.error(f"Error loading CSV: {e}")
return [], []
# Path to your CSV file (ensure 'AIChatbot.csv' is in the repository)
csv_file_path = "AIChatbot.csv"
corpus_questions, corpus_answers = load_csv(csv_file_path)
if not corpus_questions:
raise ValueError("Failed to load the knowledge base.")
###############################################################################
# 4) Sentence Embeddings & Cross-Encoder
###############################################################################
embedding_model_name = "sentence-transformers/multi-qa-mpnet-base-dot-v1"
try:
embedding_model = SentenceTransformer(embedding_model_name)
logger.info(f"Loaded embedding model: {embedding_model_name}")
except Exception as e:
logger.error(f"Failed to load embedding model: {e}")
raise e
try:
question_embeddings = embedding_model.encode(corpus_questions, convert_to_tensor=True)
logger.info("Encoded question embeddings successfully.")
except Exception as e:
logger.error(f"Failed to encode question embeddings: {e}")
raise e
cross_encoder_name = "cross-encoder/ms-marco-MiniLM-L-6-v2"
try:
cross_encoder = CrossEncoder(cross_encoder_name)
logger.info(f"Loaded cross-encoder model: {cross_encoder_name}")
except Exception as e:
logger.error(f"Failed to load cross-encoder model: {e}")
raise e
###############################################################################
# 5) Retrieval + Re-Ranking
###############################################################################
class EmbeddingRetriever:
def __init__(self, questions, answers, embeddings, model, cross_encoder):
self.questions = questions
self.answers = answers
self.embeddings = embeddings
self.model = model
self.cross_encoder = cross_encoder
def retrieve(self, query: str, top_k: int = 3):
try:
query_embedding = self.model.encode(query, convert_to_tensor=True)
scores = util.pytorch_cos_sim(query_embedding, self.embeddings)[0].cpu().tolist()
scored_data = sorted(zip(self.questions, self.answers, scores), key=lambda x: x[2], reverse=True)[:top_k]
cross_inputs = [[query, candidate[0]] for candidate in scored_data]
cross_scores = self.cross_encoder.predict(cross_inputs)
reranked = sorted(zip(scored_data, cross_scores), key=lambda x: x[1], reverse=True)
final_retrieved = [(entry[0][1], entry[1]) for entry in reranked]
logger.debug(f"Retrieved and reranked answers: {final_retrieved}")
return final_retrieved
except Exception as e:
logger.error(f"Error during retrieval: {e}")
logger.debug("Exception details:", exc_info=True)
return []
retriever = EmbeddingRetriever(corpus_questions, corpus_answers, question_embeddings, embedding_model, cross_encoder)
###############################################################################
# 6) Sanity Check Tool
###############################################################################
class QuestionSanityChecker:
def __init__(self, llm: GeminiLLM):
self.llm = llm
def is_relevant(self, question: str) -> bool:
prompt = (
f"You are an assistant that determines whether a question is relevant to daily wellness.\n\n"
f"Question: {question}\n\n"
f"Is the above question relevant to daily wellness? Respond with 'Yes' or 'No' only."
)
try:
response = self.llm._call(prompt)
is_yes = 'yes' in response.lower()
is_no = 'no' in response.lower()
logger.debug(f"Sanity check response: '{response}', interpreted as is_yes={is_yes}, is_no={is_no}")
if is_yes and not is_no:
return True
elif is_no and not is_yes:
return False
else:
# Ambiguous response
logger.warning(f"Sanity check ambiguous response: '{response}'. Defaulting to 'No'.")
return False
except Exception as e:
logger.error(f"Error in sanity check: {e}")
logger.debug("Exception details:", exc_info=True)
return False
# Instantiate the sanity checker globally
sanity_checker = QuestionSanityChecker(llm)
###############################################################################
# 7) smolagents Integration: GROQ Model and Web Search
###############################################################################
# Initialize the smolagents' LiteLLMModel with GROQ model
smol_model = HfApiModel()
# Instantiate the DuckDuckGo search tool
search_tool = DuckDuckGoSearchTool()
# Create the web agent with the search tool
web_agent = CodeAgent(
tools=[search_tool],
model=smol_model
)
# Define the managed web agent
managed_web_agent = ManagedAgent(
agent=web_agent,
name="web_search",
description="Runs a web search for you. Provide your query as an argument."
)
# Create the manager agent with managed web agent and additional tools if needed
manager_agent = CodeAgent(
tools=[], # Add additional tools here if required
model=smol_model,
managed_agents=[managed_web_agent]
)
###############################################################################
# 8) Answer Expansion
###############################################################################
class AnswerExpander:
def __init__(self, llm: GeminiLLM):
self.llm = llm
def expand(self, query: str, retrieved_answers: List[str], detail: bool = False) -> str:
"""
Synthesize answers into a single cohesive response.
If detail=True, provide a more detailed response.
"""
try:
reference_block = "\n".join(
f"- {idx+1}) {ans}" for idx, ans in enumerate(retrieved_answers, start=1)
)
# ADDED: More elaboration if detail=True
detail_instructions = (
"Provide a thorough, in-depth explanation, adding relevant tips and context, "
"while remaining creative and brand-aligned. "
if detail else
"Provide a concise response in no more than 4 sentences."
)
prompt = (
f"You are Daily Wellness AI, a friendly wellness expert. Below are multiple "
f"potential answers retrieved from a local knowledge base. You have a user question.\n\n"
f"Question: {query}\n\n"
f"Retrieved Answers:\n{reference_block}\n\n"
f"Please synthesize these references into a single cohesive, creative, and brand-aligned response. "
f"{detail_instructions} "
f"End with a short inspirational note.\n\n"
"Disclaimer: This is general wellness information, not a substitute for professional medical advice."
)
logger.debug(f"Generated prompt for answer expansion: {prompt}")
response = self.llm._call(prompt)
logger.debug(f"Expanded answer: {response}")
return response.strip()
except Exception as e:
logger.error(f"Error expanding answer: {e}")
logger.debug("Exception details:", exc_info=True)
return "Sorry, an error occurred while generating a response."
answer_expander = AnswerExpander(llm)
###############################################################################
# 9) Persistent Cache (ADDED)
###############################################################################
CACHE_FILE = "query_cache.json"
SIMILARITY_THRESHOLD_CACHE = 0.8 # Adjust for how close a query must be to reuse cache
def load_cache() -> Dict:
"""Load the cache from the local JSON file."""
if os.path.isfile(CACHE_FILE):
try:
with open(CACHE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logger.error(f"Failed to load cache file: {e}")
return {}
return {}
def save_cache(cache_data: Dict):
"""Save the cache dictionary to a local JSON file."""
try:
with open(CACHE_FILE, "w", encoding="utf-8") as f:
json.dump(cache_data, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"Failed to save cache file: {e}")
def compute_hash(text: str) -> str:
"""Compute a simple hash for the text to handle duplicates in a consistent way."""
return hashlib.md5(text.encode("utf-8")).hexdigest()
# ADDED: Load cache at startup
cache_store = load_cache()
###############################################################################
# 9.1) Utility to attempt cached retrieval (ADDED)
###############################################################################
def get_cached_answer(query: str) -> Optional[str]:
"""
Returns a cached answer if there's a very similar query in the cache.
We'll compare embeddings to find if a stored query is above threshold.
"""
if not cache_store:
return None
# Compute embedding for the incoming query
query_embedding = embedding_model.encode(query, convert_to_tensor=True)
# Check all cached items
best_score = 0.0
best_answer = None
for cached_q, cache_data in cache_store.items():
stored_embedding = np.array(cache_data["embedding"], dtype=np.float32)
score = util.pytorch_cos_sim(query_embedding, stored_embedding)[0].item()
if score > best_score:
best_score = score
best_answer = cache_data["answer"]
if best_score >= SIMILARITY_THRESHOLD_CACHE:
logger.info(f"Cache hit! Similarity: {best_score:.2f}, returning cached answer.")
return best_answer
return None
def store_in_cache(query: str, answer: str):
"""
Store a query-answer pair in the cache with the query's embedding.
"""
query_embedding = embedding_model.encode(query, convert_to_tensor=True).cpu().tolist()
cache_key = compute_hash(query)
cache_store[cache_key] = {
"query": query,
"answer": answer,
"embedding": query_embedding
}
save_cache(cache_store)
###############################################################################
# 10) Query Handling
###############################################################################
def handle_query(query: str, detail: bool = False) -> str:
"""
Main function to process the query.
:param query: The user's question.
:param detail: Whether the user wants a more detailed response.
:return: Response string from Daily Wellness AI.
"""
if not query or not isinstance(query, str) or len(query.strip()) == 0:
return "Please provide a valid question."
try:
# 1) Sanity Check: Determine if the question is relevant to daily wellness
is_relevant = sanity_checker.is_relevant(query)
if not is_relevant:
return "Your question seems out of context or not related to daily wellness. Please ask a wellness-related question."
# 2) Proceed with retrieval from the knowledge base
retrieved = retriever.retrieve(query)
# 3) Check the cache
cached_answer = get_cached_answer(query)
# 4) If no retrieved data from the knowledge base
if not retrieved:
# If we do have a cached answer, return it
if cached_answer:
logger.info("No relevant entries found in knowledge base. Returning cached answer.")
return cached_answer
# Otherwise, no KB results and no cache => no answer
return "I'm sorry, I couldn't find an answer to your question."
# 5) We have retrieved data; let's check for similarity threshold
top_score = retrieved[0][1] # Assuming the list is sorted descending
similarity_threshold = 0.3 # Adjust this threshold based on empirical results
if top_score < similarity_threshold:
# (Low similarity) Perform web search using manager_agent
logger.info("Similarity score below threshold. Performing web search.")
web_search_response = manager_agent.run(query)
logger.debug(f"Web search response: {web_search_response}")
# Combine any cached answer (if it exists) with the web result
if cached_answer:
blend_prompt = (
f"Combine the following previous answer with the new web results to create a more creative and accurate response. "
f"Do not include any of the previous prompt or instructions in your response. "
f"Add positivity and conclude with a short inspirational note.\n\n"
f"Previous Answer:\n{cached_answer}\n\n"
f"Web Results:\n{web_search_response}"
)
final_answer = llm._call(blend_prompt).strip()
else:
# If no cache, just return the web response
final_answer = (
f"**Daily Wellness AI**\n\n"
f"{web_search_response}\n\n"
"Disclaimer: This information is retrieved from the web and is not a substitute for professional medical advice.\n\n"
"Wishing you a calm and wonderful day!"
)
# Store in cache
store_in_cache(query, final_answer)
return final_answer
# 6) If similarity is sufficient, we will finalize an answer from the knowledge base
responses = [ans for ans, score in retrieved]
# 6a) If we have a cached answer, let's blend it with the new knowledge base data
if cached_answer:
blend_prompt = (
f"Combine the previous answer with the newly retrieved answers to enhance creativity and accuracy. "
f"Do not include any of the previous prompt or instructions in your response. "
f"Add new insights, creativity, and conclude with a short inspirational note.\n\n"
f"Previous Answer:\n{cached_answer}\n\n"
f"New Retrieved Answers:\n" + "\n".join(f"- {r}" for r in responses)
)
final_answer = llm._call(blend_prompt).strip()
else:
# 6b) No cache => proceed with normal expansions
final_answer = answer_expander.expand(query, responses, detail=detail)
# 7) Store new or blended answer in cache
store_in_cache(query, final_answer)
return final_answer
except Exception as e:
logger.error(f"Error handling query: {e}")
logger.debug("Exception details:", exc_info=True)
return "An error occurred while processing your request."
###############################################################################
# 11) Gradio Interface
###############################################################################
def gradio_interface(query: str, detail: bool):
"""
Gradio interface function that optionally takes a detail parameter for longer responses.
"""
try:
response = handle_query(query, detail=detail)
formatted_response = response # Response is already formatted
return formatted_response
except Exception as e:
logger.error(f"Error in Gradio interface: {e}")
logger.debug("Exception details:", exc_info=True)
return "**An error occurred while processing your request. Please try again later.**"
# ADDED: We now have a checkbox for detail in the Gradio UI
interface = gr.Interface(
fn=gradio_interface,
inputs=[
gr.Textbox(
lines=2,
placeholder="e.g., What is box breathing?",
label="Ask Daily Wellness AI"
),
gr.Checkbox(
label="In-Depth Answer?",
value=False,
info="Check for a longer, more detailed response."
)
],
outputs=gr.Markdown(label="Answer from Daily Wellness AI"),
title="Daily Wellness AI",
description="Ask wellness-related questions and receive synthesized, creative answers. Optionally request a more in-depth response.",
theme="default",
examples=[
["What is box breathing and how does it help reduce anxiety?", True],
["Provide a daily wellness schedule incorporating box breathing techniques.", False],
["What are some tips for maintaining good posture while working at a desk?", True],
["Who is the CEO of Hugging Face?", False] # Example of an out-of-context question
],
allow_flagging="never"
)
###############################################################################
# 12) Launch Gradio
###############################################################################
if __name__ == "__main__":
try:
# For Hugging Face Spaces, set share=True to create a public link
interface.launch(server_name="0.0.0.0", server_port=7860, debug=False, share=True)
except Exception as e:
logger.error(f"Failed to launch Gradio interface: {e}")
logger.debug("Exception details:", exc_info=True)
|