Spaces:
Sleeping
Sleeping
Update model_logic.py
Browse files- model_logic.py +415 -484
model_logic.py
CHANGED
@@ -1,506 +1,437 @@
|
|
1 |
-
#
|
2 |
import os
|
|
|
3 |
import json
|
4 |
-
import time
|
5 |
-
from datetime import datetime
|
6 |
import logging
|
7 |
-
import
|
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 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
|
233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
|
235 |
-
|
236 |
-
|
237 |
-
|
|
|
|
|
238 |
|
239 |
-
if
|
240 |
-
|
241 |
-
|
242 |
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
logger.error(f"
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
|
|
|
|
|
|
|
|
290 |
else:
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
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 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
392 |
|
393 |
-
#
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
|
|
400 |
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
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 |
-
|
436 |
-
|
437 |
-
|
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 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
|
|
|
|
|
|
480 |
try:
|
481 |
-
|
482 |
-
|
483 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
484 |
|
485 |
-
|
486 |
-
|
487 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|