Phoenix21 commited on
Commit
1b5e3e9
·
verified ·
1 Parent(s): 741a8ce

fix: Refine handle_query prompts to exclude internal instructions from user responses 1

Browse files

- Updated the handle_query function to remove conversational preambles that were being included in user-facing answers.
- Added explicit instructions within prompts to prevent the model from echoing back any part of the prompt.
- Structured prompts clearly with separators and labels to guide the model in generating clean, relevant responses.
- Ensured that only the synthesized and enhanced answers are presented to the user without any internal prompt text.
last working 1e7a57d99fc7d6862f193e11598041bc6e68fb7a

Files changed (1) hide show
  1. app.py +2 -425
app.py CHANGED
@@ -1,373 +1,3 @@
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
- # Use role-based messages if supported
82
- system_message = {
83
- "role": "system",
84
- "content": "You are Daily Wellness AI, a friendly and professional wellness assistant."
85
- }
86
- user_message = {
87
- "role": "user",
88
- "content": prompt
89
- }
90
-
91
- chat_session.send_message(system_message)
92
- chat_session.send_message(user_message)
93
-
94
- response = chat_session.get_response()
95
- logger.debug(f"Raw response received: {response.text}")
96
-
97
- return response.text
98
- except Exception as e:
99
- logger.error(f"Error generating response with GeminiLLM: {e}")
100
- logger.debug("Exception details:", exc_info=True)
101
- raise e
102
-
103
- # Instantiate the GeminiLLM globally
104
- llm = GeminiLLM()
105
-
106
- ###############################################################################
107
- # 3) CSV Loading and Processing
108
- ###############################################################################
109
- def load_csv(file_path: str):
110
- try:
111
- if not os.path.isfile(file_path):
112
- logger.error(f"CSV file does not exist: {file_path}")
113
- return [], []
114
-
115
- with open(file_path, 'rb') as f:
116
- result = chardet.detect(f.read())
117
- encoding = result['encoding']
118
-
119
- data = pd.read_csv(file_path, encoding=encoding)
120
- if 'Question' not in data.columns or 'Answers' not in data.columns:
121
- raise ValueError("CSV must contain 'Question' and 'Answers' columns.")
122
- data = data.dropna(subset=['Question', 'Answers'])
123
-
124
- logger.info(f"Loaded {len(data)} entries from {file_path}")
125
- return data['Question'].tolist(), data['Answers'].tolist()
126
- except Exception as e:
127
- logger.error(f"Error loading CSV: {e}")
128
- return [], []
129
-
130
- # Path to your CSV file (ensure 'AIChatbot.csv' is in the repository)
131
- csv_file_path = "AIChatbot.csv"
132
- corpus_questions, corpus_answers = load_csv(csv_file_path)
133
- if not corpus_questions:
134
- raise ValueError("Failed to load the knowledge base.")
135
-
136
- ###############################################################################
137
- # 4) Sentence Embeddings & Cross-Encoder
138
- ###############################################################################
139
- embedding_model_name = "sentence-transformers/multi-qa-mpnet-base-dot-v1"
140
- try:
141
- embedding_model = SentenceTransformer(embedding_model_name)
142
- logger.info(f"Loaded embedding model: {embedding_model_name}")
143
- except Exception as e:
144
- logger.error(f"Failed to load embedding model: {e}")
145
- raise e
146
-
147
- try:
148
- question_embeddings = embedding_model.encode(corpus_questions, convert_to_tensor=True)
149
- logger.info("Encoded question embeddings successfully.")
150
- except Exception as e:
151
- logger.error(f"Failed to encode question embeddings: {e}")
152
- raise e
153
-
154
- cross_encoder_name = "cross-encoder/ms-marco-MiniLM-L-6-v2"
155
- try:
156
- cross_encoder = CrossEncoder(cross_encoder_name)
157
- logger.info(f"Loaded cross-encoder model: {cross_encoder_name}")
158
- except Exception as e:
159
- logger.error(f"Failed to load cross-encoder model: {e}")
160
- raise e
161
-
162
- ###############################################################################
163
- # 5) Retrieval + Re-Ranking
164
- ###############################################################################
165
- class EmbeddingRetriever:
166
- def __init__(self, questions, answers, embeddings, model, cross_encoder):
167
- self.questions = questions
168
- self.answers = answers
169
- self.embeddings = embeddings
170
- self.model = model
171
- self.cross_encoder = cross_encoder
172
-
173
- def retrieve(self, query: str, top_k: int = 3):
174
- try:
175
- query_embedding = self.model.encode(query, convert_to_tensor=True)
176
- scores = util.pytorch_cos_sim(query_embedding, self.embeddings)[0].cpu().tolist()
177
- scored_data = sorted(zip(self.questions, self.answers, scores), key=lambda x: x[2], reverse=True)[:top_k]
178
-
179
- cross_inputs = [[query, candidate[0]] for candidate in scored_data]
180
- cross_scores = self.cross_encoder.predict(cross_inputs)
181
-
182
- reranked = sorted(zip(scored_data, cross_scores), key=lambda x: x[1], reverse=True)
183
- final_retrieved = [(entry[0][1], entry[1]) for entry in reranked]
184
- logger.debug(f"Retrieved and reranked answers: {final_retrieved}")
185
- return final_retrieved
186
- except Exception as e:
187
- logger.error(f"Error during retrieval: {e}")
188
- logger.debug("Exception details:", exc_info=True)
189
- return []
190
-
191
- retriever = EmbeddingRetriever(corpus_questions, corpus_answers, question_embeddings, embedding_model, cross_encoder)
192
-
193
- ###############################################################################
194
- # 6) Sanity Check Tool
195
- ###############################################################################
196
- class QuestionSanityChecker:
197
- def __init__(self, llm: GeminiLLM):
198
- self.llm = llm
199
-
200
- def is_relevant(self, question: str) -> bool:
201
- prompt = (
202
- f"Determine whether the following question is relevant to daily wellness.\n\n"
203
- f"Question: {question}\n\n"
204
- f"Is the above question relevant to daily wellness? Respond with 'Yes' or 'No' only."
205
- )
206
- try:
207
- response = self.llm._call(prompt)
208
- is_yes = 'yes' in response.lower()
209
- logger.debug(f"Sanity check response: {response}, interpreted as {is_yes}")
210
- return is_yes
211
- except Exception as e:
212
- logger.error(f"Error in sanity check: {e}")
213
- logger.debug("Exception details:", exc_info=True)
214
- return False
215
-
216
- # Instantiate the sanity checker globally
217
- sanity_checker = QuestionSanityChecker(llm)
218
-
219
- ###############################################################################
220
- # 7) smolagents Integration: GROQ Model and Web Search
221
- ###############################################################################
222
- # Initialize the smolagents' LiteLLMModel with GROQ model
223
- smol_model = LiteLLMModel("groq/llama3-8b-8192")
224
-
225
- # Instantiate the DuckDuckGo search tool
226
- search_tool = DuckDuckGoSearchTool()
227
-
228
- # Create the web agent with the search tool
229
- web_agent = CodeAgent(
230
- tools=[search_tool],
231
- model=smol_model
232
- )
233
-
234
- # Define the managed web agent
235
- managed_web_agent = ManagedAgent(
236
- agent=web_agent,
237
- name="web_search",
238
- description="Runs a web search for you. Provide your query as an argument."
239
- )
240
-
241
- # Create the manager agent with managed web agent and additional tools if needed
242
- manager_agent = CodeAgent(
243
- tools=[], # Add additional tools here if required
244
- model=smol_model,
245
- managed_agents=[managed_web_agent]
246
- )
247
-
248
- ###############################################################################
249
- # 8) Answer Expansion
250
- ###############################################################################
251
- class AnswerExpander:
252
- def __init__(self, llm: GeminiLLM):
253
- self.llm = llm
254
-
255
- def expand(self, query: str, retrieved_answers: List[str], detail: bool = False) -> str:
256
- """
257
- Synthesize answers into a single cohesive response.
258
- If detail=True, provide a more detailed response.
259
- """
260
- try:
261
- reference_block = "\n".join(
262
- f"- {idx+1}) {ans}" for idx, ans in enumerate(retrieved_answers, start=1)
263
- )
264
-
265
- # ADDED: More elaboration if detail=True
266
- detail_instructions = (
267
- "Provide a thorough, in-depth explanation, adding relevant tips and context, "
268
- "while remaining creative and brand-aligned. "
269
- if detail else
270
- "Provide a concise response in no more than 4 sentences."
271
- )
272
-
273
- prompt = (
274
- f"Synthesize the following retrieved answers into a single cohesive, creative, and brand-aligned response. "
275
- f"{detail_instructions} "
276
- f"Conclude with a short inspirational note.\n\n"
277
- f"Question: {query}\n\n"
278
- f"Retrieved Answers:\n{reference_block}\n\n"
279
- "Disclaimer: This is general wellness information and not a substitute for professional medical advice."
280
- )
281
-
282
- logger.debug(f"Generated prompt for answer expansion: {prompt}")
283
- response = self.llm._call(prompt)
284
- logger.debug(f"Expanded answer: {response}")
285
- return response.strip()
286
- except Exception as e:
287
- logger.error(f"Error expanding answer: {e}")
288
- logger.debug("Exception details:", exc_info=True)
289
- return "Sorry, an error occurred while generating a response."
290
-
291
- answer_expander = AnswerExpander(llm)
292
-
293
- ###############################################################################
294
- # 9) Persistent Cache (ADDED)
295
- ###############################################################################
296
- CACHE_FILE = "query_cache.json"
297
- SIMILARITY_THRESHOLD_CACHE = 0.8 # Adjust for how close a query must be to reuse cache
298
-
299
- def load_cache() -> Dict:
300
- """Load the cache from the local JSON file."""
301
- if os.path.isfile(CACHE_FILE):
302
- try:
303
- with open(CACHE_FILE, "r", encoding="utf-8") as f:
304
- return json.load(f)
305
- except Exception as e:
306
- logger.error(f"Failed to load cache file: {e}")
307
- return {}
308
- return {}
309
-
310
- def save_cache(cache_data: Dict):
311
- """Save the cache dictionary to a local JSON file."""
312
- try:
313
- with open(CACHE_FILE, "w", encoding="utf-8") as f:
314
- json.dump(cache_data, f, ensure_ascii=False, indent=2)
315
- except Exception as e:
316
- logger.error(f"Failed to save cache file: {e}")
317
-
318
- def compute_hash(text: str) -> str:
319
- """Compute a simple hash for the text to handle duplicates in a consistent way."""
320
- return hashlib.md5(text.encode("utf-8")).hexdigest()
321
-
322
- # ADDED: Load cache at startup
323
- cache_store = load_cache()
324
-
325
- ###############################################################################
326
- # 9.1) Utility to attempt cached retrieval (ADDED)
327
- ###############################################################################
328
- def get_cached_answer(query: str) -> Optional[str]:
329
- """
330
- Returns a cached answer if there's a very similar query in the cache.
331
- We'll compare embeddings to find if a stored query is above threshold.
332
- """
333
- if not cache_store:
334
- return None
335
-
336
- # Compute embedding for the incoming query
337
- query_embedding = embedding_model.encode(query, convert_to_tensor=True)
338
-
339
- # Check all cached items
340
- best_score = 0.0
341
- best_answer = None
342
-
343
- for cached_q, cache_data in cache_store.items():
344
- stored_embedding = np.array(cache_data["embedding"], dtype=np.float32)
345
- score = util.pytorch_cos_sim(query_embedding, stored_embedding)[0].item()
346
- if score > best_score:
347
- best_score = score
348
- best_answer = cache_data["answer"]
349
-
350
- if best_score >= SIMILARITY_THRESHOLD_CACHE:
351
- logger.info(f"Cache hit! Similarity: {best_score:.2f}, returning cached answer.")
352
- return best_answer
353
- return None
354
-
355
- def store_in_cache(query: str, answer: str):
356
- """
357
- Store a query-answer pair in the cache with the query's embedding.
358
- """
359
- query_embedding = embedding_model.encode(query, convert_to_tensor=True).cpu().tolist()
360
- cache_key = compute_hash(query)
361
- cache_store[cache_key] = {
362
- "query": query,
363
- "answer": answer,
364
- "embedding": query_embedding
365
- }
366
- save_cache(cache_store)
367
-
368
- ###############################################################################
369
- # 10) Query Handling
370
- ###############################################################################
371
  def handle_query(query: str, detail: bool = False) -> str:
372
  """
373
  Main function to process the query.
@@ -413,6 +43,7 @@ def handle_query(query: str, detail: bool = False) -> str:
413
  if cached_answer:
414
  blend_prompt = (
415
  f"Combine the following previous answer with the new web results to create a more creative and accurate response. "
 
416
  f"Add positivity and conclude with a short inspirational note.\n\n"
417
  f"Previous Answer:\n{cached_answer}\n\n"
418
  f"Web Results:\n{web_search_response}"
@@ -438,6 +69,7 @@ def handle_query(query: str, detail: bool = False) -> str:
438
  if cached_answer:
439
  blend_prompt = (
440
  f"Combine the previous answer with the newly retrieved answers to enhance creativity and accuracy. "
 
441
  f"Add new insights, creativity, and conclude with a short inspirational note.\n\n"
442
  f"Previous Answer:\n{cached_answer}\n\n"
443
  f"New Retrieved Answers:\n" + "\n".join(f"- {r}" for r in responses)
@@ -455,58 +87,3 @@ def handle_query(query: str, detail: bool = False) -> str:
455
  logger.error(f"Error handling query: {e}")
456
  logger.debug("Exception details:", exc_info=True)
457
  return "An error occurred while processing your request."
458
-
459
- ###############################################################################
460
- # 11) Gradio Interface
461
- ###############################################################################
462
- def gradio_interface(query: str, detail: bool):
463
- """
464
- Gradio interface function that optionally takes a detail parameter for longer responses.
465
- """
466
- try:
467
- response = handle_query(query, detail=detail)
468
- formatted_response = response # Response is already formatted
469
- return formatted_response
470
- except Exception as e:
471
- logger.error(f"Error in Gradio interface: {e}")
472
- logger.debug("Exception details:", exc_info=True)
473
- return "**An error occurred while processing your request. Please try again later.**"
474
-
475
- # ADDED: We now have a checkbox for detail in the Gradio UI
476
- interface = gr.Interface(
477
- fn=gradio_interface,
478
- inputs=[
479
- gr.Textbox(
480
- lines=2,
481
- placeholder="e.g., What is box breathing?",
482
- label="Ask Daily Wellness AI"
483
- ),
484
- gr.Checkbox(
485
- label="In-Depth Answer?",
486
- value=False,
487
- info="Check for a longer, more detailed response."
488
- )
489
- ],
490
- outputs=gr.Markdown(label="Answer from Daily Wellness AI"),
491
- title="Daily Wellness AI",
492
- description="Ask wellness-related questions and receive synthesized, creative answers. Optionally request a more in-depth response.",
493
- theme="default",
494
- examples=[
495
- ["What is box breathing and how does it help reduce anxiety?", True],
496
- ["Provide a daily wellness schedule incorporating box breathing techniques.", False],
497
- ["What are some tips for maintaining good posture while working at a desk?", True],
498
- ["Who is the CEO of Hugging Face?", False] # Example of an out-of-context question
499
- ],
500
- allow_flagging="never"
501
- )
502
-
503
- ###############################################################################
504
- # 12) Launch Gradio
505
- ###############################################################################
506
- if __name__ == "__main__":
507
- try:
508
- # For Hugging Face Spaces, set share=False
509
- interface.launch(server_name="0.0.0.0", server_port=7860, debug=False)
510
- except Exception as e:
511
- logger.error(f"Failed to launch Gradio interface: {e}")
512
- logger.debug("Exception details:", exc_info=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def handle_query(query: str, detail: bool = False) -> str:
2
  """
3
  Main function to process the query.
 
43
  if cached_answer:
44
  blend_prompt = (
45
  f"Combine the following previous answer with the new web results to create a more creative and accurate response. "
46
+ f"Do not include any of the previous prompt or instructions in your response. "
47
  f"Add positivity and conclude with a short inspirational note.\n\n"
48
  f"Previous Answer:\n{cached_answer}\n\n"
49
  f"Web Results:\n{web_search_response}"
 
69
  if cached_answer:
70
  blend_prompt = (
71
  f"Combine the previous answer with the newly retrieved answers to enhance creativity and accuracy. "
72
+ f"Do not include any of the previous prompt or instructions in your response. "
73
  f"Add new insights, creativity, and conclude with a short inspirational note.\n\n"
74
  f"Previous Answer:\n{cached_answer}\n\n"
75
  f"New Retrieved Answers:\n" + "\n".join(f"- {r}" for r in responses)
 
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."