broadfield-dev commited on
Commit
872bd49
·
verified ·
1 Parent(s): b7e81ea

Update model_logic.py

Browse files
Files changed (1) hide show
  1. model_logic.py +415 -484
model_logic.py CHANGED
@@ -1,506 +1,437 @@
1
- # memory_logic.py
2
  import os
 
3
  import json
4
- import time
5
- from datetime import datetime
6
  import logging
7
- import re
8
- import threading
9
-
10
- # Conditionally import heavy dependencies
11
- try:
12
- from sentence_transformers import SentenceTransformer
13
- import faiss
14
- import numpy as np
15
- except ImportError:
16
- SentenceTransformer, faiss, np = None, None, None
17
- logging.warning("SentenceTransformers, FAISS, or NumPy not installed. Semantic search will be unavailable.")
18
-
19
- try:
20
- import sqlite3
21
- except ImportError:
22
- sqlite3 = None
23
- logging.warning("sqlite3 module not available. SQLite backend will be unavailable.")
24
-
25
- try:
26
- from datasets import load_dataset, Dataset
27
- except ImportError:
28
- load_dataset, Dataset = None, None
29
- logging.warning("datasets library not installed. Hugging Face Dataset backend will be unavailable.")
30
 
 
 
31
 
 
 
 
 
32
  logger = logging.getLogger(__name__)
33
- # Suppress verbose logs from dependencies
34
- for lib_name in ["sentence_transformers", "faiss", "datasets", "huggingface_hub"]:
35
- if logging.getLogger(lib_name): # Check if logger exists
36
- logging.getLogger(lib_name).setLevel(logging.WARNING)
37
-
38
-
39
- # --- Configuration (Read directly from environment variables) ---
40
- STORAGE_BACKEND = os.getenv("STORAGE_BACKEND", "HF_DATASET").upper() #HF_DATASET, RAM, SQLITE
41
- SQLITE_DB_PATH = os.getenv("SQLITE_DB_PATH", "app_data/ai_memory.db") # Changed default path
42
- HF_TOKEN = os.getenv("HF_TOKEN")
43
- HF_MEMORY_DATASET_REPO = os.getenv("HF_MEMORY_DATASET_REPO", "broadfield-dev/ai-brain") # Example
44
- HF_RULES_DATASET_REPO = os.getenv("HF_RULES_DATASET_REPO", "broadfield-dev/ai-rules") # Example
45
-
46
- # --- Globals for RAG within this module ---
47
- _embedder = None
48
- _dimension = 384 # Default, will be set by embedder
49
- _faiss_memory_index = None
50
- _memory_items_list = [] # Stores JSON strings of memory objects for RAM, or loaded from DB/HF
51
- _faiss_rules_index = None
52
- _rules_items_list = [] # Stores rule text strings
53
-
54
- _initialized = False
55
- _init_lock = threading.Lock()
56
-
57
- # --- Helper: SQLite Connection ---
58
- def _get_sqlite_connection():
59
- if not sqlite3:
60
- raise ImportError("sqlite3 module is required for SQLite backend but not found.")
61
- db_dir = os.path.dirname(SQLITE_DB_PATH)
62
- if db_dir and not os.path.exists(db_dir):
63
- os.makedirs(db_dir, exist_ok=True)
64
- return sqlite3.connect(SQLITE_DB_PATH, timeout=10) # Added timeout
65
-
66
- def _init_sqlite_tables():
67
- if STORAGE_BACKEND != "SQLITE" or not sqlite3:
68
- return
69
- try:
70
- with _get_sqlite_connection() as conn:
71
- cursor = conn.cursor()
72
- # Stores JSON string of the memory object
73
- cursor.execute("""
74
- CREATE TABLE IF NOT EXISTS memories (
75
- id INTEGER PRIMARY KEY AUTOINCREMENT,
76
- memory_json TEXT NOT NULL,
77
- # Optionally add embedding here if not using separate FAISS index
78
- # embedding BLOB,
79
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
80
- )
81
- """)
82
- # Stores the rule text directly
83
- cursor.execute("""
84
- CREATE TABLE IF NOT EXISTS rules (
85
- id INTEGER PRIMARY KEY AUTOINCREMENT,
86
- rule_text TEXT NOT NULL UNIQUE,
87
- # embedding BLOB,
88
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
89
- )
90
- """)
91
- conn.commit()
92
- logger.info("SQLite tables for memories and rules checked/created.")
93
- except Exception as e:
94
- logger.error(f"SQLite table initialization error: {e}", exc_info=True)
95
-
96
- # --- Initialization ---
97
- def initialize_memory_system():
98
- global _initialized, _embedder, _dimension, _faiss_memory_index, _memory_items_list, _faiss_rules_index, _rules_items_list
99
-
100
- with _init_lock:
101
- if _initialized:
102
- logger.info("Memory system already initialized.")
103
- return
104
 
105
- logger.info(f"Initializing memory system with backend: {STORAGE_BACKEND}")
106
- init_start_time = time.time()
107
-
108
- # 1. Load Sentence Transformer Model (always needed for semantic operations)
109
- if not SentenceTransformer or not faiss or not np:
110
- logger.error("Core RAG libraries (SentenceTransformers, FAISS, NumPy) not available. Cannot initialize semantic memory.")
111
- _initialized = False # Mark as not properly initialized
112
- return
113
-
114
- if not _embedder:
115
- try:
116
- logger.info("Loading SentenceTransformer model (all-MiniLM-L6-v2)...")
117
- _embedder = SentenceTransformer('all-MiniLM-L6-v2', cache_folder="./sentence_transformer_cache")
118
- _dimension = _embedder.get_sentence_embedding_dimension() or 384
119
- logger.info(f"SentenceTransformer loaded. Dimension: {_dimension}")
120
- except Exception as e:
121
- logger.critical(f"FATAL: Error loading SentenceTransformer: {e}", exc_info=True)
122
- _initialized = False
123
- return # Cannot proceed without embedder
124
-
125
- # 2. Initialize SQLite if used
126
- if STORAGE_BACKEND == "SQLITE":
127
- _init_sqlite_tables()
128
-
129
- # 3. Load Memories
130
- logger.info("Loading memories...")
131
- temp_memories_json = []
132
- if STORAGE_BACKEND == "RAM":
133
- pass
134
- elif STORAGE_BACKEND == "SQLITE" and sqlite3:
135
- try:
136
- with _get_sqlite_connection() as conn:
137
- temp_memories_json = [row[0] for row in conn.execute("SELECT memory_json FROM memories ORDER BY created_at ASC")]
138
- except Exception as e: logger.error(f"Error loading memories from SQLite: {e}")
139
- elif STORAGE_BACKEND == "HF_DATASET" and HF_TOKEN and Dataset and load_dataset:
140
- try:
141
- logger.info(f"Attempting to load memories from HF Dataset: {HF_MEMORY_DATASET_REPO}")
142
- dataset = load_dataset(HF_MEMORY_DATASET_REPO, token=HF_TOKEN, trust_remote_code=True)
143
- if "train" in dataset and "memory_json" in dataset["train"].column_names:
144
- temp_memories_json = [m_json for m_json in dataset["train"]["memory_json"] if isinstance(m_json, str)]
145
- else: logger.warning(f"HF Dataset {HF_MEMORY_DATASET_REPO} for memories not found or 'memory_json' column missing.")
146
- except Exception as e: logger.error(f"Error loading memories from HF Dataset ({HF_MEMORY_DATASET_REPO}): {e}")
147
-
148
- _memory_items_list = temp_memories_json
149
- logger.info(f"Loaded {len(_memory_items_list)} memory items from {STORAGE_BACKEND}.")
150
-
151
- # 4. Build/Load FAISS Memory Index
152
- _faiss_memory_index = faiss.IndexFlatL2(_dimension)
153
- if _memory_items_list:
154
- logger.info(f"Building FAISS index for {len(_memory_items_list)} memories...")
155
- # Extract text to embed from memory JSON objects
156
- texts_to_embed_mem = []
157
- for mem_json_str in _memory_items_list:
158
- try:
159
- mem_obj = json.loads(mem_json_str)
160
- # Consistent embedding strategy: user input + bot response + takeaway
161
- text = f"User: {mem_obj.get('user_input','')}\nAI: {mem_obj.get('bot_response','')}\nTakeaway: {mem_obj.get('metrics',{}).get('takeaway','N/A')}"
162
- texts_to_embed_mem.append(text)
163
- except json.JSONDecodeError:
164
- logger.warning(f"Skipping malformed memory JSON for FAISS indexing: {mem_json_str[:100]}")
165
-
166
- if texts_to_embed_mem:
167
- try:
168
- embeddings = _embedder.encode(texts_to_embed_mem, convert_to_tensor=False, show_progress_bar=False)
169
- embeddings_np = np.array(embeddings, dtype=np.float32)
170
- if embeddings_np.ndim == 2 and embeddings_np.shape[0] == len(texts_to_embed_mem) and embeddings_np.shape[1] == _dimension:
171
- _faiss_memory_index.add(embeddings_np)
172
- else: logger.error(f"Memory embeddings shape error. Expected ({len(texts_to_embed_mem)}, {_dimension}), Got {embeddings_np.shape if hasattr(embeddings_np, 'shape') else 'N/A'}")
173
- except Exception as e_faiss_mem: logger.error(f"Error building FAISS memory index: {e_faiss_mem}")
174
- logger.info(f"FAISS memory index built. Total items: {_faiss_memory_index.ntotal if _faiss_memory_index else 'N/A'}")
175
-
176
-
177
- # 5. Load Rules
178
- logger.info("Loading rules...")
179
- temp_rules_text = []
180
- if STORAGE_BACKEND == "RAM":
181
- pass
182
- elif STORAGE_BACKEND == "SQLITE" and sqlite3:
183
- try:
184
- with _get_sqlite_connection() as conn:
185
- temp_rules_text = [row[0] for row in conn.execute("SELECT rule_text FROM rules ORDER BY created_at ASC")]
186
- except Exception as e: logger.error(f"Error loading rules from SQLite: {e}")
187
- elif STORAGE_BACKEND == "HF_DATASET" and HF_TOKEN and Dataset and load_dataset:
188
- try:
189
- logger.info(f"Attempting to load rules from HF Dataset: {HF_RULES_DATASET_REPO}")
190
- dataset = load_dataset(HF_RULES_DATASET_REPO, token=HF_TOKEN, trust_remote_code=True)
191
- if "train" in dataset and "rule_text" in dataset["train"].column_names:
192
- temp_rules_text = [r_text for r_text in dataset["train"]["rule_text"] if isinstance(r_text, str) and r_text.strip()]
193
- else: logger.warning(f"HF Dataset {HF_RULES_DATASET_REPO} for rules not found or 'rule_text' column missing.")
194
- except Exception as e: logger.error(f"Error loading rules from HF Dataset ({HF_RULES_DATASET_REPO}): {e}")
195
-
196
- _rules_items_list = sorted(list(set(temp_rules_text))) # Ensure unique and sorted
197
- logger.info(f"Loaded {len(_rules_items_list)} rule items from {STORAGE_BACKEND}.")
198
-
199
- # 6. Build/Load FAISS Rules Index
200
- _faiss_rules_index = faiss.IndexFlatL2(_dimension)
201
- if _rules_items_list:
202
- logger.info(f"Building FAISS index for {len(_rules_items_list)} rules...")
203
- if _rules_items_list: # Check again in case it became empty after filtering
204
- try:
205
- embeddings = _embedder.encode(_rules_items_list, convert_to_tensor=False, show_progress_bar=False)
206
- embeddings_np = np.array(embeddings, dtype=np.float32)
207
- if embeddings_np.ndim == 2 and embeddings_np.shape[0] == len(_rules_items_list) and embeddings_np.shape[1] == _dimension:
208
- _faiss_rules_index.add(embeddings_np)
209
- else: logger.error(f"Rule embeddings shape error. Expected ({len(_rules_items_list)}, {_dimension}), Got {embeddings_np.shape if hasattr(embeddings_np, 'shape') else 'N/A'}")
210
- except Exception as e_faiss_rule: logger.error(f"Error building FAISS rule index: {e_faiss_rule}")
211
- logger.info(f"FAISS rules index built. Total items: {_faiss_rules_index.ntotal if _faiss_rules_index else 'N/A'}")
212
-
213
- _initialized = True
214
- logger.info(f"Memory system initialization complete in {time.time() - init_start_time:.2f}s")
215
-
216
-
217
- # --- Memory Operations (Semantic) ---
218
- def add_memory_entry(user_input: str, metrics: dict, bot_response: str) -> tuple[bool, str]:
219
- """Adds a memory entry to the configured backend and FAISS index."""
220
- global _memory_items_list, _faiss_memory_index
221
- if not _initialized: initialize_memory_system()
222
- if not _embedder or not _faiss_memory_index:
223
- return False, "Memory system or embedder not initialized for adding memory."
224
-
225
- memory_obj = {
226
- "user_input": user_input,
227
- "metrics": metrics,
228
- "bot_response": bot_response,
229
- "timestamp": datetime.utcnow().isoformat()
230
  }
231
- memory_json_str = json.dumps(memory_obj)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
- text_to_embed = f"User: {user_input}\nAI: {bot_response}\nTakeaway: {metrics.get('takeaway', 'N/A')}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
 
235
- try:
236
- embedding = _embedder.encode([text_to_embed], convert_to_tensor=False)
237
- embedding_np = np.array(embedding, dtype=np.float32).reshape(1, -1)
 
 
238
 
239
- if embedding_np.shape != (1, _dimension):
240
- logger.error(f"Memory embedding shape error: {embedding_np.shape}. Expected (1, {_dimension})")
241
- return False, "Embedding shape error."
242
 
243
- # Add to FAISS
244
- _faiss_memory_index.add(embedding_np)
245
-
246
- # Add to in-memory list
247
- _memory_items_list.append(memory_json_str)
248
-
249
- # Add to persistent storage
250
- if STORAGE_BACKEND == "SQLITE" and sqlite3:
251
- with _get_sqlite_connection() as conn:
252
- conn.execute("INSERT INTO memories (memory_json) VALUES (?)", (memory_json_str,))
253
- conn.commit()
254
- elif STORAGE_BACKEND == "HF_DATASET" and HF_TOKEN and Dataset:
255
- # This can be slow, consider batching or async push
256
- logger.info(f"Pushing {len(_memory_items_list)} memories to HF Hub: {HF_MEMORY_DATASET_REPO}")
257
- Dataset.from_dict({"memory_json": list(_memory_items_list)}).push_to_hub(HF_MEMORY_DATASET_REPO, token=HF_TOKEN, private=True) # Ensure 'private' as needed
258
-
259
- logger.info(f"Added memory. RAM: {len(_memory_items_list)}, FAISS: {_faiss_memory_index.ntotal}")
260
- return True, "Memory added successfully."
261
- except Exception as e:
262
- logger.error(f"Error adding memory entry: {e}", exc_info=True)
263
- # TODO: Potential rollback logic if FAISS add succeeded but backend failed (complex)
264
- return False, f"Error adding memory: {e}"
265
-
266
- def retrieve_memories_semantic(query: str, k: int = 3) -> list[dict]:
267
- """Retrieves k most relevant memories using semantic search."""
268
- if not _initialized: initialize_memory_system()
269
- if not _embedder or not _faiss_memory_index or _faiss_memory_index.ntotal == 0:
270
- logger.debug("Cannot retrieve memories: Embedder, FAISS index not ready, or index is empty.")
271
- return []
272
-
273
- try:
274
- query_embedding = _embedder.encode([query], convert_to_tensor=False)
275
- query_embedding_np = np.array(query_embedding, dtype=np.float32).reshape(1, -1)
276
-
277
- if query_embedding_np.shape[1] != _dimension:
278
- logger.error(f"Query embedding dimension mismatch. Expected {_dimension}, got {query_embedding_np.shape[1]}")
279
- return []
280
-
281
- distances, indices = _faiss_memory_index.search(query_embedding_np, min(k, _faiss_memory_index.ntotal))
282
-
283
- results = []
284
- for i in indices[0]:
285
- if 0 <= i < len(_memory_items_list):
286
- try:
287
- results.append(json.loads(_memory_items_list[i]))
288
- except json.JSONDecodeError:
289
- logger.warning(f"Could not parse memory JSON from list at index {i}")
 
 
 
 
290
  else:
291
- logger.warning(f"FAISS index {i} out of bounds for memory_items_list (len: {len(_memory_items_list)})")
292
-
293
- logger.debug(f"Retrieved {len(results)} memories semantically for query: '{query[:50]}...'")
294
- return results
295
- except Exception as e:
296
- logger.error(f"Error retrieving memories semantically: {e}", exc_info=True)
297
- return []
298
-
299
-
300
- # --- Rule (Insight) Operations (Semantic) ---
301
- def add_rule_entry(rule_text: str) -> tuple[bool, str]:
302
- """Adds a rule if valid and not a duplicate. Updates backend and FAISS."""
303
- global _rules_items_list, _faiss_rules_index
304
- if not _initialized: initialize_memory_system()
305
- if not _embedder or not _faiss_rules_index:
306
- return False, "Rule system or embedder not initialized."
307
-
308
- rule_text = rule_text.strip()
309
- if not rule_text: return False, "Rule text cannot be empty."
310
- if not re.match(r"\[(CORE_RULE|RESPONSE_PRINCIPLE|BEHAVIORAL_ADJUSTMENT|GENERAL_LEARNING)\|([\d\.]+?)\](.*)", rule_text, re.I|re.DOTALL):
311
- return False, "Invalid rule format."
312
- if rule_text in _rules_items_list:
313
- return False, "duplicate"
314
-
315
- try:
316
- embedding = _embedder.encode([rule_text], convert_to_tensor=False)
317
- embedding_np = np.array(embedding, dtype=np.float32).reshape(1, -1)
318
-
319
- if embedding_np.shape != (1, _dimension):
320
- return False, "Rule embedding shape error."
321
-
322
- _faiss_rules_index.add(embedding_np)
323
- _rules_items_list.append(rule_text)
324
- _rules_items_list.sort()
325
-
326
- if STORAGE_BACKEND == "SQLITE" and sqlite3:
327
- with _get_sqlite_connection() as conn:
328
- conn.execute("INSERT OR IGNORE INTO rules (rule_text) VALUES (?)", (rule_text,))
329
- conn.commit()
330
- elif STORAGE_BACKEND == "HF_DATASET" and HF_TOKEN and Dataset:
331
- logger.info(f"Pushing {len(_rules_items_list)} rules to HF Hub: {HF_RULES_DATASET_REPO}")
332
- Dataset.from_dict({"rule_text": list(_rules_items_list)}).push_to_hub(HF_RULES_DATASET_REPO, token=HF_TOKEN, private=True)
333
 
334
- logger.info(f"Added rule. RAM: {len(_rules_items_list)}, FAISS: {_faiss_rules_index.ntotal}")
335
- return True, "Rule added successfully."
336
- except Exception as e:
337
- logger.error(f"Error adding rule entry: {e}", exc_info=True)
338
- # Basic rollback if FAISS add succeeded
339
- if rule_text in _rules_items_list and _faiss_rules_index.ntotal > 0: # Crude check
340
- # A full rollback would involve rebuilding FAISS index from _rules_items_list before append.
341
- # For simplicity, this is omitted here. State could be inconsistent on error.
342
- pass
343
- return False, f"Error adding rule: {e}"
344
-
345
- def retrieve_rules_semantic(query: str, k: int = 5) -> list[str]:
346
- """Retrieves k most relevant rules using semantic search."""
347
- if not _initialized: initialize_memory_system()
348
- if not _embedder or not _faiss_rules_index or _faiss_rules_index.ntotal == 0:
349
- return []
350
- try:
351
- query_embedding = _embedder.encode([query], convert_to_tensor=False)
352
- query_embedding_np = np.array(query_embedding, dtype=np.float32).reshape(1, -1)
353
-
354
- if query_embedding_np.shape[1] != _dimension: return []
355
-
356
- distances, indices = _faiss_rules_index.search(query_embedding_np, min(k, _faiss_rules_index.ntotal))
357
- results = [_rules_items_list[i] for i in indices[0] if 0 <= i < len(_rules_items_list)]
358
- logger.debug(f"Retrieved {len(results)} rules semantically for query: '{query[:50]}...'")
359
- return results
360
- except Exception as e:
361
- logger.error(f"Error retrieving rules semantically: {e}", exc_info=True)
362
- return []
363
-
364
- def remove_rule_entry(rule_text_to_delete: str) -> bool:
365
- """Removes a rule from backend and rebuilds FAISS for rules."""
366
- global _rules_items_list, _faiss_rules_index
367
- if not _initialized: initialize_memory_system()
368
- if not _embedder or not _faiss_rules_index: return False
369
-
370
- rule_text_to_delete = rule_text_to_delete.strip()
371
- if rule_text_to_delete not in _rules_items_list:
372
- return False # Not found
373
-
374
- try:
375
- _rules_items_list.remove(rule_text_to_delete)
376
- _rules_items_list.sort() # Maintain sorted order
377
-
378
- # Rebuild FAISS index for rules (simplest way to ensure consistency after removal)
379
- new_faiss_rules_index = faiss.IndexFlatL2(_dimension)
380
- if _rules_items_list:
381
- embeddings = _embedder.encode(_rules_items_list, convert_to_tensor=False)
382
- embeddings_np = np.array(embeddings, dtype=np.float32)
383
- if embeddings_np.ndim == 2 and embeddings_np.shape[0] == len(_rules_items_list) and embeddings_np.shape[1] == _dimension:
384
- new_faiss_rules_index.add(embeddings_np)
385
- else: # Should not happen if list is consistent
386
- logger.error("Error rebuilding FAISS for rules after removal: Embedding shape error. State might be inconsistent.")
387
- # Attempt to revert _rules_items_list (add back the rule)
388
- _rules_items_list.append(rule_text_to_delete)
389
- _rules_items_list.sort()
390
- return False # Indicate failure
391
- _faiss_rules_index = new_faiss_rules_index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
 
393
- # Remove from persistent storage
394
- if STORAGE_BACKEND == "SQLITE" and sqlite3:
395
- with _get_sqlite_connection() as conn:
396
- conn.execute("DELETE FROM rules WHERE rule_text = ?", (rule_text_to_delete,))
397
- conn.commit()
398
- elif STORAGE_BACKEND == "HF_DATASET" and HF_TOKEN and Dataset:
399
- Dataset.from_dict({"rule_text": list(_rules_items_list)}).push_to_hub(HF_RULES_DATASET_REPO, token=HF_TOKEN, private=True)
 
400
 
401
- logger.info(f"Removed rule. RAM: {len(_rules_items_list)}, FAISS: {_faiss_rules_index.ntotal}")
402
- return True
403
- except Exception as e:
404
- logger.error(f"Error removing rule entry: {e}", exc_info=True)
405
- # Potential partial failure, state might be inconsistent.
406
- return False
407
-
408
- # --- Utility functions to get all data (for UI display, etc.) ---
409
- def get_all_rules_cached() -> list[str]:
410
- if not _initialized: initialize_memory_system()
411
- return list(_rules_items_list)
412
-
413
- def get_all_memories_cached() -> list[dict]:
414
- if not _initialized: initialize_memory_system()
415
- # Convert JSON strings to dicts for easier use by UI
416
- mem_dicts = []
417
- for mem_json_str in _memory_items_list:
418
- try: mem_dicts.append(json.loads(mem_json_str))
419
- except: pass # Ignore parse errors for display
420
- return mem_dicts
421
-
422
- def clear_all_memory_data_backend() -> bool:
423
- """Clears all memories from backend and resets in-memory FAISS/list."""
424
- global _memory_items_list, _faiss_memory_index
425
- if not _initialized: initialize_memory_system()
426
-
427
- success = True
428
- try:
429
- if STORAGE_BACKEND == "SQLITE" and sqlite3:
430
- with _get_sqlite_connection() as conn: conn.execute("DELETE FROM memories"); conn.commit()
431
- elif STORAGE_BACKEND == "HF_DATASET" and HF_TOKEN and Dataset:
432
- # Deleting from HF usually means pushing an empty dataset
433
- Dataset.from_dict({"memory_json": []}).push_to_hub(HF_MEMORY_DATASET_REPO, token=HF_TOKEN, private=True)
434
 
435
- _memory_items_list = []
436
- if _faiss_memory_index: _faiss_memory_index.reset() # Clear FAISS index
437
- logger.info("All memories cleared from backend and in-memory stores.")
438
- except Exception as e:
439
- logger.error(f"Error clearing all memory data: {e}")
440
- success = False
441
- return success
442
-
443
- def clear_all_rules_data_backend() -> bool:
444
- """Clears all rules from backend and resets in-memory FAISS/list."""
445
- global _rules_items_list, _faiss_rules_index
446
- if not _initialized: initialize_memory_system()
447
-
448
- success = True
449
- try:
450
- if STORAGE_BACKEND == "SQLITE" and sqlite3:
451
- with _get_sqlite_connection() as conn: conn.execute("DELETE FROM rules"); conn.commit()
452
- elif STORAGE_BACKEND == "HF_DATASET" and HF_TOKEN and Dataset:
453
- Dataset.from_dict({"rule_text": []}).push_to_hub(HF_RULES_DATASET_REPO, token=HF_TOKEN, private=True)
454
-
455
- _rules_items_list = []
456
- if _faiss_rules_index: _faiss_rules_index.reset()
457
- logger.info("All rules cleared from backend and in-memory stores.")
458
- except Exception as e:
459
- logger.error(f"Error clearing all rules data: {e}")
460
- success = False
461
- return success
462
-
463
- # Optional: Function to save FAISS indices to disk (from ai-learn, if needed for persistence between app runs with RAM backend)
464
- FAISS_MEMORY_PATH = os.path.join(os.getenv("FAISS_STORAGE_PATH", "app_data/faiss_indices"), "memory_index.faiss")
465
- FAISS_RULES_PATH = os.path.join(os.getenv("FAISS_STORAGE_PATH", "app_data/faiss_indices"), "rules_index.faiss")
466
-
467
- def save_faiss_indices_to_disk():
468
- if not _initialized or not faiss: return
469
-
470
- faiss_dir = os.path.dirname(FAISS_MEMORY_PATH)
471
- if not os.path.exists(faiss_dir): os.makedirs(faiss_dir, exist_ok=True)
472
 
473
- if _faiss_memory_index and _faiss_memory_index.ntotal > 0:
474
- try:
475
- faiss.write_index(_faiss_memory_index, FAISS_MEMORY_PATH)
476
- logger.info(f"Memory FAISS index saved to disk ({_faiss_memory_index.ntotal} items).")
477
- except Exception as e: logger.error(f"Error saving memory FAISS index: {e}")
478
-
479
- if _faiss_rules_index and _faiss_rules_index.ntotal > 0:
 
 
 
480
  try:
481
- faiss.write_index(_faiss_rules_index, FAISS_RULES_PATH)
482
- logger.info(f"Rules FAISS index saved to disk ({_faiss_rules_index.ntotal} items).")
483
- except Exception as e: logger.error(f"Error saving rules FAISS index: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484
 
485
- def load_faiss_indices_from_disk():
486
- global _faiss_memory_index, _faiss_rules_index
487
- if not _initialized or not faiss: return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
 
489
- if os.path.exists(FAISS_MEMORY_PATH) and _faiss_memory_index: # Check if index object exists
490
- try:
491
- logger.info(f"Loading memory FAISS index from {FAISS_MEMORY_PATH}...")
492
- _faiss_memory_index = faiss.read_index(FAISS_MEMORY_PATH)
493
- logger.info(f"Memory FAISS index loaded ({_faiss_memory_index.ntotal} items).")
494
- # Consistency check: FAISS ntotal vs len(_memory_items_list)
495
- if _faiss_memory_index.ntotal != len(_memory_items_list) and len(_memory_items_list) > 0:
496
- logger.warning(f"Memory FAISS index count ({_faiss_memory_index.ntotal}) differs from loaded texts ({len(_memory_items_list)}). Consider rebuilding FAISS.")
497
- except Exception as e: logger.error(f"Error loading memory FAISS index: {e}. Will use fresh index.")
498
-
499
- if os.path.exists(FAISS_RULES_PATH) and _faiss_rules_index:
500
  try:
501
- logger.info(f"Loading rules FAISS index from {FAISS_RULES_PATH}...")
502
- _faiss_rules_index = faiss.read_index(FAISS_RULES_PATH)
503
- logger.info(f"Rules FAISS index loaded ({_faiss_rules_index.ntotal} items).")
504
- if _faiss_rules_index.ntotal != len(_rules_items_list) and len(_rules_items_list) > 0:
505
- logger.warning(f"Rules FAISS index count ({_faiss_rules_index.ntotal}) differs from loaded texts ({len(_rules_items_list)}). Consider rebuilding FAISS.")
506
- except Exception as e: logger.error(f"Error loading rules FAISS index: {e}. Will use fresh index.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # model_logic.py
2
  import os
3
+ import requests
4
  import json
 
 
5
  import logging
6
+ from dotenv import load_dotenv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Load environment variables from .env file
9
+ load_dotenv()
10
 
11
+ logging.basicConfig(
12
+ level=logging.INFO,
13
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
14
+ )
15
  logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ # Maps provider name (uppercase) to environment variable name for API key
18
+ API_KEYS_ENV_VARS = {
19
+ "HUGGINGFACE": 'HF_TOKEN', # Note: HF_TOKEN is often used for general HF auth
20
+ "GROQ": 'GROQ_API_KEY',
21
+ "OPENROUTER": 'OPENROUTER_API_KEY',
22
+ "TOGETHERAI": 'TOGETHERAI_API_KEY',
23
+ "COHERE": 'COHERE_API_KEY',
24
+ "XAI": 'XAI_API_KEY',
25
+ "OPENAI": 'OPENAI_API_KEY',
26
+ "GOOGLE": 'GOOGLE_API_KEY', # Or GOOGLE_GEMINI_API_KEY etc.
27
+ }
28
+
29
+ API_URLS = {
30
+ "HUGGINGFACE": 'https://api-inference.huggingface.co/models/',
31
+ "GROQ": 'https://api.groq.com/openai/v1/chat/completions',
32
+ "OPENROUTER": 'https://openrouter.ai/api/v1/chat/completions',
33
+ "TOGETHERAI": 'https://api.together.ai/v1/chat/completions',
34
+ "COHERE": 'https://api.cohere.ai/v1/chat', # v1 is common for chat, was v2 in ai-learn
35
+ "XAI": 'https://api.x.ai/v1/chat/completions',
36
+ "OPENAI": 'https://api.openai.com/v1/chat/completions',
37
+ "GOOGLE": 'https://generativelanguage.googleapis.com/v1beta/models/',
38
+ }
39
+
40
+ # MODELS_BY_PROVIDER = json.load(open("./models.json")) ## commented for demo
41
+ MODELS_BY_PROVIDER = {
42
+ "groq": {
43
+ "default": "llama3-8b-8192",
44
+ "models": {
45
+ "Llama 3 8B (Groq)": "llama3-8b-8192",
46
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  }
48
+ }
49
+
50
+ def _get_api_key(provider: str, ui_api_key_override: str = None) -> str | None:
51
+ """
52
+ Retrieves API key for a given provider.
53
+ Priority: UI Override > Environment Variable from API_KEYS_ENV_VARS > Specific (e.g. HF_TOKEN for HuggingFace).
54
+ """
55
+ provider_upper = provider.upper()
56
+ if ui_api_key_override and ui_api_key_override.strip():
57
+ logger.debug(f"Using UI-provided API key for {provider_upper}.")
58
+ return ui_api_key_override.strip()
59
+
60
+ env_var_name = API_KEYS_ENV_VARS.get(provider_upper)
61
+ if env_var_name:
62
+ env_key = os.getenv(env_var_name)
63
+ if env_key and env_key.strip():
64
+ logger.debug(f"Using API key from env var '{env_var_name}' for {provider_upper}.")
65
+ return env_key.strip()
66
+
67
+ # Specific fallback for HuggingFace if HF_TOKEN is set and API_KEYS_ENV_VARS['HUGGINGFACE'] wasn't specific enough
68
+ if provider_upper == 'HUGGINGFACE':
69
+ hf_token_fallback = os.getenv("HF_TOKEN")
70
+ if hf_token_fallback and hf_token_fallback.strip():
71
+ logger.debug("Using HF_TOKEN as fallback for HuggingFace provider.")
72
+ return hf_token_fallback.strip()
73
+
74
+ logger.warning(f"API Key not found for provider '{provider_upper}'. Checked UI override and environment variable '{env_var_name or 'N/A'}'.")
75
+ return None
76
+
77
+ def get_available_providers() -> list[str]:
78
+ """Returns a sorted list of available provider names (e.g., 'groq', 'openai')."""
79
+ return sorted(list(MODELS_BY_PROVIDER.keys()))
80
+
81
+ def get_model_display_names_for_provider(provider: str) -> list[str]:
82
+ """Returns a sorted list of model display names for a given provider."""
83
+ return sorted(list(MODELS_BY_PROVIDER.get(provider.lower(), {}).get("models", {}).keys()))
84
+
85
+ def get_default_model_display_name_for_provider(provider: str) -> str | None:
86
+ """Gets the default model's display name for a provider."""
87
+ provider_data = MODELS_BY_PROVIDER.get(provider.lower(), {})
88
+ models_dict = provider_data.get("models", {})
89
+ default_model_id = provider_data.get("default")
90
+
91
+ if default_model_id and models_dict:
92
+ for display_name, model_id_val in models_dict.items():
93
+ if model_id_val == default_model_id:
94
+ return display_name
95
 
96
+ # Fallback to the first model in the sorted list if default not found or not set
97
+ if models_dict:
98
+ sorted_display_names = sorted(list(models_dict.keys()))
99
+ if sorted_display_names:
100
+ return sorted_display_names[0]
101
+ return None
102
+
103
+ def get_model_id_from_display_name(provider: str, display_name: str) -> str | None:
104
+ """Gets the actual model ID from its display name for a given provider."""
105
+ models = MODELS_BY_PROVIDER.get(provider.lower(), {}).get("models", {})
106
+ return models.get(display_name)
107
+
108
+
109
+ def call_model_stream(provider: str, model_display_name: str, messages: list[dict], api_key_override: str = None, temperature: float = 0.7, max_tokens: int = None) -> iter:
110
+ """
111
+ Calls the specified model via its provider and streams the response.
112
+ Handles provider-specific request formatting and error handling.
113
+ Yields chunks of the response text or an error string.
114
+ """
115
+ provider_lower = provider.lower()
116
+ api_key = _get_api_key(provider_lower, api_key_override)
117
+ base_url = API_URLS.get(provider.upper())
118
+ model_id = get_model_id_from_display_name(provider_lower, model_display_name)
119
+
120
+ if not api_key:
121
+ env_var_name = API_KEYS_ENV_VARS.get(provider.upper(), 'N/A')
122
+ yield f"Error: API Key not found for {provider}. Please set it in the UI or env var '{env_var_name}'."
123
+ return
124
+ if not base_url:
125
+ yield f"Error: Unknown provider '{provider}' or missing API URL configuration."
126
+ return
127
+ if not model_id:
128
+ yield f"Error: Model ID not found for '{model_display_name}' under provider '{provider}'. Check configuration."
129
+ return
130
+
131
+ headers = {}
132
+ payload = {}
133
+ request_url = base_url
134
+
135
+ logger.info(f"Streaming from {provider}/{model_display_name} (ID: {model_id})...")
136
 
137
+ # --- Standard OpenAI-compatible providers ---
138
+ if provider_lower in ["groq", "openrouter", "togetherai", "openai", "xai"]:
139
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
140
+ payload = {"model": model_id, "messages": messages, "stream": True, "temperature": temperature}
141
+ if max_tokens: payload["max_tokens"] = max_tokens
142
 
143
+ if provider_lower == "openrouter":
144
+ headers["HTTP-Referer"] = os.getenv("OPENROUTER_REFERRER") or "http://localhost/gradio" # Example Referer
145
+ headers["X-Title"] = os.getenv("OPENROUTER_X_TITLE") or "Gradio AI Researcher" # Example Title
146
 
147
+ try:
148
+ response = requests.post(request_url, headers=headers, json=payload, stream=True, timeout=180)
149
+ response.raise_for_status()
150
+
151
+ # More robust SSE parsing
152
+ buffer = ""
153
+ for chunk in response.iter_content(chunk_size=None): # Process raw bytes
154
+ buffer += chunk.decode('utf-8', errors='replace')
155
+ while '\n\n' in buffer:
156
+ event_str, buffer = buffer.split('\n\n', 1)
157
+ if not event_str.strip(): continue
158
+
159
+ content_chunk = ""
160
+ for line in event_str.splitlines():
161
+ if line.startswith('data: '):
162
+ data_json = line[len('data: '):].strip()
163
+ if data_json == '[DONE]':
164
+ return # Stream finished
165
+ try:
166
+ data = json.loads(data_json)
167
+ if data.get("choices") and len(data["choices"]) > 0:
168
+ delta = data["choices"][0].get("delta", {})
169
+ if delta and delta.get("content"):
170
+ content_chunk += delta["content"]
171
+ except json.JSONDecodeError:
172
+ logger.warning(f"Failed to decode JSON from stream line: {data_json}")
173
+ if content_chunk:
174
+ yield content_chunk
175
+ # Process any remaining buffer content (less common with '\n\n' delimiter)
176
+ if buffer.strip():
177
+ logger.debug(f"Remaining buffer after OpenAI-like stream: {buffer}")
178
+
179
+
180
+ except requests.exceptions.HTTPError as e:
181
+ err_msg = f"API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
182
+ logger.error(f"{err_msg} for {provider}/{model_id}", exc_info=False)
183
+ yield f"Error: {err_msg}"
184
+ except requests.exceptions.RequestException as e:
185
+ logger.error(f"API Request Error for {provider}/{model_id}: {e}", exc_info=False)
186
+ yield f"Error: Could not connect to {provider} ({e})"
187
+ except Exception as e:
188
+ logger.exception(f"Unexpected error during {provider} stream:")
189
+ yield f"Error: An unexpected error occurred: {e}"
190
+ return
191
+
192
+ # --- Google Gemini ---
193
+ elif provider_lower == "google":
194
+ system_instruction = None
195
+ filtered_messages = []
196
+ for msg in messages:
197
+ if msg["role"] == "system": system_instruction = {"parts": [{"text": msg["content"]}]}
198
  else:
199
+ role = "model" if msg["role"] == "assistant" else msg["role"]
200
+ filtered_messages.append({"role": role, "parts": [{"text": msg["content"]}]})
201
+
202
+ payload = {
203
+ "contents": filtered_messages,
204
+ "safetySettings": [ # Example: more permissive settings
205
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
206
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
207
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
208
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
209
+ ],
210
+ "generationConfig": {"temperature": temperature}
211
+ }
212
+ if max_tokens: payload["generationConfig"]["maxOutputTokens"] = max_tokens
213
+ if system_instruction: payload["system_instruction"] = system_instruction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
+ request_url = f"{base_url}{model_id}:streamGenerateContent?key={api_key}" # API key in query param
216
+ headers = {"Content-Type": "application/json"}
217
+
218
+ try:
219
+ response = requests.post(request_url, headers=headers, json=payload, stream=True, timeout=180)
220
+ response.raise_for_status()
221
+
222
+ # Google's stream is a bit different, often newline-delimited JSON arrays/objects
223
+ buffer = ""
224
+ for chunk in response.iter_content(chunk_size=None):
225
+ buffer += chunk.decode('utf-8', errors='replace')
226
+ # Google might send chunks that are not complete JSON objects, or multiple objects
227
+ # A common pattern is [ {obj1} , {obj2} ] where chunks split mid-array or mid-object.
228
+ # This parsing needs to be robust. A simple split by '\n' might not always work if JSON is pretty-printed.
229
+ # The previous code's `json.loads(f"[{decoded_line}]")` was an attempt to handle this.
230
+ # For now, let's assume newline delimited for simplicity, but this is a known tricky part.
231
+
232
+ while '\n' in buffer:
233
+ line, buffer = buffer.split('\n', 1)
234
+ line = line.strip()
235
+ if not line: continue
236
+ if line.startswith(','): line = line[1:] # Handle leading commas if splitting an array
237
+
238
+ try:
239
+ # Remove "data: " prefix if present (less common for Gemini direct API but good practice)
240
+ if line.startswith('data: '): line = line[len('data: '):]
241
+
242
+ # Gemini often streams an array of objects, or just one object.
243
+ # Try to parse as a single object first. If fails, try as array.
244
+ parsed_data = None
245
+ try:
246
+ parsed_data = json.loads(line)
247
+ except json.JSONDecodeError:
248
+ # If it's part of an array, it might be missing brackets.
249
+ # This heuristic is fragile. A proper SSE parser or stateful JSON parser is better.
250
+ if line.startswith('{') and line.endswith('}'): # Looks like a complete object
251
+ pass # already tried json.loads
252
+ # Try to wrap with [] if it seems like a list content without brackets
253
+ elif line.startswith('{') or line.endswith('}'):
254
+ try:
255
+ temp_parsed_list = json.loads(f"[{line}]")
256
+ if temp_parsed_list and isinstance(temp_parsed_list, list):
257
+ parsed_data = temp_parsed_list[0] # take first if it becomes a list
258
+ except json.JSONDecodeError:
259
+ logger.warning(f"Google: Still can't parse line even with array wrap: {line}")
260
+
261
+ if parsed_data:
262
+ data_to_process = [parsed_data] if isinstance(parsed_data, dict) else parsed_data # Ensure list
263
+ for event_data in data_to_process:
264
+ if not isinstance(event_data, dict): continue
265
+ if event_data.get("candidates"):
266
+ for candidate in event_data["candidates"]:
267
+ if candidate.get("content", {}).get("parts"):
268
+ for part in candidate["content"]["parts"]:
269
+ if part.get("text"):
270
+ yield part["text"]
271
+ except json.JSONDecodeError:
272
+ logger.warning(f"Google: JSONDecodeError for line: {line}")
273
+ except Exception as e_google_proc:
274
+ logger.error(f"Google: Error processing stream data: {e_google_proc}, Line: {line}")
275
+
276
+ except requests.exceptions.HTTPError as e:
277
+ err_msg = f"Google API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
278
+ logger.error(err_msg, exc_info=False)
279
+ yield f"Error: {err_msg}"
280
+ except Exception as e:
281
+ logger.exception(f"Unexpected error during Google stream:")
282
+ yield f"Error: An unexpected error occurred with Google API: {e}"
283
+ return
284
+
285
+ # --- Cohere ---
286
+ elif provider_lower == "cohere":
287
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "Accept": "application/json"}
288
 
289
+ # Cohere message format
290
+ chat_history_cohere = []
291
+ preamble_cohere = None
292
+ user_message_cohere = ""
293
+
294
+ temp_messages = list(messages) # Work with a copy
295
+ if temp_messages and temp_messages[0]["role"] == "system":
296
+ preamble_cohere = temp_messages.pop(0)["content"]
297
 
298
+ if temp_messages:
299
+ user_message_cohere = temp_messages.pop()["content"] # Last message is the current user query
300
+ for msg in temp_messages: # Remaining are history
301
+ role = "USER" if msg["role"] == "user" else "CHATBOT"
302
+ chat_history_cohere.append({"role": role, "message": msg["content"]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
 
304
+ if not user_message_cohere:
305
+ yield "Error: User message is empty for Cohere."
306
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
 
308
+ payload = {
309
+ "model": model_id,
310
+ "message": user_message_cohere,
311
+ "stream": True,
312
+ "temperature": temperature
313
+ }
314
+ if max_tokens: payload["max_tokens"] = max_tokens # Cohere uses max_tokens
315
+ if chat_history_cohere: payload["chat_history"] = chat_history_cohere
316
+ if preamble_cohere: payload["preamble"] = preamble_cohere
317
+
318
  try:
319
+ response = requests.post(base_url, headers=headers, json=payload, stream=True, timeout=180)
320
+ response.raise_for_status()
321
+
322
+ # Cohere SSE format is event: type\ndata: {json}\n\n
323
+ buffer = ""
324
+ for chunk_bytes in response.iter_content(chunk_size=None):
325
+ buffer += chunk_bytes.decode('utf-8', errors='replace')
326
+ while '\n\n' in buffer:
327
+ event_str, buffer = buffer.split('\n\n', 1)
328
+ if not event_str.strip(): continue
329
+
330
+ event_type = None
331
+ data_json_str = None
332
+ for line in event_str.splitlines():
333
+ if line.startswith("event:"): event_type = line[len("event:"):].strip()
334
+ elif line.startswith("data:"): data_json_str = line[len("data:"):].strip()
335
+
336
+ if data_json_str:
337
+ try:
338
+ data = json.loads(data_json_str)
339
+ if event_type == "text-generation" and "text" in data:
340
+ yield data["text"]
341
+ elif event_type == "stream-end":
342
+ logger.debug(f"Cohere stream ended. Finish reason: {data.get('finish_reason')}")
343
+ return
344
+ except json.JSONDecodeError:
345
+ logger.warning(f"Cohere: Failed to decode JSON: {data_json_str}")
346
+ if buffer.strip():
347
+ logger.debug(f"Cohere: Remaining buffer: {buffer.strip()}")
348
+
349
+
350
+ except requests.exceptions.HTTPError as e:
351
+ err_msg = f"Cohere API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
352
+ logger.error(err_msg, exc_info=False)
353
+ yield f"Error: {err_msg}"
354
+ except Exception as e:
355
+ logger.exception(f"Unexpected error during Cohere stream:")
356
+ yield f"Error: An unexpected error occurred with Cohere API: {e}"
357
+ return
358
 
359
+ # --- HuggingFace Inference API (Basic TGI support) ---
360
+ # This is very basic and might not work for all models or complex scenarios.
361
+ # Assumes model is deployed with Text Generation Inference (TGI) and supports streaming.
362
+ elif provider_lower == "huggingface":
363
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
364
+ # Construct prompt string for TGI (often needs specific formatting)
365
+ # This is a generic attempt, specific models might need <|user|>, <|assistant|> etc.
366
+ prompt_parts = []
367
+ for msg in messages:
368
+ role_prefix = ""
369
+ if msg['role'] == 'system': role_prefix = "System: " # Or might be ignored/handled differently
370
+ elif msg['role'] == 'user': role_prefix = "User: "
371
+ elif msg['role'] == 'assistant': role_prefix = "Assistant: "
372
+ prompt_parts.append(f"{role_prefix}{msg['content']}")
373
+
374
+ # TGI typically expects a final "Assistant: " to start generating from
375
+ tgi_prompt = "\n".join(prompt_parts) + "\nAssistant: "
376
+
377
+ payload = {
378
+ "inputs": tgi_prompt,
379
+ "parameters": {
380
+ "temperature": temperature if temperature > 0 else 0.01, # TGI needs temp > 0 for sampling
381
+ "max_new_tokens": max_tokens or 1024, # Default TGI max_new_tokens
382
+ "return_full_text": False, # We only want generated part
383
+ "do_sample": True if temperature > 0 else False,
384
+ },
385
+ "stream": True
386
+ }
387
+ request_url = f"{base_url}{model_id}" # Model ID is part of URL path for HF
388
 
 
 
 
 
 
 
 
 
 
 
 
389
  try:
390
+ response = requests.post(request_url, headers=headers, json=payload, stream=True, timeout=180)
391
+ response.raise_for_status()
392
+
393
+ # TGI SSE stream: data: {"token": {"id": ..., "text": "...", "logprob": ..., "special": ...}}
394
+ # Or sometimes just data: "text_chunk" for simpler models/configs
395
+ buffer = ""
396
+ for chunk_bytes in response.iter_content(chunk_size=None):
397
+ buffer += chunk_bytes.decode('utf-8', errors='replace')
398
+ while '\n' in buffer: # TGI often uses single newline
399
+ line, buffer = buffer.split('\n', 1)
400
+ line = line.strip()
401
+ if not line: continue
402
+
403
+ if line.startswith('data:'):
404
+ data_json_str = line[len('data:'):].strip()
405
+ try:
406
+ data = json.loads(data_json_str)
407
+ if "token" in data and "text" in data["token"]:
408
+ yield data["token"]["text"]
409
+ elif "generated_text" in data and data.get("details") is None: # Sometimes a final non-streaming like object might appear
410
+ # This case is tricky, if it's the *only* thing then it's not really streaming
411
+ pass # For now, ignore if it's not a token object
412
+ # Some TGI might send raw text if not fully SSE compliant for stream
413
+ # elif isinstance(data, str): yield data
414
+
415
+ except json.JSONDecodeError:
416
+ # If it's not JSON, it might be a raw string (less common for TGI stream=True)
417
+ # For safety, only yield if it's a clear text string
418
+ if not data_json_str.startswith('{') and not data_json_str.startswith('['):
419
+ yield data_json_str
420
+ else:
421
+ logger.warning(f"HF: Failed to decode JSON and not raw string: {data_json_str}")
422
+ if buffer.strip():
423
+ logger.debug(f"HF: Remaining buffer: {buffer.strip()}")
424
+
425
+
426
+ except requests.exceptions.HTTPError as e:
427
+ err_msg = f"HF API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
428
+ logger.error(err_msg, exc_info=False)
429
+ yield f"Error: {err_msg}"
430
+ except Exception as e:
431
+ logger.exception(f"Unexpected error during HF stream:")
432
+ yield f"Error: An unexpected error occurred with HF API: {e}"
433
+ return
434
+
435
+ else:
436
+ yield f"Error: Provider '{provider}' is not configured for streaming in this handler."
437
+ return