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