Futuresony commited on
Commit
2ae5792
·
verified ·
1 Parent(s): d744dd8

Upload gold_app.py

Browse files
Files changed (1) hide show
  1. gold_app.py +1194 -0
gold_app.py ADDED
@@ -0,0 +1,1194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import gradio as gr
4
+ from huggingface_hub import InferenceClient
5
+ import torch
6
+ import re
7
+ import warnings
8
+ import time
9
+ import json
10
+ import asyncio # Import asyncio for asynchronous operations
11
+ # Removed specific transformers imports that might not be strictly necessary for InferenceClient
12
+ # from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, BitsAndBytesConfig
13
+ from sentence_transformers import SentenceTransformer, util, CrossEncoder
14
+ import gspread
15
+ # Removed google.auth.default as service account from dict is used
16
+ # from google.auth import default
17
+ from tqdm import tqdm
18
+ from ddgs import DDGS
19
+ import spacy
20
+ from datetime import date, timedelta, datetime
21
+ from dateutil.relativedelta import relativedelta # Corrected import
22
+ import traceback
23
+ import base64
24
+ import dateparser
25
+ from dateparser.search import search_dates
26
+ import pytz
27
+ # Removed userdata as secrets are accessed via environment variables in Spaces
28
+ # from google.colab import userdata
29
+ import os # Ensure os is imported for environment variables
30
+ from datasets import Dataset, DatasetDict, concatenate_datasets, load_dataset
31
+ from huggingface_hub import HfApi, login # Import login for initial auth
32
+
33
+ import faiss
34
+ import numpy as np
35
+ import pickle
36
+
37
+
38
+ # --- SQL Logging Imports and Connection Placeholder (Removed for HF Space) ---
39
+ # Removed SQL related code as per user's request to use HF Datasets
40
+ # ---
41
+
42
+ # Define the dataset name (replace with your actual Hugging Face username and desired dataset name)
43
+ # Ensure this dataset is set to private on the Hugging Face Hub
44
+ dataset_name = "Futuresony/Logs_Conversation" # REPLACE WITH YOUR ACTUAL DATASET NAME
45
+
46
+ # Global variable to store the dataset
47
+ conversation_dataset = None
48
+
49
+ # Initialize HfApi for pushing - Use token from environment variable
50
+ # No need to re-initialize HfApi with token here as login handles it
51
+ # hf_api = HfApi(token=HF_TOKEN)
52
+
53
+
54
+ # Suppress warnings
55
+ warnings.filterwarnings("ignore", category=UserWarning)
56
+
57
+ # Define global variables and load secrets from environment variables for HF Spaces
58
+ # HF_TOKEN is now accessed via os.environ or handled by huggingface_hub login
59
+ HF_TOKEN = os.getenv("HF_TOKEN") # Access HF_TOKEN from environment variable
60
+ # Add a print statement to check if HF_TOKEN is loaded
61
+ print(f"HF_TOKEN loaded: {'Yes' if HF_TOKEN else 'No'}")
62
+
63
+ SHEET_ID = "19ipxC2vHYhpXCefpxpIkpeYdI43a1Ku2kYwecgUULIw"
64
+ # GOOGLE_BASE64_CREDENTIALS is now accessed via os.environ
65
+ GOOGLE_BASE64_CREDENTIALS = os.getenv("GOOGLE_BASE64_CREDENTIALS")
66
+
67
+
68
+ # SECRET_API_KEY is now accessed via os.environ
69
+ SECRET_API_KEY = os.getenv("APP_API_KEY")
70
+ # Add a print statement to check if SECRET_API_KEY is loaded
71
+ print(f"SECRET_API_KEY loaded: {'Yes' if SECRET_API_KEY else 'No'}")
72
+
73
+ if not SECRET_API_KEY:
74
+ print("Warning: APP_API_KEY secret not set. API key validation will fail.")
75
+ elif not SECRET_API_KEY.startswith("fs_"):
76
+ print("Warning: APP_API_KEY secret does not start with 'fs_'. Please check your secret.")
77
+
78
+ # Authenticate with Hugging Face Hub using the token from environment variable
79
+ try:
80
+ print("Attempting to authenticate with Hugging Face Hub...")
81
+ # login() automatically looks for HF_TOKEN in environment variables
82
+ login(add_to_git_credential=True)
83
+ print("Hugging Face Hub authentication successful.")
84
+ except Exception as e:
85
+ print(f"Hugging Face Hub authentication failed: {e}")
86
+ print(traceback.format_exc())
87
+
88
+
89
+ # Initialize InferenceClient for primary model (LLaMA-3.3-70B-Instruct)
90
+ primary_client = InferenceClient("meta-llama/Llama-3.3-70B-Instruct", token=HF_TOKEN)
91
+ print("Primary model (LLaMA-3.3-70B-Instruct) client initialized.")
92
+
93
+ # Initialize InferenceClient for fallback model (Gemma-2-9b-it)
94
+ fallback_client = InferenceClient("google/gemma-2-9b-it", token=HF_TOKEN)
95
+ print("Fallback model (Gemma-2-9b-it) client initialized.")
96
+
97
+
98
+ # Load spacy model for sentence splitting
99
+ nlp = None
100
+ try:
101
+ nlp = spacy.load("en_core_web_sm")
102
+ print("SpaCy model 'en_core_web_sm' loaded.")
103
+ except OSError:
104
+ print("SpaCy model 'en_core_web_sm' not found. Downloading...")
105
+ try:
106
+ import subprocess
107
+ subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"], check=True)
108
+ nlp = spacy.load("en_core_web_sm")
109
+ print("SpaCy model 'en_core_web_sm' downloaded and loaded.")
110
+ except Exception as e:
111
+ print(f"Failed to download or load SpaCy model: {e}")
112
+
113
+ # Load SentenceTransformer for RAG/business info retrieval and semantic detection
114
+ embedder = None
115
+ try:
116
+ print("Attempting to load Sentence Transformer (sentence-transformers/paraphrase-MiniLM-L6-v2)...")
117
+ embedder = SentenceTransformer("sentence-transformers/paraphrase-MiniLM-L6-v2")
118
+ print("Sentence Transformer loaded.")
119
+ except Exception as e:
120
+ print(f"Error loading Sentence Transformer: {e}")
121
+
122
+ # Load a Cross-Encoder model for re-ranking retrieved documents
123
+ reranker = None
124
+ try:
125
+ print("Attempting to load Cross-Encoder Reranker (cross-encoder/ms-marco-MiniLM-L6-v2)...")
126
+ reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L6-v2')
127
+ print("Cross-Encoder Reranker loaded.")
128
+ except Exception as e:
129
+ print(f"Error loading Cross-Encoder Reranker: {e}")
130
+ print("Please ensure the model identifier 'cross-encoder/ms-marco-MiniLM-L6-v2' is correct and accessible on Hugging Face Hub.")
131
+ print(traceback.format_exc())
132
+ reranker = None
133
+
134
+ # Google Sheets Authentication
135
+ gc = None
136
+ def authenticate_google_sheets():
137
+ """Authenticates with Google Sheets using base64 encoded credentials."""
138
+ global gc
139
+ print("Authenticating Google Account...")
140
+ if not GOOGLE_BASE64_CREDENTIALS:
141
+ print("Error: GOOGLE_BASE64_CREDENTIALS secret not found.")
142
+ return False
143
+ try:
144
+ credentials_json = base64.b64decode(GOOGLE_BASE64_CREDENTIALS).decode('utf-8')
145
+ credentials = json.loads(credentials_json)
146
+ gc = gspread.service_account_from_dict(credentials)
147
+ print("Google Sheets authentication successful via service account.")
148
+ return True
149
+ except Exception as e:
150
+ print(f"Google Sheets authentication failed: {e}")
151
+ print(traceback.format_exc())
152
+ print("Please ensure your GOOGLE_BASE64_CREDENTIALS secret is correctly set and contains valid service account credentials.")
153
+ return False
154
+
155
+ # Google Sheets Data Loading and Embedding for RAG
156
+ data = []
157
+ descriptions_for_embedding = []
158
+ embeddings = torch.tensor([]) # This will store embeddings for RAG data
159
+ business_info_available = False
160
+
161
+ def load_business_info():
162
+ """Loads business information from Google Sheet and creates embeddings."""
163
+ global data, descriptions_for_embedding, embeddings, business_info_available
164
+ business_info_available = False
165
+ if gc is None:
166
+ print("Skipping Google Sheet loading: Google Sheets client not authenticated.")
167
+ return
168
+ if not SHEET_ID:
169
+ print("Error: SHEET_ID not set.")
170
+ return
171
+ try:
172
+ sheet = gc.open_by_key(SHEET_ID).sheet1
173
+ print(f"Successfully opened Google Sheet with ID: {SHEET_ID}")
174
+ data_records = sheet.get_all_records()
175
+ if not data_records:
176
+ print(f"Warning: No data records found in Google Sheet with ID: {SHEET_ID}")
177
+ data = []
178
+ descriptions_for_embedding = []
179
+ else:
180
+ filtered_data = [row for row in data_records if row.get('Service') and row.get('Description')]
181
+ if not filtered_data:
182
+ print("Warning: Filtered data is empty after checking for 'Service' and 'Description'.")
183
+ data = []
184
+ descriptions_for_embedding = []
185
+ else:
186
+ data = filtered_data
187
+ descriptions_for_embedding = [f"Service: {row['Service']}. Description: {row['Description']}" for row in data]
188
+ if descriptions_for_embedding and embedder is not None:
189
+ print("Encoding descriptions for RAG...")
190
+ try:
191
+ embeddings = embedder.encode(descriptions_for_embedding, convert_to_tensor=True)
192
+ print("Encoding complete. RAG embeddings created.")
193
+ business_info_available = True
194
+ except Exception as e:
195
+ print(f"Error during description encoding for RAG: {e}")
196
+ embeddings = torch.tensor([])
197
+ business_info_available = False
198
+ else:
199
+ print("Skipping encoding descriptions for RAG: No descriptions found or embedder not available.")
200
+ embeddings = torch.tensor([])
201
+ business_info_available = False
202
+ print(f"Loaded {len(descriptions_for_embedding)} entries from Google Sheet for embedding/RAG.")
203
+ if not business_info_available:
204
+ print("Business information retrieval (RAG) is NOT available.")
205
+ else:
206
+ print("Business information retrieval (RAG) is available.")
207
+ except gspread.exceptions.SpreadsheetNotFound:
208
+ print(f"Error: Google Sheet with ID '{SHEET_ID}' not found.")
209
+ print("Please check the SHEET_ID and ensure your authenticated Google Account has access to this sheet.")
210
+ business_info_available = False
211
+ except Exception as e:
212
+ print(f"An error occurred while accessing the Google Sheet: {e}")
213
+ print(traceback.format_exc())
214
+ business_info_available = False
215
+
216
+ # Business Info Retrieval (RAG) function - Reusing the existing one
217
+ def retrieve_business_info(query: str, top_n: int = 3) -> list:
218
+ """
219
+ Retrieves relevant business information from loaded data based on a query.
220
+ """
221
+ global data, embeddings
222
+ if not business_info_available or embedder is None or not descriptions_for_embedding or not data or embeddings.numel() == 0:
223
+ print("Business information retrieval is not available or RAG data is empty.")
224
+ return []
225
+ try:
226
+ query_embedding = embedder.encode(query, convert_to_tensor=True)
227
+ # Ensure both tensors are on the same device for cosine similarity calculation
228
+ if query_embedding.device != embeddings.device:
229
+ query_embedding = query_embedding.to(embeddings.device)
230
+
231
+ cosine_scores = util.cos_sim(query_embedding, embeddings)[0]
232
+ top_results_indices = torch.topk(cosine_scores, k=min(top_n, len(data)))[1].tolist()
233
+ top_results = [data[i] for i in top_results_indices]
234
+ if reranker is not None and top_results:
235
+ print("Re-ranking top results...")
236
+ rerank_pairs = [(query, descriptions_for_embedding[i]) for i in top_results_indices]
237
+ rerank_scores = reranker.predict(rerank_pairs)
238
+ reranked_indices = sorted(range(len(rerank_scores)), key=lambda i: rerank_scores[i], reverse=True)
239
+ reranked_results = [top_results[i] for i in reranked_indices]
240
+ print("Re-ranking complete.")
241
+ return reranked_results
242
+ else:
243
+ return top_results
244
+ except Exception as e:
245
+ print(f"Error during business information retrieval: {e}")
246
+ print(traceback.format_exc())
247
+ return []
248
+
249
+
250
+ # Function to perform DuckDuckGo Search and return results with URLs
251
+ async def perform_duckduckgo_search(query: str, max_results: int = 5):
252
+ """
253
+ Performs a search using DuckDuckGo asynchronously and returns a list of dictionaries.
254
+ """
255
+ print(f"Executing Tool: perform_duckduckgo_search with query='{query}')")
256
+ search_results_list = []
257
+ try:
258
+ await asyncio.sleep(1) # Simulate async operation
259
+ with DDGS() as ddgs:
260
+ search_query = query.strip()
261
+ if not search_query or len(search_query.split()) < 2:
262
+ print(f"Skipping search for short query: '{search_query}'")
263
+ return []
264
+ print(f"Sending search query to DuckDuckGo: '{search_query}'")
265
+ # DDGS text method is not inherently async, but we can run it in a thread
266
+ # to make the chat function awaitable.
267
+ loop = asyncio.get_event_loop()
268
+ results_generator = await loop.run_in_executor(None, lambda: list(ddgs.text(search_query, max_results=max_results)))
269
+ results_found = False
270
+ for r in results_generator:
271
+ search_results_list.append(r)
272
+ results_found = True
273
+ print(f"Raw results from DuckDuckGo: {search_results_list}")
274
+ if not results_found and max_results > 0:
275
+ print(f"DuckDuckGo search for '{search_query}' returned no results.")
276
+ elif results_found:
277
+ print(f"DuckDuckGo search for '{search_query}' completed. Found {len(search_results_list)} results.")
278
+ except Exception as e:
279
+ print(f"Error during Duckduckgo search for '{search_query if 'search_query' in locals() else query}': {e}")
280
+ print(traceback.format_exc())
281
+ return f"An error occurred during web search: {e}" # Return error message on failure
282
+ return search_results_list
283
+
284
+ # Define the new semantic date/time detection and calculation function using dateparser
285
+ async def perform_date_calculation(query: str) -> str or None:
286
+ """
287
+ Analyzes query for date/time information using dateparser asynchronously.
288
+ """
289
+ print(f"Executing Tool: perform_date_calculation with query='{query}') using dateparser.search_dates")
290
+ try:
291
+ await asyncio.sleep(0.1) # Simulate async operation
292
+ eafrica_tz = pytz.timezone('Africa/Dar_es_Salaam')
293
+ now = datetime.now(eafrica_tz)
294
+ except pytz.UnknownTimeZoneError:
295
+ print("Error: Unknown timezone 'Africa/Dar_es_Salaam'. Using default system time.")
296
+ now = datetime.now()
297
+ try:
298
+ # dateparser.search_dates is not inherently async, run in thread
299
+ loop = asyncio.get_event_loop()
300
+ found = await loop.run_in_executor(None, lambda: search_dates(
301
+ query,
302
+ settings={
303
+ "PREFER_DATES_FROM": "future",
304
+ "RELATIVE_BASE": now
305
+ },
306
+ languages=['sw', 'en']
307
+ ))
308
+
309
+ if not found:
310
+ print("dateparser.search_dates could not parse any date/time.")
311
+ return None
312
+ text_snippet, parsed = found[0]
313
+ print(f"dateparser.search_dates found: text='{text_snippet}', parsed='{parsed}'")
314
+ is_swahili = any(swahili_phrase in query.lower() for swahili_phrase in ['tarehe', 'siku', 'saa', 'muda', 'leo', 'kesho', 'jana', 'ngapi', 'gani', 'mwezi', 'mwaka', 'habari', 'mambo', 'shikamoo', 'karibu', 'asante'])
315
+
316
+ if is_swahili:
317
+ query_lower = query.lower().strip()
318
+ if query_lower in ['habari', 'mambo', 'habari gani']:
319
+ return "Nzuri! Habari zako?"
320
+ elif query_lower in ['shikamoo']:
321
+ return "Marahaba!"
322
+ elif query_lower in ['asante']:
323
+ return "Karibu!"
324
+ elif query_lower in ['karibu']:
325
+ return "Asante!"
326
+
327
+ if now.tzinfo is not None and parsed.tzinfo is None:
328
+ parsed = now.tzinfo.localize(parsed)
329
+ elif now.tzinfo is None and parsed.tzinfo is not None:
330
+ parsed = parsed.replace(tzinfo=None)
331
+
332
+ if parsed.date() == now.date():
333
+ if abs((parsed - now).total_seconds()) < 60 or parsed.time() == datetime.min.time():
334
+ print("Query parsed to today's date and time is close to 'now' or midnight, returning current time/date.")
335
+ if is_swahili:
336
+ return f"Kwa saa za Afrika Mashariki (Tanzania), tarehe ya leo ni {now.strftime('%A, %d %B %Y')} na saa ni {now.strftime('%H:%M:%S')}."
337
+ else:
338
+ return f"In East Africa (Tanzania), the current date is {now.strftime('%A, %d %B %Y')} and the time is {now.strftime('%H:%M:%S')}."
339
+ else:
340
+ print(f"Query parsed to a specific time today: {parsed.strftime('%H:%M:%S')}")
341
+ if is_swahili:
342
+ return f"Hiyo inafanyika leo, {parsed.strftime('%A, %d %B %Y')}, saa {parsed.strftime('%H:%M:%S')} saa za Afrika Mashariki."
343
+ else:
344
+ return f"That falls on today, {parsed.strftime('%A, %d %B %Y')}, at {parsed.strftime('%H:%M:%S')} East Africa Time."
345
+ else:
346
+ print(f"Query parsed to a specific date: {parsed.strftime('%A, %d %B %Y')} at {parsed.strftime('%H:%M:%S')}")
347
+ time_str = parsed.strftime('%H:%M:%S')
348
+ date_str = parsed.strftime('%A, %d %B %Y')
349
+ if parsed.tzinfo:
350
+ tz_name = parsed.tzinfo.tzname(parsed) or 'UTC'
351
+ if is_swahili:
352
+ return f"Hiyo inafanyika tarehe {date_str} saa {time_str} {tz_name}."
353
+ else:
354
+ return f"That falls on {date_str} at {time_str} {tz_name}."
355
+ else:
356
+ if is_swahili:
357
+ return f"Hiyo inafanyika tarehe {date_str} saa {time_str}."
358
+ else:
359
+ return f"That falls on {date_str} at {time_str}."
360
+ except Exception as e:
361
+ print(f"Error during dateparser.search_dates execution: {e}")
362
+ print(traceback.format_exc())
363
+ return f"An error occurred while parsing date/time: {e}" # Return error message on failure
364
+
365
+ # Function to determine if a query requires a tool or can be answered directly
366
+ # Modified to include complexity check for routing to primary vs fallback
367
+ def determine_tool_usage(query: str) -> tuple[str, str]:
368
+ """
369
+ Analyzes the query to determine if a specific tool is needed and its complexity.
370
+ Returns a tuple: (tool_name, complexity_level)
371
+ Complexity levels: 'simple' (fallback), 'complex' (primary)
372
+ """
373
+ query_lower = query.lower()
374
+
375
+ swahili_conversational_phrases = ['habari', 'mambo', 'shikamoo', 'karibu', 'asante', 'habari gani']
376
+ if any(swahili_phrase in query_lower for swahili_phrase in swahili_conversational_phrases):
377
+ print(f"Detected a Swahili conversational phrase: '{query}'. Using 'date_calculation' tool and 'simple' complexity.")
378
+ return "date_calculation", "simple" # Simple conversational queries routed to fallback
379
+
380
+ # Check for business info retrieval first
381
+ if business_info_available:
382
+ # Use a simple LLM call to check if the query is business-related
383
+ messages_business_check = [{"role": "user", "content": f"Does the following query ask about a specific person, service, offering, or description that is likely to be found *only* within a specific business's internal knowledge base, and not general knowledge? For example, questions about 'Salum' or 'Jackson Kisanga' are likely business-related, while questions about 'the current president of the USA' or 'who won the Ballon d'Or' are general knowledge. Answer only 'yes' or 'no'. Query: {query}"}]
384
+ try:
385
+ business_check_response = primary_client.chat_completion( # Use primary client for this check
386
+ messages=messages_business_check,
387
+ max_tokens=10,
388
+ temperature=0.1
389
+ ).choices[0].message.content.strip().lower()
390
+ if business_check_response == "yes":
391
+ print(f"Detected as specific business info query based on LLM check: '{query}'. Using 'business_info_retrieval' tool and 'simple' complexity.")
392
+ # Business info RAG is handled by the fallback model
393
+ return "business_info_retrieval", "simple"
394
+ else:
395
+ print(f"LLM check indicates not a specific business info query: '{query}')")
396
+ except Exception as e:
397
+ print(f"Error during LLM call for business info check for query '{query}': {e}")
398
+ print(traceback.format_exc())
399
+ print(f"Proceeding without business info check for query '{query}' due to error.")
400
+
401
+ # Check for date/time calculation
402
+ # We don't pre-calculate here, just check if the tool might be relevant
403
+ date_time_keywords = ['date', 'time', 'when', 'what day', 'what time', 'leo', 'kesho', 'jana', 'muda', 'saa', 'tarehe', 'siku']
404
+ if any(keyword in query_lower for keyword in date_time_keywords):
405
+ print(f"Detected date/time keywords in query: '{query}'. Suggesting 'date_calculation' tool.")
406
+ # We still need to determine complexity for the final generation
407
+ messages_complexity = [{"role": "user", "content": f"Is the following query simple or complex? A simple query is a basic question, a greeting, or a question that can be answered with a short, direct response. A complex query requires detailed understanding, multiple steps, or external information synthesis. Respond ONLY with 'simple' or 'complex'. Query: {query}"}]
408
+ try:
409
+ complexity_response = primary_client.chat_completion(
410
+ messages=messages_complexity,
411
+ max_tokens=10,
412
+ temperature=0.1
413
+ ).choices[0].message.content.strip().lower()
414
+ print(f"Determined complexity for date/time query '{query}': '{complexity_response}'")
415
+ return "date_calculation", complexity_response # Use date_calculation tool, complexity from LLM
416
+ except Exception as e:
417
+ print(f"Error determining complexity for date/time query '{query}': {e}. Defaulting to 'simple'.")
418
+ return "date_calculation", "simple" # Default to simple on error
419
+
420
+
421
+ # Check if web search is needed for general knowledge or current info
422
+ messages_tool_determination_search = [{"role": "user", "content": f"Does the following query require searching the web for current or general knowledge information (e.g., news, facts, definitions, current events)? Respond ONLY with 'duckduckgo_search' or 'none'. Query: {query}"}]
423
+ try:
424
+ search_determination_response = primary_client.chat_completion( # Use primary client for this check
425
+ messages=messages_tool_determination_search,
426
+ max_tokens=20,
427
+ temperature=0.1,
428
+ top_p=0.9
429
+ ).choices[0].message.content or ""
430
+ response_lower = search_determination_response.strip().lower()
431
+ if "duckduckgo_search" in response_lower:
432
+ print(f"Model-determined tool for '{query}': 'duckduckgo_search'. Using 'complex' complexity.")
433
+ # Web search queries are generally more complex and routed to primary
434
+ return "duckduckgo_search", "complex"
435
+ else:
436
+ print(f"Model-determined tool for '{query}': 'none' (for search).")
437
+ except Exception as e:
438
+ print(f"Error during LLM call for search tool determination for query '{query}': {e}")
439
+ print(traceback.format_exc())
440
+ print(f"Proceeding without search tool check for query '{query}' due to error.")
441
+
442
+ # If no specific tool is determined, route based on query complexity
443
+ messages_complexity = [{"role": "user", "content": f"Is the following query simple or complex? A simple query is a basic question, a greeting, or a question that can be answered with a short, direct response. A complex query requires detailed understanding, multiple steps, or external information synthesis. Respond ONLY with 'simple' or 'complex'. Query: {query}"}]
444
+ try:
445
+ complexity_response = primary_client.chat_completion( # Use primary client for complexity check
446
+ messages=messages_complexity,
447
+ max_tokens=10,
448
+ temperature=0.1
449
+ ).choices[0].message.content.strip().lower()
450
+
451
+ if "complex" in complexity_response:
452
+ print(f"Determined query complexity for '{query}': 'complex'. Using 'none' tool.")
453
+ return "none", "complex" # No tool, complex query routed to primary
454
+ else:
455
+ print(f"Determined query complexity for '{query}': 'simple'. Using 'none' tool.")
456
+ return "none", "simple" # No tool, simple query routed to fallback
457
+
458
+ except Exception as e:
459
+ print(f"Error during LLM call for complexity determination for query '{query}': {e}")
460
+ print(traceback.format_exc())
461
+ print(f"Defaulting query '{query}' to 'complex' due to error.")
462
+ return "none", "complex" # Default to complex on error
463
+
464
+
465
+ # Function to summarize chat history
466
+ def summarize_chat_history(chat_history: list[dict]) -> str:
467
+ """
468
+ Summarizes the provided chat history using the LLM.
469
+ Uses the primary client for summarization.
470
+ """
471
+ print("\n--- Summarizing chat history ---")
472
+ if not chat_history:
473
+ print("Chat history is empty, no summarization needed.")
474
+ return ""
475
+
476
+ history_text = "\n".join([f"{msg['role']}: {msg['content']}" for msg in chat_history])
477
+
478
+ prompt_for_summary = f"""
479
+ Please provide a concise summary of the following conversation history.
480
+ Conversation History:
481
+ {history_text}
482
+
483
+ Summary:
484
+ """
485
+ try:
486
+ messages_summary = [{"role": "user", "content": prompt_for_summary}]
487
+ summary_response = primary_client.chat_completion( # Use primary client
488
+ messages=messages_summary,
489
+ max_tokens=200, # Adjust based on desired summary length
490
+ temperature=0.3,
491
+ top_p=0.9
492
+ ).choices[0].message.content or ""
493
+ print("Chat history summarization successful using primary client.")
494
+ return summary_response.strip()
495
+ except Exception as e:
496
+ print(f"Error during LLM call for chat history summarization (primary client): {e}")
497
+ print(traceback.format_exc())
498
+ return "Unable to summarize previous conversation."
499
+
500
+
501
+ # Function to generate text using the LLM, incorporating tool results if available
502
+ # Modified to use primary or fallback client based on complexity
503
+ def generate_text(prompt: str, tool_results: dict = None, chat_history: list[dict] = None, complexity_level: str = 'complex') -> str:
504
+ """
505
+ Generates text using the configured LLM (primary or fallback), optionally incorporating tool results and chat history.
506
+ Implements conversation summarization and windowing for long histories.
507
+ """
508
+ persona_instructions = """You are absa_ai, an AI developed on August 7, 2025, by the absa team. Your knowledge about business data comes from the company's internal Google Sheet.
509
+ You are a friendly and helpful chatbot. Respond to greetings appropriately (e.g., "Hello!", "Hi there!", "Habari!"). If the user uses Swahili greetings or simple conversational phrases, respond in Swahili. Otherwise, respond in English unless the query is clearly in Swahili. Handle conversational flow and ask follow-up questions when appropriate.
510
+ If the user asks a question about other companies or general knowledge, answer their question. However, subtly remind them that your primary expertise and purpose are related to Absa-specific information.
511
+ """
512
+ messages = [{"role": "user", "content": persona_instructions}]
513
+
514
+ # --- Conversation Summarization and Windowing ---
515
+ SUMMARY_THRESHOLD = 10 # Summarize after 10 turns (5 user/assistant pairs)
516
+ HISTORY_WINDOW_SIZE = 4 # Keep the last 4 turns (2 user/assistant pairs)
517
+
518
+ if chat_history:
519
+ print(f"Current chat history length: {len(chat_history)}")
520
+ if len(chat_history) > SUMMARY_THRESHOLD:
521
+ print("Chat history exceeds threshold, summarizing older turns.")
522
+ history_to_summarize = chat_history[:-HISTORY_WINDOW_SIZE]
523
+ summary = summarize_chat_history(history_to_summarize) # summarize_chat_history uses primary client
524
+ if summary:
525
+ messages.append({"role": "assistant", "content": f"Summary of previous conversation: {summary}"})
526
+ print("Added summary to messages.")
527
+ recent_history = chat_history[-HISTORY_WINDOW_SIZE:]
528
+ print(f"Including last {len(recent_history)} turns from history.")
529
+ for message_dict in recent_history:
530
+ role = message_dict.get("role")
531
+ content = message_dict.get("content")
532
+ if role in ["user", "assistant"] and content is not None:
533
+ messages.append({"role": role, "content": content})
534
+ else:
535
+ print("Including full chat history in LLM prompt.")
536
+ for message_dict in chat_history:
537
+ role = message_dict.get("role")
538
+ content = message_dict.get("content")
539
+ if role in ["user", "assistant"] and content is not None:
540
+ messages.append({"role": role, "content": content})
541
+
542
+
543
+ current_user_content = prompt
544
+ if tool_results and any(tool_results.values()):
545
+ current_user_content += "\n\nTool Results:\n"
546
+ for question, results in tool_results.items():
547
+ if results is not None and results != "none": # Only include if results are not None or "none"
548
+ current_user_content += f"--- Results for: {question} ---\n"
549
+ if isinstance(results, list):
550
+ if not results: # Handle empty list case
551
+ current_user_content += "No results found.\n\n"
552
+ else:
553
+ for i, result in enumerate(results):
554
+ if isinstance(result, dict) and 'Service' in result and 'Description' in result:
555
+ current_user_content += f"Business Info {i+1}:\nService: {result.get('Service', 'N/A')}\nDescription: {result.get('Description', 'N/A')}\n\n"
556
+ elif isinstance(result, dict) and 'url' in result:
557
+ current_user_content += f"Search Result {i+1}:\nTitle: {result.get('title', 'N/A')}\nURL: {result.get('url', 'N/A')}\nSnippet: {result.get('body', 'N/A')}\n\n"
558
+ else:
559
+ current_user_content += f"{result}\n\n"
560
+ elif isinstance(results, dict):
561
+ if not results: # Handle empty dict case
562
+ current_user_content += "No results found.\n\n"
563
+ else:
564
+ for key, value in results.items():
565
+ current_user_content += f"{key}: {value}\n"
566
+ current_user_content += "\n"
567
+ else: # Handle string results (like date calculation or error messages)
568
+ current_user_content += f"{results}\n\n"
569
+
570
+ current_user_content += "Based on the provided tool results and the conversation history, answer the user's latest query. If a question was answered by a tool, use the tool's result directly in your response. If a tool returned an error or no results, acknowledge that and try to answer based on your general knowledge or other tool results. Maintain the language of the original query if possible, especially for simple greetings or direct questions answered by tools."
571
+ print("Added tool results and instruction to final prompt.")
572
+ else:
573
+ current_user_content += "Based on the conversation history, answer the user's latest query."
574
+ print("No tool results to add to final prompt, relying on conversation history.")
575
+
576
+ messages.append({"role": "user", "content": current_user_content})
577
+
578
+ generation_config = {
579
+ "temperature": 0.7,
580
+ "max_new_tokens": 500,
581
+ "top_p": 0.95,
582
+ "top_k": 50,
583
+ "do_sample": True,
584
+ }
585
+
586
+ try:
587
+ if complexity_level == 'complex':
588
+ print("Using primary client for generation.")
589
+ response = primary_client.chat_completion(
590
+ messages=messages,
591
+ max_tokens=generation_config.get("max_new_tokens", 512),
592
+ temperature=generation_config.get("temperature", 0.7),
593
+ top_p=generation_config.get("top_p", 0.95)
594
+ ).choices[0].message.content or ""
595
+ print("LLM generation successful using primary client.")
596
+ else: # complexity_level == 'simple' or fallback needed
597
+ print("Using fallback client for generation.")
598
+ # Use fallback_client for chat completion with Gemma
599
+ response = fallback_client.chat_completion(
600
+ messages=messages,
601
+ max_tokens=generation_config.get("max_new_tokens", 512),
602
+ temperature=generation_config.get("temperature", 0.7),
603
+ top_p=generation_config.get("top_p", 0.95)
604
+ ).choices[0].message.content or ""
605
+ print("LLM generation successful using fallback client.")
606
+
607
+
608
+ return response.strip()
609
+ except Exception as e:
610
+ print(f"Error during final LLM generation (primary or fallback): {e}")
611
+ print(traceback.format_exc())
612
+ return "An error occurred while generating the final response."
613
+
614
+ # Function to log conversation data to the Hugging Face Dataset and push
615
+ def log_conversation(user_query: str, model_response: str, tool_details: dict = None, user_id: str = None):
616
+ """
617
+ Logs conversation data (query, response, timestamp, optional details) to the Hugging Face Dataset
618
+ and pushes the changes to the Hub.
619
+ """
620
+ global conversation_dataset # Access the global dataset variable
621
+ global dataset_name # Access the dataset name
622
+
623
+ print("\n--- Attempting to log conversation to Hugging Face Dataset ---")
624
+
625
+ if conversation_dataset is None:
626
+ print("Warning: Hugging Face dataset not loaded or created. Skipping conversation logging.")
627
+ return
628
+
629
+ try:
630
+ timestamp = datetime.now().isoformat()
631
+ # Ensure tool_details is a JSON string or None
632
+ tool_details_json = json.dumps(tool_details) if tool_details is not None else None
633
+ # Handle potential None values for user_id
634
+ user_id_val = user_id if user_id is not None else "anonymous"
635
+
636
+ # Create a dictionary for the new log entry
637
+ new_log_entry = {
638
+ 'timestamp': timestamp,
639
+ 'user_id': user_id_val,
640
+ 'user_query': user_query,
641
+ 'model_response': model_response,
642
+ 'tool_details': tool_details_json
643
+ }
644
+
645
+ # Append the new log entry to the 'train' split of the dataset
646
+ new_row_dataset = Dataset.from_dict({key: [value] for key, value in new_log_entry.items()})
647
+
648
+ # Check if the 'train' split exists before concatenating
649
+ if 'train' in conversation_dataset:
650
+ conversation_dataset['train'] = concatenate_datasets([conversation_dataset['train'], new_row_dataset])
651
+ else:
652
+ # If 'train' doesn't exist (e.g., first log entry), create it
653
+ # Need to define the schema here as well if creating from scratch
654
+ log_schema = {
655
+ 'timestamp': 'string',
656
+ 'user_id': 'string',
657
+ 'user_query': 'string',
658
+ 'model_response': 'string',
659
+ 'tool_details': 'string'
660
+ }
661
+ conversation_dataset = DatasetDict({'train': new_dataset.cast(log_schema)}) # Use new_dataset with schema
662
+
663
+
664
+ print("Conversation data successfully added to the dataset object.")
665
+
666
+ # --- Pushing to the Hugging Face Hub ---
667
+ print(f"Attempting to push dataset to {dataset_name}...")
668
+ # Use the push_to_hub method of the DatasetDict
669
+ # Use commit_message for clarity
670
+ conversation_dataset.push_to_hub(dataset_name, token=HF_TOKEN, commit_message=f"Add conversation log: {timestamp}")
671
+ print(f"Successfully pushed dataset to {dataset_name}.")
672
+
673
+
674
+ except Exception as e:
675
+ print(f"An unexpected error occurred during Hugging Face Dataset logging and pushing: {e}")
676
+ print(traceback.format_exc())
677
+
678
+
679
+ # Need to import concatenate_datasets
680
+ from datasets import concatenate_datasets
681
+ from huggingface_hub import HfApi # Ensure HfApi is imported
682
+
683
+ # --- Caching Implementation ---
684
+ # Define the path for the FAISS index file
685
+ FAISS_INDEX_FILE = "cache.index"
686
+ # Define the path for the metadata file (query text, response, timestamp)
687
+ CACHE_METADATA_FILE = "cache_metadata.pkl"
688
+
689
+ # Global variables for FAISS index and metadata
690
+ faiss_index = None
691
+ cache_metadata = {}
692
+
693
+ # Dimension of the embeddings (should match your embedder model output dimension)
694
+ # For 'sentence-transformers/paraphrase-MiniLM-L6-v2', the dimension is 384
695
+ EMBEDDING_DIM = 384
696
+
697
+ CACHE_SIMILARITY_THRESHOLD = 0.9 # Cosine similarity threshold for cache hit
698
+ CACHE_EXPIRATION_DAYS = 7 # Cache entries expire after 7 days
699
+
700
+
701
+ def initialize_cache():
702
+ """Initializes or loads the FAISS index and cache metadata."""
703
+ global faiss_index, cache_metadata
704
+ print("\n--- Initializing Cache ---")
705
+ if os.path.exists(FAISS_INDEX_FILE) and os.path.exists(CACHE_METADATA_FILE):
706
+ print("Loading existing cache...")
707
+ try:
708
+ faiss_index = faiss.read_index(FAISS_INDEX_FILE)
709
+ with open(CACHE_METADATA_FILE, 'rb') as f:
710
+ cache_metadata = pickle.load(f)
711
+ print(f"Cache loaded successfully. Current cache size: {faiss_index.ntotal}")
712
+ # Clean up expired entries on load
713
+ cleanup_expired_cache_entries()
714
+ except Exception as e:
715
+ print(f"Error loading cache files: {e}. Initializing new cache.")
716
+ print(traceback.format_exc())
717
+ faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM) # Using L2 distance
718
+ cache_metadata = {}
719
+ save_cache() # Save empty cache
720
+ else:
721
+ print("No existing cache found. Initializing new cache.")
722
+ faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM) # Using L2 distance
723
+ cache_metadata = {}
724
+ save_cache() # Save empty cache
725
+
726
+ def save_cache():
727
+ """Saves the FAISS index and cache metadata to files."""
728
+ global faiss_index, cache_metadata
729
+ if faiss_index is None:
730
+ print("Warning: FAISS index not initialized. Cannot save cache.")
731
+ return
732
+ print("Saving cache...")
733
+ try:
734
+ faiss.write_index(faiss_index, FAISS_INDEX_FILE)
735
+ with open(CACHE_METADATA_FILE, 'wb') as f:
736
+ pickle.dump(cache_metadata, f)
737
+ print("Cache saved successfully.")
738
+ except Exception as e:
739
+ print(f"Error saving cache files: {e}")
740
+ print(traceback.format_exc())
741
+
742
+ def get_query_embedding(query: str):
743
+ """Generates an embedding for the given query."""
744
+ if embedder is None:
745
+ print("Warning: Embedder not available. Cannot generate query embedding for caching.")
746
+ return None
747
+ try:
748
+ return embedder.encode(query, convert_to_tensor=False) # Return numpy array for FAISS
749
+ except Exception as e:
750
+ print(f"Error generating embedding for query '{query}': {e}")
751
+ print(traceback.format_exc())
752
+ return None
753
+
754
+ def add_to_cache(query: str, response: str):
755
+ """Adds the query, response, and timestamp to the cache."""
756
+ global faiss_index, cache_metadata
757
+ if embedder is None or faiss_index is None:
758
+ print("Warning: Embedder or FAISS index not available. Cannot add query to cache.")
759
+ return
760
+
761
+ try:
762
+ query_embedding = get_query_embedding(query)
763
+ if query_embedding is None:
764
+ return
765
+
766
+ # Add the embedding to the FAISS index
767
+ faiss_index.add(np.array([query_embedding])) # Add expects a numpy array of shape (n, dim)
768
+
769
+ # Store metadata (query, response, timestamp) keyed by the FAISS index ID
770
+ # The last added embedding gets the index faiss_index.ntotal - 1
771
+ cache_id = faiss_index.ntotal - 1
772
+ now = datetime.now()
773
+ cache_metadata[cache_id] = {
774
+ 'query': query, # Store original query for debugging/verification
775
+ 'response': response,
776
+ 'timestamp': now,
777
+ 'count': 1 # Initialize count
778
+ }
779
+ print(f"Added query and response to cache with ID {cache_id}.")
780
+ save_cache() # Save cache after adding
781
+ print(f"Current cache size: {faiss_index.ntotal}")
782
+
783
+ except Exception as e:
784
+ print(f"Error adding query to cache: {e}")
785
+ print(traceback.format_exc())
786
+
787
+
788
+ def check_cache(query: str):
789
+ """Checks the cache for a similar query and returns the cached response if found and not expired."""
790
+ global faiss_index, cache_metadata
791
+ if faiss_index is None or embedder is None or faiss_index.ntotal == 0:
792
+ print("Cache is empty or not available. Skipping cache check.")
793
+ return None
794
+
795
+ try:
796
+ query_embedding = get_query_embedding(query)
797
+ if query_embedding is None:
798
+ return None
799
+
800
+ # Search the FAISS index for similar embeddings
801
+ # D is distances, I is indices of the nearest neighbors
802
+ D, I = faiss_index.search(np.array([query_embedding]), 1) # Search for the 1 nearest neighbor
803
+
804
+ if I[0][0] != -1 and D[0][0] <= (1 - CACHE_SIMILARITY_THRESHOLD): # Check if a neighbor was found and distance is within threshold
805
+ cached_id = I[0][0]
806
+ print(f"Found potential cache hit with ID {cached_id} and distance {D[0][0]:.4f}.")
807
+
808
+ if cached_id in cache_metadata:
809
+ cached_data = cache_metadata[cached_id]
810
+ now = datetime.now()
811
+ # Check for expiration
812
+ if (now - cached_data['timestamp']).days <= CACHE_EXPIRATION_DAYS:
813
+ print(f"Cache hit! Returning cached response for query: '{query}'")
814
+ # Update timestamp and count on cache hit
815
+ cache_metadata[cached_id]['timestamp'] = now
816
+ cache_metadata[cached_id]['count'] += 1
817
+ save_cache() # Save cache after updating metadata
818
+ return cached_data['response']
819
+ else:
820
+ print(f"Cache entry with ID {cached_id} found but expired.")
821
+ # We could remove the expired entry here, but it's handled by cleanup_expired_cache_entries
822
+ else:
823
+ print(f"Cache ID {cached_id} found in index but not in metadata. Cache inconsistency.")
824
+
825
+ print(f"No suitable cache entry found for query: '{query}'")
826
+ return None
827
+
828
+ except Exception as e:
829
+ print(f"Error during cache check: {e}")
830
+ print(traceback.format_exc())
831
+ return None
832
+
833
+ def cleanup_expired_cache_entries():
834
+ """Removes expired entries from the cache and rebuilds the FAISS index if necessary."""
835
+ global faiss_index, cache_metadata
836
+ if faiss_index is None or faiss_index.ntotal == 0:
837
+ print("Cache is empty or not initialized. No expired entries to clean.")
838
+ return
839
+
840
+ print("Cleaning up expired cache entries...")
841
+ now = datetime.now()
842
+ expired_ids = [
843
+ cache_id for cache_id, cached_data in cache_metadata.items()
844
+ if (now - cached_data['timestamp']).days > CACHE_EXPIRATION_DAYS
845
+ ]
846
+
847
+ if expired_ids:
848
+ print(f"Found {len(expired_ids)} expired cache entries.")
849
+ # Remove from metadata
850
+ for cache_id in expired_ids:
851
+ del cache_metadata[cache_id]
852
+
853
+ # Rebuild FAISS index with non-expired entries
854
+ if cache_metadata:
855
+ print("Rebuilding FAISS index with non-expired entries...")
856
+ try:
857
+ # Get embeddings for non-expired entries
858
+ non_expired_embeddings = []
859
+ non_expired_metadata_list = sorted(cache_metadata.items()) # Sort by ID to maintain order
860
+ for cache_id, cached_data in non_expired_metadata_list:
861
+ # Need to retrieve original query to re-embed
862
+ original_query = cached_data.get('query')
863
+ if original_query and embedder:
864
+ try:
865
+ non_expired_embeddings.append(embedder.encode(original_query, convert_to_tensor=False).tolist())
866
+ except Exception as e:
867
+ print(f"Error re-embedding query '{original_query}': {e}. Skipping.")
868
+
869
+
870
+ if non_expired_embeddings:
871
+ print(f"Re-embedding {len(non_expired_embeddings)} non-expired queries.")
872
+ faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
873
+ faiss_index.add(np.array(non_expired_embeddings))
874
+ print(f"FAISS index rebuilt. New size: {faiss_index.ntotal}")
875
+ else:
876
+ print("No non-expired entries to rebuild FAISS index. Clearing index.")
877
+ faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
878
+ cache_metadata = {} # Clear metadata if index is cleared
879
+
880
+ except Exception as e:
881
+ print(f"Error rebuilding FAISS index: {e}")
882
+ print(traceback.format_exc())
883
+ # On error, it might be safer to clear the cache to avoid inconsistencies
884
+ print("Clearing cache due to rebuild error.")
885
+ faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
886
+ cache_metadata = {}
887
+
888
+ else:
889
+ print("All cache entries expired. Clearing FAISS index and metadata.")
890
+ faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
891
+ cache_metadata = {}
892
+
893
+ save_cache() # Save after cleanup
894
+ else:
895
+ print("No expired cache entries found.")
896
+
897
+
898
+ # Main chat function with query breakdown and tool execution per question
899
+ async def chat(query: str, chat_history: list[dict], api_key: str):
900
+ """
901
+ Processes user queries by breaking down multi-part queries, determining and
902
+ executing appropriate tools for each question asynchronously, and synthesizing results
903
+ using the LLM. Incorporates caching for repeated questions and routes
904
+ to primary or fallback model based on complexity.
905
+ """
906
+ print(f"\n--- chat function received new query ---")
907
+ print(f" query: {query}")
908
+ print(f" Validating against SECRET_API_KEY: {'Yes' if SECRET_API_KEY else 'No'}")
909
+ print(f" chat_history: {chat_history}")
910
+ print(f" api_key from UI received: {'Yes' if api_key else 'No'}")
911
+
912
+
913
+ if not SECRET_API_KEY:
914
+ print("Error: APP_API_KEY secret not set in Hugging Face Space Secrets.")
915
+ # Log failure before returning
916
+ log_conversation(
917
+ user_query=query,
918
+ model_response="API key validation failed: Application not configured correctly. APP_API_KEY secret is missing.",
919
+ tool_details={"validation_status": "failed", "reason": "secret_not_set"},
920
+ user_id="unknown"
921
+ )
922
+ return "API key validation failed: Application not configured correctly. APP_API_KEY secret is missing."
923
+
924
+ if api_key != SECRET_API_KEY:
925
+ print("Error: API key from UI does not match SECRET_API_KEY.")
926
+ # Log failure before returning
927
+ log_conversation(
928
+ user_query=query,
929
+ model_response="API key validation failed: Invalid API key provided.",
930
+ tool_details={"validation_status": "failed", "reason": "invalid_api_key"},
931
+ user_id="unknown"
932
+ )
933
+ return "API key validation failed: Invalid API key provided."
934
+
935
+ # --- Cache Check ---
936
+ cached_response = check_cache(query)
937
+ if cached_response:
938
+ print(f"Returning cached response for query: '{query}'")
939
+ # Log the cached response
940
+ try:
941
+ user_id_to_log = "anonymous"
942
+ if chat_history:
943
+ for turn in chat_history:
944
+ if turn.get("role") == "user" and "user_id:" in turn.get("content", "").lower():
945
+ match = re.search(r"user_id:\s*(\S+)", turn.get("content", ""), re.IGNORECASE)
946
+ if match:
947
+ user_id_to_log = match.group(1)
948
+ break
949
+
950
+ log_conversation(
951
+ user_query=query,
952
+ model_response=cached_response,
953
+ tool_details={"cache_status": "hit"},
954
+ user_id=user_id_to_log
955
+ )
956
+ except Exception as e:
957
+ print(f"Error during logging of cached response: {e}")
958
+ print(traceback.format_exc())
959
+
960
+ return cached_response
961
+
962
+ print("\n--- Breaking down query ---")
963
+ # Use the primary client for query breakdown as it's generally better at understanding complex queries
964
+ prompt_for_question_breakdown = f"""
965
+ Analyze the following query and list each distinct question found within it.
966
+ Present each question on a new line, starting with a hyphen.
967
+ Query: {query}
968
+ """
969
+ try:
970
+ messages_question_breakdown = primary_client.chat_completion( # Use primary client
971
+ messages=[{"role": "user", "content": prompt_for_question_breakdown}],
972
+ max_tokens=100,
973
+ temperature=0.1,
974
+ top_p=0.9
975
+ ).choices[0].message.content or ""
976
+ individual_questions = [line.strip() for line in messages_question_breakdown.split('\n') if line.strip()]
977
+ cleaned_questions = [re.sub(r'^[-*]?\s*', '', q) for q in individual_questions if not q.strip().lower().startswith('note:')]
978
+ print("Individual questions identified:")
979
+ for q in cleaned_questions:
980
+ print(f"- {q}")
981
+ except Exception as e:
982
+ print(f"Error during LLM call for question breakdown (primary client): {e}")
983
+ print(traceback.format_exc())
984
+ print(f"Proceeding with original query as a single question due to breakdown error.")
985
+ cleaned_questions = [query]
986
+
987
+ print("\n--- Determining tools and complexity per question ---")
988
+ determined_tools_and_complexity = {}
989
+ for question in cleaned_questions:
990
+ print(f"\nAnalyzing question for tool determination and complexity: '{question}'")
991
+ tool, complexity = determine_tool_usage(question) # determine_tool_usage uses primary client for checks
992
+ determined_tools_and_complexity[question] = {"tool": tool, "complexity": complexity}
993
+ print(f"Determined tool and complexity for '{question}': Tool='{tool}', Complexity='{complexity}'")
994
+
995
+ print("\nSummary of determined tools and complexity per question:")
996
+ for question, details in determined_tools_and_complexity.items():
997
+ print(f"'{question}': Tool='{details['tool']}', Complexity='{details['complexity']}'")
998
+
999
+ print("\n--- Executing tools asynchronously and collecting results ---")
1000
+ tool_results = {}
1001
+ tasks = []
1002
+ questions_to_process = []
1003
+
1004
+ for question, details in determined_tools_and_complexity.items():
1005
+ tool = details['tool']
1006
+ print(f"\nQueueing tool '{tool}' for question: '{question}')")
1007
+ questions_to_process.append(question)
1008
+ if tool == "date_calculation":
1009
+ tasks.append(perform_date_calculation(question))
1010
+ elif tool == "duckduckgo_search":
1011
+ tasks.append(perform_duckduckgo_search(question))
1012
+ elif tool == "business_info_retrieval":
1013
+ # Business info retrieval is synchronous, run it directly or wrap in run_in_executor
1014
+ # For simplicity and to leverage async, we'll wrap it.
1015
+ loop = asyncio.get_event_loop()
1016
+ tasks.append(loop.run_in_executor(None, retrieve_business_info, question))
1017
+ elif tool == "none":
1018
+ print(f"Skipping tool execution for question: '{question}' as tool is 'none'. LLM will handle.")
1019
+ tasks.append(asyncio.Future()) # Add a placeholder future
1020
+ tasks[-1].set_result("none") # Set result immediately to indicate no tool used
1021
+
1022
+ # Run all tasks concurrently
1023
+ try:
1024
+ results = await asyncio.gather(*tasks, return_exceptions=True)
1025
+ print("\n--- Asynchronous Tool Execution Results ---")
1026
+ for i, question in enumerate(questions_to_process):
1027
+ result = results[i]
1028
+ if isinstance(result, Exception):
1029
+ print(f"Error executing tool for question '{question}': {result}")
1030
+ tool_results[question] = f"An error occurred while fetching information for this part of your query: {result}" # Error message for the user
1031
+ else:
1032
+ print(f"Result for question '{question}': {result}")
1033
+ tool_results[question] = result
1034
+ print("\n-----------------------------------------")
1035
+ except Exception as e:
1036
+ print(f"An error occurred during asynchronous tool execution: {e}")
1037
+ print(traceback.format_exc())
1038
+ # If gathering fails completely, set error for all
1039
+ for question in questions_to_process:
1040
+ tool_results[question] = f"An error occurred while fetching information for this part of your query: {e}"
1041
+
1042
+
1043
+ print("\n--- Collected Tool Results ---")
1044
+ if tool_results:
1045
+ for question, result in tool_results.items():
1046
+ print(f"\nQuestion: {question}")
1047
+ print(f"Result: {result}")
1048
+ else:
1049
+ print("No tool results were collected.")
1050
+ print("\n--------------------------")
1051
+
1052
+ print("\n--- Generating final response ---")
1053
+
1054
+ # Determine the overall complexity to choose the final generation model
1055
+ # If any question was determined as 'complex', use the primary model
1056
+ overall_complexity = 'simple'
1057
+ for details in determined_tools_and_complexity.values():
1058
+ if details['complexity'] == 'complex':
1059
+ overall_complexity = 'complex'
1060
+ break
1061
+ print(f"Overall query complexity determined as: '{overall_complexity}'")
1062
+
1063
+
1064
+ final_response = generate_text(query, tool_results, chat_history, complexity_level=overall_complexity)
1065
+ print("\n--- Final Response from LLM ---")
1066
+ print(final_response)
1067
+ print("\n----------------------------")
1068
+
1069
+ # --- Add response to cache ---
1070
+ # We add the entire query and final response to the cache, not individual questions.
1071
+ add_to_cache(query, final_response)
1072
+
1073
+ try:
1074
+ user_id_to_log = "anonymous"
1075
+ if chat_history:
1076
+ for turn in chat_history:
1077
+ if turn.get("role") == "user" and "user_id:" in turn.get("content", "").lower():
1078
+ match = re.search(r"user_id:\s*(\S+)", turn.get("content", ""), re.IGNORECASE)
1079
+ if match:
1080
+ user_id_to_log = match.group(1)
1081
+ break
1082
+
1083
+ logged_tool_details = {}
1084
+ for question, details in determined_tools_and_complexity.items():
1085
+ logged_tool_details[question] = {
1086
+ "tool_used": details['tool'],
1087
+ "complexity": details['complexity'],
1088
+ "raw_output": tool_results.get(question)
1089
+ }
1090
+ logged_tool_details["cache_status"] = "miss" # Log cache miss when generating a new response
1091
+ logged_tool_details["model_used_for_generation"] = "primary" if overall_complexity == 'complex' else "fallback"
1092
+
1093
+
1094
+ # Call the logging function (currently logs to Hugging Face Dataset)
1095
+ log_conversation(
1096
+ user_query=query,
1097
+ model_response=final_response,
1098
+ tool_details=logged_tool_details,
1099
+ user_id=user_id_to_log
1100
+ )
1101
+ except Exception as e:
1102
+ print(f"Error during conversation logging after response generation: {e}")
1103
+ print(traceback.format_exc())
1104
+
1105
+ return final_response
1106
+
1107
+ # Keep the Gradio interface setup as is for now
1108
+ if __name__ == "__main__":
1109
+ # Load/Create Hugging Face Dataset on startup
1110
+ try:
1111
+ # Attempt to load the existing dataset
1112
+ print(f"Attempting to load dataset from {dataset_name} on startup...")
1113
+ # Use load_dataset for loading directly from the Hub
1114
+ conversation_dataset = load_dataset(dataset_name, token=HF_TOKEN)
1115
+ print(f"Successfully loaded existing dataset from {dataset_name} on startup.")
1116
+ print(conversation_dataset)
1117
+
1118
+ except Exception as e:
1119
+ print(f"Dataset not found or failed to load from {dataset_name} on startup: {e}")
1120
+ print("Creating a new dataset object on startup...")
1121
+
1122
+ # Define the schema for conversation logs
1123
+ # Using 'string' as the data type for simplicity, tool_details will be JSON string
1124
+ log_schema = {
1125
+ 'timestamp': 'string',
1126
+ 'user_id': 'string',
1127
+ 'user_query': 'string',
1128
+ 'model_response': 'string',
1129
+ 'tool_details': 'string' # Store JSON string here
1130
+ }
1131
+
1132
+ # Create an empty dataset with the defined schema
1133
+ empty_data = {col: [] for col in log_schema.keys()}
1134
+ new_dataset = Dataset.from_dict(empty_data)
1135
+
1136
+ # Wrap the dataset in a DatasetDict
1137
+ conversation_dataset = DatasetDict({'train': new_dataset})
1138
+
1139
+ print(f"Created a new empty dataset object with schema: {log_schema}")
1140
+ print(conversation_dataset)
1141
+
1142
+
1143
+ authenticate_google_sheets()
1144
+ load_business_info() # This will also create RAG embeddings if data is loaded
1145
+
1146
+ if nlp is None:
1147
+ print("Warning: SpaCy model not loaded. Sentence splitting may not work correctly.")
1148
+ if embedder is None:
1149
+ print("Warning: Sentence Transformer (embedder) not loaded. RAG will not be available.")
1150
+ if reranker is None:
1151
+ print("Warning: Cross-Encoder Reranker not loaded. Re-ranking of RAG results will not be performed.")
1152
+ if not business_info_available:
1153
+ print("Warning: Business information (Google Sheet data) not loaded successfully. "
1154
+ "RAG will not be available. Please ensure the GOOGLE_BASE64_CREDENTIALS secret is set correctly.")
1155
+
1156
+
1157
+ DESCRIPTION = """
1158
+ # LLM with Tools (DuckDuckGo Search, Date Calculation, Business Info RAG, Hugging Face Dataset Logging) and Two-Tier Model System
1159
+ Ask me anything! I can perform web searches, calculate dates, retrieve business information using RAG, and conversation data will be logged to a Hugging Face Dataset. I use a primary LLaMA-70B model for complex queries and a fallback Gemma-2-9b-it model for simpler ones and RAG synthesis.
1160
+ """
1161
+
1162
+ demo = gr.ChatInterface(
1163
+ fn=chat,
1164
+ stop_btn=None,
1165
+ examples=[
1166
+ ["Hello there! How are you doing?"],
1167
+ ["What is the current time in East Africa?"],
1168
+ ["Tell me about the 'Project Management' service from Absa."],
1169
+ ["Search the web for the latest news on AI."],
1170
+ ["Habari!"],
1171
+ ["What is the date next Tuesday?"],
1172
+ ["What is the time in East Africa and search for latest AI news"],
1173
+ ["Who is Jackson Kisanga?"], # Example for business info retrieval
1174
+ ["What is the weather like in London?"], # Example for web search
1175
+ ["Tell me a joke."], # Example for simple query
1176
+ ],
1177
+ cache_examples=False,
1178
+ type="messages",
1179
+ description=DESCRIPTION,
1180
+ fill_height=True,
1181
+ additional_inputs=[
1182
+ gr.Textbox(label="API Key", type="password", placeholder="Enter your API key (starts with fs_)", interactive=True)
1183
+ ],
1184
+ additional_inputs_accordion="API Key (Required)"
1185
+ )
1186
+
1187
+ try:
1188
+ # Initialize the cache before launching the demo
1189
+ initialize_cache()
1190
+ demo.launch(debug=True, show_error=True)
1191
+ except Exception as e:
1192
+ print(f"Error launching Gradio interface: {e}")
1193
+ print(traceback.format_exc())
1194
+ print("Please check the console output for more details on the error.")