Spaces:
Sleeping
Sleeping
Commit ·
195c86d
1
Parent(s): 6c97eaf
refactor: Modularize app structure (app_module.py + thin entry points)
Browse files- app.py +3 -552
- app_local.py +9 -552
- app_module.py +553 -0
- tests/rag_reproduce_test.py +1 -1
- tests/suite_test.py +1 -1
- tests/test_accumulation_bug.py +5 -5
- tests/test_agent.py +1 -1
- tests/test_agent_tools.py +2 -2
- tests/test_final_suite.py +14 -14
- tests/test_full_coverage.py +23 -23
- tests/test_name_extraction.py +11 -11
- tests/test_regression_v6_5.py +4 -4
- tests/test_ui_logic.py +5 -5
app.py
CHANGED
|
@@ -1,554 +1,5 @@
|
|
| 1 |
-
import
|
| 2 |
-
import torch
|
| 3 |
-
import gradio as gr
|
| 4 |
-
import time
|
| 5 |
-
import re
|
| 6 |
-
import codecs
|
| 7 |
-
import uuid
|
| 8 |
-
import json
|
| 9 |
-
import logging
|
| 10 |
-
import tempfile
|
| 11 |
-
import numpy as np
|
| 12 |
-
import scipy.io.wavfile as wavfile
|
| 13 |
-
import asyncio
|
| 14 |
-
import warnings
|
| 15 |
-
from typing import List, Tuple, Generator, Dict
|
| 16 |
-
from threading import Thread
|
| 17 |
-
|
| 18 |
-
# ML / Transformers
|
| 19 |
-
import transformers
|
| 20 |
-
transformers.utils.logging.set_verbosity_error()
|
| 21 |
-
warnings.filterwarnings("ignore", category=UserWarning, module="gradio.components.dropdown")
|
| 22 |
-
from transformers import AutoProcessor, Gemma3ForConditionalGeneration, TextIteratorStreamer
|
| 23 |
-
|
| 24 |
-
# --- Logging Setup ---
|
| 25 |
-
# Set root logger to ERROR to suppress external library noise
|
| 26 |
-
logging.basicConfig(level=logging.ERROR, format='%(name)s [%(levelname)s] %(message)s')
|
| 27 |
-
|
| 28 |
-
# Specific library suppressions
|
| 29 |
-
for lib in ["transformers", "accelerate", "httpx", "gradio", "langchain"]:
|
| 30 |
-
logging.getLogger(lib).setLevel(logging.ERROR)
|
| 31 |
-
|
| 32 |
-
# Application-level logger
|
| 33 |
-
logger = logging.getLogger("app")
|
| 34 |
-
logger.setLevel(logging.DEBUG)
|
| 35 |
-
logger.propagate = False # DO NOT propagate to root to avoid double-logging or filtering
|
| 36 |
-
ch = logging.StreamHandler()
|
| 37 |
-
ch.setLevel(logging.DEBUG)
|
| 38 |
-
ch.setFormatter(logging.Formatter('[app] [%(levelname)s] %(message)s'))
|
| 39 |
-
logger.addHandler(ch)
|
| 40 |
-
|
| 41 |
-
# --------------------------------------------------------------------
|
| 42 |
-
# Konfiguration & Globale States
|
| 43 |
-
# --------------------------------------------------------------------
|
| 44 |
-
EMBED_MODEL_ID = "google/embeddinggemma-300m"
|
| 45 |
-
LLM_MODEL_ID = "google/gemma-3-4b-it"
|
| 46 |
-
|
| 47 |
-
EMBEDDING_FUNCTION = None
|
| 48 |
-
LLM_MODEL = None
|
| 49 |
-
LLM_PROCESSOR = None
|
| 50 |
-
|
| 51 |
-
# --- UI Premium Aesthetics ---
|
| 52 |
-
PREMIUM_CSS = """
|
| 53 |
-
.glass-panel {
|
| 54 |
-
background: rgba(255, 255, 255, 0.05) !important;
|
| 55 |
-
backdrop-filter: blur(10px) !important;
|
| 56 |
-
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 57 |
-
border-radius: 15px !important;
|
| 58 |
-
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37) !important;
|
| 59 |
-
}
|
| 60 |
-
.sidebar-panel {
|
| 61 |
-
border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 62 |
-
height: 100vh;
|
| 63 |
-
}
|
| 64 |
-
border-bottom: 2px solid #0f3460;
|
| 65 |
-
}
|
| 66 |
-
.desktop-only { display: block; }
|
| 67 |
-
.mobile-only { display: none; }
|
| 68 |
-
@media (max-width: 768px) {
|
| 69 |
-
.desktop-only { display: none !important; }
|
| 70 |
-
.mobile-only { display: block !important; }
|
| 71 |
-
.sidebar-panel { display: none !important; }
|
| 72 |
-
}
|
| 73 |
-
"""
|
| 74 |
-
|
| 75 |
-
try:
|
| 76 |
-
from pypdf import PdfReader
|
| 77 |
-
from langchain_community.vectorstores import FAISS
|
| 78 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
| 79 |
-
from langchain_core.documents import Document
|
| 80 |
-
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 81 |
-
from mongochain import MongoDBHandler
|
| 82 |
-
except ImportError:
|
| 83 |
-
pass
|
| 84 |
-
|
| 85 |
-
# Spiritual Integration
|
| 86 |
-
try:
|
| 87 |
-
from spiritual_bridge import get_oracle_data
|
| 88 |
-
except ImportError:
|
| 89 |
-
get_oracle_data = None
|
| 90 |
-
|
| 91 |
-
# --- Model Loading ---
|
| 92 |
-
def get_device() -> torch.device:
|
| 93 |
-
if torch.cuda.is_available(): return torch.device("cuda")
|
| 94 |
-
return torch.device("cpu")
|
| 95 |
-
|
| 96 |
-
def get_embedding_function():
|
| 97 |
-
global EMBEDDING_FUNCTION
|
| 98 |
-
if EMBEDDING_FUNCTION is None:
|
| 99 |
-
device = get_device()
|
| 100 |
-
logger.debug(f"Initialisiere Embedding-Modell '{EMBED_MODEL_ID}' auf Device '{device}'.")
|
| 101 |
-
EMBEDDING_FUNCTION = HuggingFaceEmbeddings(
|
| 102 |
-
model_name=EMBED_MODEL_ID,
|
| 103 |
-
model_kwargs={'device': device}
|
| 104 |
-
)
|
| 105 |
-
logger.debug("Embedding-Modell erfolgreich initialisiert.")
|
| 106 |
-
return EMBEDDING_FUNCTION
|
| 107 |
-
|
| 108 |
-
def get_llm():
|
| 109 |
-
global LLM_MODEL, LLM_PROCESSOR
|
| 110 |
-
if LLM_MODEL is None or LLM_PROCESSOR is None:
|
| 111 |
-
device = get_device()
|
| 112 |
-
logger.debug(f"Initialisiere LLM '{LLM_MODEL_ID}' auf Device '{device}'.")
|
| 113 |
-
dtype = torch.bfloat16 if "cuda" in device.type else torch.float32
|
| 114 |
-
LLM_MODEL = Gemma3ForConditionalGeneration.from_pretrained(
|
| 115 |
-
LLM_MODEL_ID,
|
| 116 |
-
dtype=dtype,
|
| 117 |
-
device_map="auto",
|
| 118 |
-
).eval()
|
| 119 |
-
LLM_PROCESSOR = AutoProcessor.from_pretrained(LLM_MODEL_ID)
|
| 120 |
-
logger.debug("LLM und Prozessor erfolgreich initialisiert.")
|
| 121 |
-
return LLM_MODEL, LLM_PROCESSOR
|
| 122 |
-
|
| 123 |
-
# --- Language Detection ---
|
| 124 |
-
def detect_language(text: str) -> str:
|
| 125 |
-
if not text or len(text) < 3: return "English"
|
| 126 |
-
model, processor = get_llm()
|
| 127 |
-
prompt = f"Detect the language of the following text and return ONLY the language name (e.g., 'English', 'German', 'French'):\n\n\"{text}\""
|
| 128 |
-
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 129 |
-
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
|
| 130 |
-
with torch.no_grad():
|
| 131 |
-
outputs = model.generate(inputs, max_new_tokens=20, do_sample=False)
|
| 132 |
-
raw_output = processor.batch_decode(outputs[:, inputs.shape[1]:], skip_special_tokens=True)[0].strip()
|
| 133 |
-
logger.debug(f"DEBUG: Raw Language Detection Output: '{raw_output}'")
|
| 134 |
-
|
| 135 |
-
keywords = ["English", "German", "French", "Spanish", "Italian", "Dutch", "Russian", "Chinese", "Japanese"]
|
| 136 |
-
for k in keywords:
|
| 137 |
-
if k.lower() in raw_output.lower():
|
| 138 |
-
logger.debug(f"DEBUG: Detected User Language (Normalized): '{k}'")
|
| 139 |
-
return k
|
| 140 |
-
return "English"
|
| 141 |
-
|
| 142 |
-
# --- Document Handling ---
|
| 143 |
-
def extract_text_from_file(path: str) -> str:
|
| 144 |
-
ext = os.path.splitext(path)[1].lower()
|
| 145 |
-
if ext in [".txt", ".md", ".markdown"]:
|
| 146 |
-
with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
|
| 147 |
-
if ext == ".pdf":
|
| 148 |
-
text_parts = []
|
| 149 |
-
try:
|
| 150 |
-
reader = PdfReader(path)
|
| 151 |
-
for page in reader.pages:
|
| 152 |
-
page_text = page.extract_text()
|
| 153 |
-
if page_text: text_parts.append(page_text)
|
| 154 |
-
return "\n\n".join(text_parts)
|
| 155 |
-
except Exception as e:
|
| 156 |
-
logger.error(f"Error reading PDF {path}: {e}"); return ""
|
| 157 |
-
try:
|
| 158 |
-
with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
|
| 159 |
-
except Exception: return ""
|
| 160 |
-
|
| 161 |
-
def get_text_splitter() -> RecursiveCharacterTextSplitter:
|
| 162 |
-
return RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, length_function=len)
|
| 163 |
-
|
| 164 |
-
# --- RAG Core ---
|
| 165 |
-
def index_files(file_paths, mongo_uri, db_name, coll_name, use_mongo, vs_state, mh_state, progress=gr.Progress(track_tqdm=True)):
|
| 166 |
-
if not file_paths: return "Keine Dateien zum Indexieren ausgewählt.", vs_state, mh_state
|
| 167 |
-
|
| 168 |
-
logger.debug(f"Indexierung gestartet für {len(file_paths)} Datei(en).")
|
| 169 |
-
embed_fn = get_embedding_function()
|
| 170 |
-
splitter = get_text_splitter()
|
| 171 |
-
documents = []
|
| 172 |
-
|
| 173 |
-
for path in progress.tqdm(file_paths, desc="1/2: Dateien verarbeiten"):
|
| 174 |
-
if path is None: continue
|
| 175 |
-
text = extract_text_from_file(path)
|
| 176 |
-
if not text.strip(): continue
|
| 177 |
-
chunks = splitter.split_text(text)
|
| 178 |
-
source_name = os.path.basename(path)
|
| 179 |
-
for c in chunks:
|
| 180 |
-
documents.append(Document(page_content=c, metadata={"source": source_name}))
|
| 181 |
-
|
| 182 |
-
logger.debug(f"Total chunks created: {len(documents)}")
|
| 183 |
-
if not documents: return "Kein Text zum Indexieren gefunden.", vs_state, mh_state
|
| 184 |
-
|
| 185 |
-
progress(0.7, desc="2/2: Indexing...")
|
| 186 |
-
new_vs = FAISS.from_documents(documents, embed_fn)
|
| 187 |
-
if vs_state:
|
| 188 |
-
vs_state.merge_from(new_vs)
|
| 189 |
-
else:
|
| 190 |
-
vs_state = new_vs
|
| 191 |
-
|
| 192 |
-
mh_state = None
|
| 193 |
-
if use_mongo:
|
| 194 |
-
try:
|
| 195 |
-
mh_state = MongoDBHandler(uri=mongo_uri, db_name=db_name, collection_name=coll_name)
|
| 196 |
-
mh_state.connect()
|
| 197 |
-
logger.debug(f"Pushe {len(documents)} Chunks nach MongoDB...")
|
| 198 |
-
for doc in documents:
|
| 199 |
-
mh_state.insert_chunk(doc.page_content, doc.metadata)
|
| 200 |
-
logger.debug("MongoDB-Sync abgeschlossen.")
|
| 201 |
-
except Exception as e:
|
| 202 |
-
logger.error(f"Mongo Error: {e}")
|
| 203 |
-
|
| 204 |
-
logger.debug(f"Indexierung abgeschlossen. Gesamt: {vs_state.index.ntotal} Chunks.")
|
| 205 |
-
return f"Index aktualisiert: {vs_state.index.ntotal} Chunks insgesamt.", vs_state, mh_state
|
| 206 |
-
|
| 207 |
-
def clear_index():
|
| 208 |
-
import gc; gc.collect()
|
| 209 |
-
logger.debug("Vektor-Index wurde geleert.")
|
| 210 |
-
return "Index geleert.", None, None
|
| 211 |
-
|
| 212 |
-
def retrieve_relevant_chunks(query, vs_state, mh_state, top_k=3):
|
| 213 |
-
if not vs_state: return []
|
| 214 |
-
logger.debug(f"Suche in FAISS: '{query}'")
|
| 215 |
-
docs = vs_state.similarity_search(query, k=top_k)
|
| 216 |
-
return [{"content": d.page_content, "source": d.metadata.get("source", "Unknown")} for d in docs]
|
| 217 |
-
|
| 218 |
-
def build_rag_prompt(user_question: str, retrieved_chunks: List[Dict]) -> str:
|
| 219 |
-
if not retrieved_chunks: context_str = "Kein relevanter Kontext gefunden."
|
| 220 |
-
else:
|
| 221 |
-
context_parts = [f"[{i}] (Quelle: {ch['source']}): \"{ch['content']}\"" for i, ch in enumerate(retrieved_chunks, 1)]
|
| 222 |
-
context_str = "\n\n".join(context_parts)
|
| 223 |
-
return (f"Beantworte die Benutzerfrage nur basierend auf dem Kontext.\n\n"
|
| 224 |
-
f"--- Kontext ---\n{context_str}\n\n"
|
| 225 |
-
f"--- Frage ---\n{user_question}\n\n"
|
| 226 |
-
f"--- Antwort ---")
|
| 227 |
-
|
| 228 |
-
# --- Agent System ---
|
| 229 |
-
def build_agent_prompt(query, context, history, language="English", short_answers=False):
|
| 230 |
-
context_str = "\n".join([f"- {c['content']} (Source: {c['source']})" for i, c in enumerate(context)])
|
| 231 |
-
|
| 232 |
-
style_instruction = "Be concise." if short_answers else ""
|
| 233 |
-
|
| 234 |
-
system = f"""You are Sage 6.5, a spiritual AI guide.
|
| 235 |
-
Respond in {language}. {style_instruction}
|
| 236 |
-
If you need to use a tool, you MUST use the following JSON format inside <tool_call> tags:
|
| 237 |
-
<tool_call>{{"name": "tool_name", "arguments": {{"arg1": "val1"}}}}</tool_call>
|
| 238 |
-
|
| 239 |
-
Available Tools:
|
| 240 |
-
1. oracle_consultation: Consult the archive for deep wisdom. Arguments: {{"topic": "str", "name": "str (Optional. Use ONLY if the user explicitly stated their name, otherwise omit)"}}
|
| 241 |
-
"""
|
| 242 |
-
return system + f"\n\nContext:\n{context_str}\n\nUser Question: {query}"
|
| 243 |
-
|
| 244 |
-
def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
|
| 245 |
-
model, processor = get_llm()
|
| 246 |
-
lang = user_lang if user_lang else detect_language(query)
|
| 247 |
-
context = retrieve_relevant_chunks(query, vs_state, mh_state)
|
| 248 |
-
prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
|
| 249 |
-
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 250 |
-
|
| 251 |
-
logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
|
| 252 |
-
|
| 253 |
-
def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
|
| 254 |
-
model, processor = get_llm()
|
| 255 |
-
lang = user_lang if user_lang else detect_language(query)
|
| 256 |
-
context = retrieve_relevant_chunks(query, vs_state, mh_state)
|
| 257 |
-
prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
|
| 258 |
-
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 259 |
-
|
| 260 |
-
logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
|
| 261 |
-
|
| 262 |
-
max_turns = 3
|
| 263 |
-
for turn in range(max_turns):
|
| 264 |
-
logger.info(f"[AGENT] 🔄 Turn {turn+1}/{max_turns}")
|
| 265 |
-
|
| 266 |
-
input_ids = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
|
| 267 |
-
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 268 |
-
|
| 269 |
-
gen_kwargs = {"input_ids": input_ids, "streamer": streamer, "max_new_tokens": 512, "do_sample": False}
|
| 270 |
-
thread = Thread(target=model.generate, kwargs=gen_kwargs)
|
| 271 |
-
thread.start()
|
| 272 |
-
|
| 273 |
-
current_turn_text = ""
|
| 274 |
-
# We yield a TUPLE: (accumulated_text_for_THIS_turn, is_final)
|
| 275 |
-
# But wait, the wrapper needs to handle new messages.
|
| 276 |
-
# Strategy: Yield just the text of THIS turn. Wrapper handles appending to a NEW history item each turn.
|
| 277 |
-
|
| 278 |
-
logger.info("[AGENT] ⏳ Streaming response...")
|
| 279 |
-
for new_text in streamer:
|
| 280 |
-
current_turn_text += new_text
|
| 281 |
-
clean_chunk = re.sub(r"<tool_call>.*?</tool_call>", "", current_turn_text, flags=re.DOTALL)
|
| 282 |
-
yield clean_chunk.strip()
|
| 283 |
-
|
| 284 |
-
logger.info(f"[AGENT] 🛑 Raw Model Output: {current_turn_text}")
|
| 285 |
-
|
| 286 |
-
# Tool Detection
|
| 287 |
-
tool_match = re.search(r"<tool_call>(.*?)</tool_call>", current_turn_text, re.DOTALL)
|
| 288 |
-
if tool_match:
|
| 289 |
-
# If tool found, this turn is OVER regarding user output.
|
| 290 |
-
# We yield a special signal to indicate "End of Message, Start Next Logic"?
|
| 291 |
-
# actually, if we yield, the wrapper updates history[-1].
|
| 292 |
-
# If we want a NEW message, we need to tell wrapper to append.
|
| 293 |
-
# Simplified: Use a separator? No, wrapper loop is easier.
|
| 294 |
-
|
| 295 |
-
# For now, let's keep the generator simple.
|
| 296 |
-
# It yields text updates for the CURRENT turn.
|
| 297 |
-
# Once loop breaks (tool found), we start next turn.
|
| 298 |
-
# BUT: How to tell wrapper "This turn is done, start a new bubble"?
|
| 299 |
-
# Generator yields: {"text": "...", "new_bubble": True/False}
|
| 300 |
-
|
| 301 |
-
try:
|
| 302 |
-
tool_data = json.loads(tool_match.group(1))
|
| 303 |
-
logger.info(f"[AGENT] 🛠️ Tool Call Detected: {tool_data}")
|
| 304 |
-
|
| 305 |
-
tool_name = tool_data.get("name")
|
| 306 |
-
tool_args = tool_data.get("arguments", {})
|
| 307 |
-
|
| 308 |
-
if tool_name == "oracle_consultation":
|
| 309 |
-
topic = tool_args.get("topic", "")
|
| 310 |
-
|
| 311 |
-
# Name Handling: Use provided name or default to 'Seeker'
|
| 312 |
-
req_name = tool_args.get("name", "").strip()
|
| 313 |
-
effective_name = req_name if req_name else "Seeker"
|
| 314 |
-
|
| 315 |
-
logger.info(f"[AGENT] 🔮 Executing Oracle with topic: '{topic}' for '{effective_name}'")
|
| 316 |
-
if get_oracle_data:
|
| 317 |
-
try:
|
| 318 |
-
# Call backend
|
| 319 |
-
oracle_raw = get_oracle_data(name=effective_name, topic=topic, date_str="")
|
| 320 |
-
|
| 321 |
-
# FILTERING LOGIC (User Request: Only 3 sources, no BOS API/ELS)
|
| 322 |
-
# We construct a filtered dictionary
|
| 323 |
-
filtered_result = {
|
| 324 |
-
"wisdom_nodes": oracle_raw.get("wisdom_nodes", [])
|
| 325 |
-
}
|
| 326 |
-
# If wisdom_nodes is missing/empty, maybe keep raw but warn?
|
| 327 |
-
# Use strict filtering as requested.
|
| 328 |
-
|
| 329 |
-
tool_result = json.dumps(filtered_result, indent=2)
|
| 330 |
-
logger.info(f"[AGENT] ✅ Oracle Result Obtained (Filtered Size: {len(tool_result)} bytes)")
|
| 331 |
-
except Exception as e:
|
| 332 |
-
logger.error(f"[AGENT] ❌ Oracle Backend Error: {e}")
|
| 333 |
-
tool_result = f"Error executing oracle: {str(e)}"
|
| 334 |
-
else:
|
| 335 |
-
logger.warning("[AGENT] ⚠️ Oracle module not available")
|
| 336 |
-
tool_result = "Oracle module not available."
|
| 337 |
-
else:
|
| 338 |
-
logger.warning(f"[AGENT] ⚠️ Unknown tool requested: {tool_name}")
|
| 339 |
-
tool_result = f"Unknown tool: {tool_name}"
|
| 340 |
-
|
| 341 |
-
messages.append({"role": "assistant", "content": [{"type": "text", "text": current_turn_text}]})
|
| 342 |
-
|
| 343 |
-
tool_injection = f"""<tool_result>{tool_result}</tool_result>
|
| 344 |
-
Now interpret this result soulfully and poetically for the user. Do not mention JSON.
|
| 345 |
-
IMPORTANT: Connect this smoothly to your previous statement. Ensure a fluid, cohesive narrative without abrupt jumps."""
|
| 346 |
-
|
| 347 |
-
logger.info("[AGENT] 💉 Injecting Tool Result into context for interpretation...")
|
| 348 |
-
messages.append({"role": "user", "content": [{"type": "text", "text": tool_injection}]})
|
| 349 |
-
|
| 350 |
-
# Yield a special marker to say "Turn Finished"
|
| 351 |
-
yield "__TURN_END__"
|
| 352 |
-
continue
|
| 353 |
-
except Exception as e:
|
| 354 |
-
logger.error(f"[AGENT] 💥 Tool parsing/logic crash: {e}")
|
| 355 |
-
break
|
| 356 |
-
else:
|
| 357 |
-
logger.info("[AGENT] ✨ No tool calls. Finalizing response.")
|
| 358 |
-
break
|
| 359 |
-
|
| 360 |
-
# --- Voice Engine ---
|
| 361 |
-
async def generate_speech(text: str, lang: str = "English"):
|
| 362 |
-
import edge_tts
|
| 363 |
-
VOICES = {"English": "en-US-GuyNeural", "German": "de-DE-ConradNeural", "French": "fr-FR-HenriNeural"}
|
| 364 |
-
voice = VOICES.get(lang, VOICES["English"])
|
| 365 |
-
logger.debug(f"TRACE: generate_speech() called. Text len: {len(text)}, Lang: {lang}")
|
| 366 |
-
temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
|
| 367 |
-
communicate = edge_tts.Communicate(text, voice)
|
| 368 |
-
await communicate.save(temp_wav.name)
|
| 369 |
-
return temp_wav.name
|
| 370 |
-
|
| 371 |
-
def transcribe_audio(path: str):
|
| 372 |
-
logger.debug(f"TRACE: transcribe_audio() called with path: {path}")
|
| 373 |
-
return "Transcribed text"
|
| 374 |
-
|
| 375 |
-
# --- Gradio Wrappers ---
|
| 376 |
-
def voice_chat_wrapper(audio_path, history, threads, tid, vs_state, mh_state, short_answers):
|
| 377 |
-
if audio_path is None: yield history, threads, gr.update(), gr.update(), None; return
|
| 378 |
-
text = transcribe_audio(audio_path)
|
| 379 |
-
detected_lang = detect_language(text)
|
| 380 |
-
final_history, final_threads, final_update = history, threads, gr.update()
|
| 381 |
-
if text:
|
| 382 |
-
gen = chat_wrapper(text, history, threads, tid, vs_state, mh_state, short_answers=short_answers, lang=detected_lang)
|
| 383 |
-
for h, t, tr1, tr2, _ in gen:
|
| 384 |
-
final_history, final_threads, final_update = h, t, tr1
|
| 385 |
-
yield h, t, tr1, tr2, None
|
| 386 |
-
import asyncio
|
| 387 |
-
last_msg = final_history[-1]["content"] if final_history else ""
|
| 388 |
-
if last_msg:
|
| 389 |
-
voice_path = asyncio.run(generate_speech(last_msg, lang=detected_lang))
|
| 390 |
-
yield final_history, final_threads, final_update, final_update, voice_path
|
| 391 |
-
else:
|
| 392 |
-
yield final_history, final_threads, final_update, final_update, None
|
| 393 |
-
|
| 394 |
-
def chat_wrapper(message, history, threads, tid, vs_state, mh_state, short_answers=False, lang=None):
|
| 395 |
-
if not message.strip():
|
| 396 |
-
upd = gr.update(choices=[(v["title"], k) for k, v in threads.items()], value=tid)
|
| 397 |
-
yield history, threads, upd, upd, None
|
| 398 |
-
return
|
| 399 |
-
history.append({"role": "user", "content": message})
|
| 400 |
-
yield history, threads, gr.update(), gr.update(), None
|
| 401 |
-
|
| 402 |
-
# Start first response bubble
|
| 403 |
-
history.append({"role": "assistant", "content": ""})
|
| 404 |
-
|
| 405 |
-
for response_part in chat_agent_stream(message, history[:-2], vs_state, mh_state, user_lang=lang, short_answers=short_answers):
|
| 406 |
-
if response_part == "__TURN_END__":
|
| 407 |
-
# Start NEW bubble for next turn
|
| 408 |
-
history.append({"role": "assistant", "content": ""})
|
| 409 |
-
yield history, threads, gr.update(), gr.update(), None
|
| 410 |
-
else:
|
| 411 |
-
history[-1]["content"] = response_part
|
| 412 |
-
yield history, threads, gr.update(), gr.update(), None
|
| 413 |
-
|
| 414 |
-
# Cleanup empty bubble if exists (rare edge case)
|
| 415 |
-
if not history[-1]["content"]: history.pop()
|
| 416 |
-
|
| 417 |
-
if tid not in threads: threads[tid] = {"title": "Conversation", "history": []}
|
| 418 |
-
threads[tid]["history"] = history
|
| 419 |
-
if len(history) <= 2:
|
| 420 |
-
threads[tid]["title"] = (message[:25] + "..") if message else "Conversation"
|
| 421 |
-
choices = [(v["title"], k) for k, v in threads.items()]
|
| 422 |
-
upd = gr.update(choices=choices, value=tid)
|
| 423 |
-
yield history, threads, upd, upd, None
|
| 424 |
-
|
| 425 |
-
def stream_handler(stream, state):
|
| 426 |
-
if stream is None: return state, None
|
| 427 |
-
sr, y = stream
|
| 428 |
-
if y is None or len(y) == 0: return state, None
|
| 429 |
-
y = y.astype(np.float32)
|
| 430 |
-
y = y / np.max(np.abs(y)) if np.max(np.abs(y)) > 0 else y
|
| 431 |
-
rms = np.sqrt(np.mean(y**2))
|
| 432 |
-
SILENCE_THRESHOLD, SILENCE_CHUNKS = 0.01, 20
|
| 433 |
-
if state is None: state = {"buffer": [], "silence_counter": 0, "is_speaking": False}
|
| 434 |
-
state["buffer"].append((sr, stream[1]))
|
| 435 |
-
if rms > SILENCE_THRESHOLD:
|
| 436 |
-
state["is_speaking"], state["silence_counter"] = True, 0
|
| 437 |
-
elif state["is_speaking"]:
|
| 438 |
-
state["silence_counter"] += 1
|
| 439 |
-
if state["is_speaking"] and state["silence_counter"] > SILENCE_CHUNKS:
|
| 440 |
-
full_audio = np.concatenate([c[1] for c in state["buffer"]])
|
| 441 |
-
sr_final = state["buffer"][0][0]
|
| 442 |
-
temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
|
| 443 |
-
wavfile.write(temp_wav.name, sr_final, full_audio)
|
| 444 |
-
return {"buffer": [], "silence_counter": 0, "is_speaking": False}, temp_wav.name
|
| 445 |
-
return state, None
|
| 446 |
-
|
| 447 |
-
# --- INTERNAL CALLBACKS ---
|
| 448 |
-
def create_new_thread_callback(threads):
|
| 449 |
-
nid = str(uuid.uuid4())
|
| 450 |
-
threads[nid] = {"title": "New Conversation", "history": []}
|
| 451 |
-
choices = [(v["title"], k) for k, v in threads.items()]
|
| 452 |
-
return threads, nid, gr.update(choices=choices, value=nid), []
|
| 453 |
-
|
| 454 |
-
def switch_thread(tid, t_state):
|
| 455 |
-
logger.debug(f"TRACE: switch_thread() called for tid: {tid}")
|
| 456 |
-
if isinstance(tid, list):
|
| 457 |
-
if not tid: return [], gr.update(), gr.update(), gr.update()
|
| 458 |
-
tid = tid[0]
|
| 459 |
-
tid = str(tid)
|
| 460 |
-
history = t_state.get(tid, {}).get("history", [])
|
| 461 |
-
choices = [(v["title"], k) for k, v in t_state.items()]
|
| 462 |
-
upd = gr.update(value=tid, choices=choices)
|
| 463 |
-
return history, tid, upd, upd
|
| 464 |
-
|
| 465 |
-
def session_import_handler(file):
|
| 466 |
-
if not file: return [], {}, None, gr.update(), gr.update()
|
| 467 |
-
with open(file.name, "r") as f: data = json.load(f)
|
| 468 |
-
imported_threads = data.get("threads", {})
|
| 469 |
-
active_id = data.get("active_id", list(imported_threads.keys())[0] if imported_threads else None)
|
| 470 |
-
history = imported_threads.get(active_id, {}).get("history", []) if active_id else []
|
| 471 |
-
choices = [(v["title"], k) for k, v in imported_threads.items()]
|
| 472 |
-
upd = gr.update(choices=choices, value=active_id)
|
| 473 |
-
return history, imported_threads, active_id, upd, upd
|
| 474 |
-
|
| 475 |
-
def session_export_handler(chatbot_val, threads, active_id):
|
| 476 |
-
export_data = {"threads": threads, "active_id": active_id}
|
| 477 |
-
path = "sage_session_export.json"
|
| 478 |
-
with open(path, "w") as f: json.dump(export_data, f, indent=2)
|
| 479 |
-
return path
|
| 480 |
-
|
| 481 |
-
def build_demo() -> gr.Blocks:
|
| 482 |
-
initial_thread_id = str(uuid.uuid4())
|
| 483 |
-
with gr.Blocks(title="Gemma 3 Sage v6.5 SP1", theme="soft", css=PREMIUM_CSS) as demo:
|
| 484 |
-
threads_state = gr.State({initial_thread_id: {"title": "New Chat", "history": []}})
|
| 485 |
-
active_thread_id = gr.State(initial_thread_id)
|
| 486 |
-
vector_store_state = gr.State(None)
|
| 487 |
-
mongo_handler_state = gr.State(None)
|
| 488 |
-
|
| 489 |
-
with gr.Row(elem_classes="header-tray"):
|
| 490 |
-
gr.Markdown("# 🌌 Gemma 3 Sage <small>v6.5 SP1</small>")
|
| 491 |
-
|
| 492 |
-
with gr.Row():
|
| 493 |
-
# Desktop Sidebar (Radio List)
|
| 494 |
-
with gr.Column(scale=1, variant="panel", elem_classes="sidebar-panel glass-panel desktop-only"):
|
| 495 |
-
gr.Markdown("### 🕒 Recent Chats")
|
| 496 |
-
# Using Radio as a list selector
|
| 497 |
-
thread_list = gr.Radio(choices=[(f"New Chat", initial_thread_id)], value=initial_thread_id, label=None, interactive=True, container=False)
|
| 498 |
-
new_thread_btn = gr.Button("➕ New Conversation", variant="secondary")
|
| 499 |
-
|
| 500 |
-
with gr.Column(scale=4):
|
| 501 |
-
with gr.Tabs() as tabs:
|
| 502 |
-
with gr.Tab("💬 Live Conversation", id=0, elem_classes="glass-panel"):
|
| 503 |
-
|
| 504 |
-
# Mobile Menu (Accordion + Dropdown)
|
| 505 |
-
with gr.Accordion("🕒 Conversations (Mobile)", open=False, visible=True, elem_classes="mobile-only") as mobile_sessions:
|
| 506 |
-
m_thread_list = gr.Dropdown(choices=[("New Chat", initial_thread_id)], value=initial_thread_id, label="Select Session")
|
| 507 |
-
m_new_btn = gr.Button("➕ New Conversation", variant="secondary")
|
| 508 |
-
|
| 509 |
-
chatbot = gr.Chatbot(label="Sage", type="messages", height=600, show_label=False, autoscroll=False)
|
| 510 |
-
with gr.Row():
|
| 511 |
-
msg_textbox = gr.Textbox(placeholder="Whisper your heart or type...", label=None, scale=8, container=False)
|
| 512 |
-
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 513 |
-
# Moved Short Answer checkbox here for visibility
|
| 514 |
-
with gr.Row():
|
| 515 |
-
short_ans_cb = gr.Checkbox(label="Short Answers", value=False)
|
| 516 |
-
with gr.Row():
|
| 517 |
-
stream_state = gr.State({"buffer": [], "silence_counter": 0, "is_speaking": False})
|
| 518 |
-
audio_input = gr.Audio(label="Voice", sources="microphone", type="numpy", streaming=True)
|
| 519 |
-
processed_audio, audio_output = gr.State(None), gr.Audio(label="Sage Voice", autoplay=True, visible=False)
|
| 520 |
-
with gr.Row(elem_classes="glass-panel"):
|
| 521 |
-
export_btn = gr.Button("📤 Export Session", variant="secondary", size="sm")
|
| 522 |
-
import_file = gr.File(label="Import", file_count="single", height=60)
|
| 523 |
-
export_file = gr.File(label="Download", interactive=False, visible=False)
|
| 524 |
-
|
| 525 |
-
with gr.Tab("📚 Sacred Knowledge", id=1, elem_classes="glass-panel"):
|
| 526 |
-
file_uploader = gr.File(label="Upload", file_count="multiple", type="filepath")
|
| 527 |
-
index_button = gr.Button("🔄 Sync Index", variant="primary")
|
| 528 |
-
index_status = gr.Markdown("Bereit.")
|
| 529 |
-
with gr.Accordion("⚙️ MongoDB Settings", open=False):
|
| 530 |
-
mongo_uri = gr.Textbox(label="URI", value="mongodb://localhost:27017/")
|
| 531 |
-
mongo_db = gr.Textbox(label="DB", value="rag_db")
|
| 532 |
-
mongo_coll = gr.Textbox(label="Coll", value="gemma_chunks")
|
| 533 |
-
use_mongo_cb = gr.Checkbox(label="Sync to Mongo", value=True)
|
| 534 |
-
clear_mongo_btn = gr.Button("🗑️ Clear Mongo")
|
| 535 |
-
clear_idx_btn = gr.Button("🧹 Clear FAISS", variant="stop")
|
| 536 |
-
|
| 537 |
-
clear_mongo_btn.click(lambda u, d, c: MongoDBHandler(u, d, c).connect() and MongoDBHandler(u, d, c).clear() or "Mongo geleert", [mongo_uri, mongo_db, mongo_coll], index_status)
|
| 538 |
-
|
| 539 |
-
audio_input.stream(stream_handler, [audio_input, stream_state], [stream_state, processed_audio])
|
| 540 |
-
processed_audio.change(voice_chat_wrapper, [processed_audio, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output])
|
| 541 |
-
msg_textbox.submit(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
|
| 542 |
-
submit_btn.click(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
|
| 543 |
-
new_thread_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, thread_list, chatbot])
|
| 544 |
-
m_new_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, m_thread_list, chatbot])
|
| 545 |
-
thread_list.change(switch_thread, [thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
|
| 546 |
-
m_thread_list.change(switch_thread, [m_thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
|
| 547 |
-
index_button.click(index_files, [file_uploader, mongo_uri, mongo_db, mongo_coll, use_mongo_cb, vector_store_state, mongo_handler_state], [index_status, vector_store_state, mongo_handler_state], show_progress="full")
|
| 548 |
-
clear_idx_btn.click(clear_index, outputs=[index_status, vector_store_state, mongo_handler_state], show_progress="full")
|
| 549 |
-
import_file.change(session_import_handler, import_file, [chatbot, threads_state, active_thread_id, thread_list, m_thread_list], show_progress="full")
|
| 550 |
-
export_btn.click(session_export_handler, [chatbot, threads_state, active_thread_id], export_file, show_progress="full").then(lambda: gr.update(visible=True), None, export_file)
|
| 551 |
-
return demo
|
| 552 |
|
| 553 |
if __name__ == "__main__":
|
| 554 |
-
get_llm()
|
|
|
|
|
|
| 1 |
+
from app_module import get_llm, build_demo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
if __name__ == "__main__":
|
| 4 |
+
get_llm()
|
| 5 |
+
build_demo().launch(server_name="0.0.0.0")
|
app_local.py
CHANGED
|
@@ -1,554 +1,11 @@
|
|
| 1 |
-
import
|
| 2 |
-
import torch
|
| 3 |
-
import gradio as gr
|
| 4 |
-
import time
|
| 5 |
-
import re
|
| 6 |
-
import codecs
|
| 7 |
-
import uuid
|
| 8 |
-
import json
|
| 9 |
-
import logging
|
| 10 |
-
import tempfile
|
| 11 |
-
import numpy as np
|
| 12 |
-
import scipy.io.wavfile as wavfile
|
| 13 |
-
import asyncio
|
| 14 |
-
import warnings
|
| 15 |
-
from typing import List, Tuple, Generator, Dict
|
| 16 |
-
from threading import Thread
|
| 17 |
-
|
| 18 |
-
# ML / Transformers
|
| 19 |
-
import transformers
|
| 20 |
-
transformers.utils.logging.set_verbosity_error()
|
| 21 |
-
warnings.filterwarnings("ignore", category=UserWarning, module="gradio.components.dropdown")
|
| 22 |
-
from transformers import AutoProcessor, Gemma3ForConditionalGeneration, TextIteratorStreamer
|
| 23 |
-
|
| 24 |
-
# --- Logging Setup ---
|
| 25 |
-
# Set root logger to ERROR to suppress external library noise
|
| 26 |
-
logging.basicConfig(level=logging.ERROR, format='%(name)s [%(levelname)s] %(message)s')
|
| 27 |
-
|
| 28 |
-
# Specific library suppressions
|
| 29 |
-
for lib in ["transformers", "accelerate", "httpx", "gradio", "langchain"]:
|
| 30 |
-
logging.getLogger(lib).setLevel(logging.ERROR)
|
| 31 |
-
|
| 32 |
-
# Application-level logger
|
| 33 |
-
logger = logging.getLogger("app")
|
| 34 |
-
logger.setLevel(logging.DEBUG)
|
| 35 |
-
logger.propagate = False # DO NOT propagate to root to avoid double-logging or filtering
|
| 36 |
-
ch = logging.StreamHandler()
|
| 37 |
-
ch.setLevel(logging.DEBUG)
|
| 38 |
-
ch.setFormatter(logging.Formatter('[app] [%(levelname)s] %(message)s'))
|
| 39 |
-
logger.addHandler(ch)
|
| 40 |
-
|
| 41 |
-
# --------------------------------------------------------------------
|
| 42 |
-
# Konfiguration & Globale States
|
| 43 |
-
# --------------------------------------------------------------------
|
| 44 |
-
EMBED_MODEL_ID = "google/embeddinggemma-300m"
|
| 45 |
-
LLM_MODEL_ID = "google/gemma-3-4b-it"
|
| 46 |
-
|
| 47 |
-
EMBEDDING_FUNCTION = None
|
| 48 |
-
LLM_MODEL = None
|
| 49 |
-
LLM_PROCESSOR = None
|
| 50 |
-
|
| 51 |
-
# --- UI Premium Aesthetics ---
|
| 52 |
-
PREMIUM_CSS = """
|
| 53 |
-
.glass-panel {
|
| 54 |
-
background: rgba(255, 255, 255, 0.05) !important;
|
| 55 |
-
backdrop-filter: blur(10px) !important;
|
| 56 |
-
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 57 |
-
border-radius: 15px !important;
|
| 58 |
-
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37) !important;
|
| 59 |
-
}
|
| 60 |
-
.sidebar-panel {
|
| 61 |
-
border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 62 |
-
height: 100vh;
|
| 63 |
-
}
|
| 64 |
-
border-bottom: 2px solid #0f3460;
|
| 65 |
-
}
|
| 66 |
-
.desktop-only { display: block; }
|
| 67 |
-
.mobile-only { display: none; }
|
| 68 |
-
@media (max-width: 768px) {
|
| 69 |
-
.desktop-only { display: none !important; }
|
| 70 |
-
.mobile-only { display: block !important; }
|
| 71 |
-
.sidebar-panel { display: none !important; }
|
| 72 |
-
}
|
| 73 |
-
"""
|
| 74 |
-
|
| 75 |
-
try:
|
| 76 |
-
from pypdf import PdfReader
|
| 77 |
-
from langchain_community.vectorstores import FAISS
|
| 78 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
| 79 |
-
from langchain_core.documents import Document
|
| 80 |
-
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 81 |
-
from mongochain import MongoDBHandler
|
| 82 |
-
except ImportError:
|
| 83 |
-
pass
|
| 84 |
-
|
| 85 |
-
# Spiritual Integration
|
| 86 |
-
try:
|
| 87 |
-
from spiritual_bridge import get_oracle_data
|
| 88 |
-
except ImportError:
|
| 89 |
-
get_oracle_data = None
|
| 90 |
-
|
| 91 |
-
# --- Model Loading ---
|
| 92 |
-
def get_device() -> torch.device:
|
| 93 |
-
if torch.cuda.is_available(): return torch.device("cuda")
|
| 94 |
-
return torch.device("cpu")
|
| 95 |
-
|
| 96 |
-
def get_embedding_function():
|
| 97 |
-
global EMBEDDING_FUNCTION
|
| 98 |
-
if EMBEDDING_FUNCTION is None:
|
| 99 |
-
device = get_device()
|
| 100 |
-
logger.debug(f"Initialisiere Embedding-Modell '{EMBED_MODEL_ID}' auf Device '{device}'.")
|
| 101 |
-
EMBEDDING_FUNCTION = HuggingFaceEmbeddings(
|
| 102 |
-
model_name=EMBED_MODEL_ID,
|
| 103 |
-
model_kwargs={'device': device}
|
| 104 |
-
)
|
| 105 |
-
logger.debug("Embedding-Modell erfolgreich initialisiert.")
|
| 106 |
-
return EMBEDDING_FUNCTION
|
| 107 |
-
|
| 108 |
-
def get_llm():
|
| 109 |
-
global LLM_MODEL, LLM_PROCESSOR
|
| 110 |
-
if LLM_MODEL is None or LLM_PROCESSOR is None:
|
| 111 |
-
device = get_device()
|
| 112 |
-
logger.debug(f"Initialisiere LLM '{LLM_MODEL_ID}' auf Device '{device}'.")
|
| 113 |
-
dtype = torch.bfloat16 if "cuda" in device.type else torch.float32
|
| 114 |
-
LLM_MODEL = Gemma3ForConditionalGeneration.from_pretrained(
|
| 115 |
-
LLM_MODEL_ID,
|
| 116 |
-
dtype=dtype,
|
| 117 |
-
device_map="auto",
|
| 118 |
-
).eval()
|
| 119 |
-
LLM_PROCESSOR = AutoProcessor.from_pretrained(LLM_MODEL_ID)
|
| 120 |
-
logger.debug("LLM und Prozessor erfolgreich initialisiert.")
|
| 121 |
-
return LLM_MODEL, LLM_PROCESSOR
|
| 122 |
-
|
| 123 |
-
# --- Language Detection ---
|
| 124 |
-
def detect_language(text: str) -> str:
|
| 125 |
-
if not text or len(text) < 3: return "English"
|
| 126 |
-
model, processor = get_llm()
|
| 127 |
-
prompt = f"Detect the language of the following text and return ONLY the language name (e.g., 'English', 'German', 'French'):\n\n\"{text}\""
|
| 128 |
-
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 129 |
-
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
|
| 130 |
-
with torch.no_grad():
|
| 131 |
-
outputs = model.generate(inputs, max_new_tokens=20, do_sample=False)
|
| 132 |
-
raw_output = processor.batch_decode(outputs[:, inputs.shape[1]:], skip_special_tokens=True)[0].strip()
|
| 133 |
-
logger.debug(f"DEBUG: Raw Language Detection Output: '{raw_output}'")
|
| 134 |
-
|
| 135 |
-
keywords = ["English", "German", "French", "Spanish", "Italian", "Dutch", "Russian", "Chinese", "Japanese"]
|
| 136 |
-
for k in keywords:
|
| 137 |
-
if k.lower() in raw_output.lower():
|
| 138 |
-
logger.debug(f"DEBUG: Detected User Language (Normalized): '{k}'")
|
| 139 |
-
return k
|
| 140 |
-
return "English"
|
| 141 |
-
|
| 142 |
-
# --- Document Handling ---
|
| 143 |
-
def extract_text_from_file(path: str) -> str:
|
| 144 |
-
ext = os.path.splitext(path)[1].lower()
|
| 145 |
-
if ext in [".txt", ".md", ".markdown"]:
|
| 146 |
-
with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
|
| 147 |
-
if ext == ".pdf":
|
| 148 |
-
text_parts = []
|
| 149 |
-
try:
|
| 150 |
-
reader = PdfReader(path)
|
| 151 |
-
for page in reader.pages:
|
| 152 |
-
page_text = page.extract_text()
|
| 153 |
-
if page_text: text_parts.append(page_text)
|
| 154 |
-
return "\n\n".join(text_parts)
|
| 155 |
-
except Exception as e:
|
| 156 |
-
logger.error(f"Error reading PDF {path}: {e}"); return ""
|
| 157 |
-
try:
|
| 158 |
-
with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
|
| 159 |
-
except Exception: return ""
|
| 160 |
-
|
| 161 |
-
def get_text_splitter() -> RecursiveCharacterTextSplitter:
|
| 162 |
-
return RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, length_function=len)
|
| 163 |
-
|
| 164 |
-
# --- RAG Core ---
|
| 165 |
-
def index_files(file_paths, mongo_uri, db_name, coll_name, use_mongo, vs_state, mh_state, progress=gr.Progress(track_tqdm=True)):
|
| 166 |
-
if not file_paths: return "Keine Dateien zum Indexieren ausgewählt.", vs_state, mh_state
|
| 167 |
-
|
| 168 |
-
logger.debug(f"Indexierung gestartet für {len(file_paths)} Datei(en).")
|
| 169 |
-
embed_fn = get_embedding_function()
|
| 170 |
-
splitter = get_text_splitter()
|
| 171 |
-
documents = []
|
| 172 |
-
|
| 173 |
-
for path in progress.tqdm(file_paths, desc="1/2: Dateien verarbeiten"):
|
| 174 |
-
if path is None: continue
|
| 175 |
-
text = extract_text_from_file(path)
|
| 176 |
-
if not text.strip(): continue
|
| 177 |
-
chunks = splitter.split_text(text)
|
| 178 |
-
source_name = os.path.basename(path)
|
| 179 |
-
for c in chunks:
|
| 180 |
-
documents.append(Document(page_content=c, metadata={"source": source_name}))
|
| 181 |
-
|
| 182 |
-
logger.debug(f"Total chunks created: {len(documents)}")
|
| 183 |
-
if not documents: return "Kein Text zum Indexieren gefunden.", vs_state, mh_state
|
| 184 |
-
|
| 185 |
-
progress(0.7, desc="2/2: Indexing...")
|
| 186 |
-
new_vs = FAISS.from_documents(documents, embed_fn)
|
| 187 |
-
if vs_state:
|
| 188 |
-
vs_state.merge_from(new_vs)
|
| 189 |
-
else:
|
| 190 |
-
vs_state = new_vs
|
| 191 |
-
|
| 192 |
-
mh_state = None
|
| 193 |
-
if use_mongo:
|
| 194 |
-
try:
|
| 195 |
-
mh_state = MongoDBHandler(uri=mongo_uri, db_name=db_name, collection_name=coll_name)
|
| 196 |
-
mh_state.connect()
|
| 197 |
-
logger.debug(f"Pushe {len(documents)} Chunks nach MongoDB...")
|
| 198 |
-
for doc in documents:
|
| 199 |
-
mh_state.insert_chunk(doc.page_content, doc.metadata)
|
| 200 |
-
logger.debug("MongoDB-Sync abgeschlossen.")
|
| 201 |
-
except Exception as e:
|
| 202 |
-
logger.error(f"Mongo Error: {e}")
|
| 203 |
-
|
| 204 |
-
logger.debug(f"Indexierung abgeschlossen. Gesamt: {vs_state.index.ntotal} Chunks.")
|
| 205 |
-
return f"Index aktualisiert: {vs_state.index.ntotal} Chunks insgesamt.", vs_state, mh_state
|
| 206 |
-
|
| 207 |
-
def clear_index():
|
| 208 |
-
import gc; gc.collect()
|
| 209 |
-
logger.debug("Vektor-Index wurde geleert.")
|
| 210 |
-
return "Index geleert.", None, None
|
| 211 |
-
|
| 212 |
-
def retrieve_relevant_chunks(query, vs_state, mh_state, top_k=3):
|
| 213 |
-
if not vs_state: return []
|
| 214 |
-
logger.debug(f"Suche in FAISS: '{query}'")
|
| 215 |
-
docs = vs_state.similarity_search(query, k=top_k)
|
| 216 |
-
return [{"content": d.page_content, "source": d.metadata.get("source", "Unknown")} for d in docs]
|
| 217 |
-
|
| 218 |
-
def build_rag_prompt(user_question: str, retrieved_chunks: List[Dict]) -> str:
|
| 219 |
-
if not retrieved_chunks: context_str = "Kein relevanter Kontext gefunden."
|
| 220 |
-
else:
|
| 221 |
-
context_parts = [f"[{i}] (Quelle: {ch['source']}): \"{ch['content']}\"" for i, ch in enumerate(retrieved_chunks, 1)]
|
| 222 |
-
context_str = "\n\n".join(context_parts)
|
| 223 |
-
return (f"Beantworte die Benutzerfrage nur basierend auf dem Kontext.\n\n"
|
| 224 |
-
f"--- Kontext ---\n{context_str}\n\n"
|
| 225 |
-
f"--- Frage ---\n{user_question}\n\n"
|
| 226 |
-
f"--- Antwort ---")
|
| 227 |
-
|
| 228 |
-
# --- Agent System ---
|
| 229 |
-
def build_agent_prompt(query, context, history, language="English", short_answers=False):
|
| 230 |
-
context_str = "\n".join([f"- {c['content']} (Source: {c['source']})" for i, c in enumerate(context)])
|
| 231 |
-
|
| 232 |
-
style_instruction = "Be concise." if short_answers else ""
|
| 233 |
-
|
| 234 |
-
system = f"""You are Sage 6.5, a spiritual AI guide.
|
| 235 |
-
Respond in {language}. {style_instruction}
|
| 236 |
-
If you need to use a tool, you MUST use the following JSON format inside <tool_call> tags:
|
| 237 |
-
<tool_call>{{"name": "tool_name", "arguments": {{"arg1": "val1"}}}}</tool_call>
|
| 238 |
-
|
| 239 |
-
Available Tools:
|
| 240 |
-
1. oracle_consultation: Consult the archive for deep wisdom. Arguments: {{"topic": "str", "name": "str (Optional. Use ONLY if the user explicitly stated their name, otherwise omit)"}}
|
| 241 |
-
"""
|
| 242 |
-
return system + f"\n\nContext:\n{context_str}\n\nUser Question: {query}"
|
| 243 |
-
|
| 244 |
-
def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
|
| 245 |
-
model, processor = get_llm()
|
| 246 |
-
lang = user_lang if user_lang else detect_language(query)
|
| 247 |
-
context = retrieve_relevant_chunks(query, vs_state, mh_state)
|
| 248 |
-
prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
|
| 249 |
-
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 250 |
-
|
| 251 |
-
logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
|
| 252 |
-
|
| 253 |
-
def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
|
| 254 |
-
model, processor = get_llm()
|
| 255 |
-
lang = user_lang if user_lang else detect_language(query)
|
| 256 |
-
context = retrieve_relevant_chunks(query, vs_state, mh_state)
|
| 257 |
-
prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
|
| 258 |
-
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 259 |
-
|
| 260 |
-
logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
|
| 261 |
-
|
| 262 |
-
max_turns = 3
|
| 263 |
-
for turn in range(max_turns):
|
| 264 |
-
logger.info(f"[AGENT] 🔄 Turn {turn+1}/{max_turns}")
|
| 265 |
-
|
| 266 |
-
input_ids = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
|
| 267 |
-
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 268 |
-
|
| 269 |
-
gen_kwargs = {"input_ids": input_ids, "streamer": streamer, "max_new_tokens": 512, "do_sample": False}
|
| 270 |
-
thread = Thread(target=model.generate, kwargs=gen_kwargs)
|
| 271 |
-
thread.start()
|
| 272 |
-
|
| 273 |
-
current_turn_text = ""
|
| 274 |
-
# We yield a TUPLE: (accumulated_text_for_THIS_turn, is_final)
|
| 275 |
-
# But wait, the wrapper needs to handle new messages.
|
| 276 |
-
# Strategy: Yield just the text of THIS turn. Wrapper handles appending to a NEW history item each turn.
|
| 277 |
-
|
| 278 |
-
logger.info("[AGENT] ⏳ Streaming response...")
|
| 279 |
-
for new_text in streamer:
|
| 280 |
-
current_turn_text += new_text
|
| 281 |
-
clean_chunk = re.sub(r"<tool_call>.*?</tool_call>", "", current_turn_text, flags=re.DOTALL)
|
| 282 |
-
yield clean_chunk.strip()
|
| 283 |
-
|
| 284 |
-
logger.info(f"[AGENT] 🛑 Raw Model Output: {current_turn_text}")
|
| 285 |
-
|
| 286 |
-
# Tool Detection
|
| 287 |
-
tool_match = re.search(r"<tool_call>(.*?)</tool_call>", current_turn_text, re.DOTALL)
|
| 288 |
-
if tool_match:
|
| 289 |
-
# If tool found, this turn is OVER regarding user output.
|
| 290 |
-
# We yield a special signal to indicate "End of Message, Start Next Logic"?
|
| 291 |
-
# actually, if we yield, the wrapper updates history[-1].
|
| 292 |
-
# If we want a NEW message, we need to tell wrapper to append.
|
| 293 |
-
# Simplified: Use a separator? No, wrapper loop is easier.
|
| 294 |
-
|
| 295 |
-
# For now, let's keep the generator simple.
|
| 296 |
-
# It yields text updates for the CURRENT turn.
|
| 297 |
-
# Once loop breaks (tool found), we start next turn.
|
| 298 |
-
# BUT: How to tell wrapper "This turn is done, start a new bubble"?
|
| 299 |
-
# Generator yields: {"text": "...", "new_bubble": True/False}
|
| 300 |
-
|
| 301 |
-
try:
|
| 302 |
-
tool_data = json.loads(tool_match.group(1))
|
| 303 |
-
logger.info(f"[AGENT] 🛠️ Tool Call Detected: {tool_data}")
|
| 304 |
-
|
| 305 |
-
tool_name = tool_data.get("name")
|
| 306 |
-
tool_args = tool_data.get("arguments", {})
|
| 307 |
-
|
| 308 |
-
if tool_name == "oracle_consultation":
|
| 309 |
-
topic = tool_args.get("topic", "")
|
| 310 |
-
|
| 311 |
-
# Name Handling: Use provided name or default to 'Seeker'
|
| 312 |
-
req_name = tool_args.get("name", "").strip()
|
| 313 |
-
effective_name = req_name if req_name else "Seeker"
|
| 314 |
-
|
| 315 |
-
logger.info(f"[AGENT] 🔮 Executing Oracle with topic: '{topic}' for '{effective_name}'")
|
| 316 |
-
if get_oracle_data:
|
| 317 |
-
try:
|
| 318 |
-
# Call backend
|
| 319 |
-
oracle_raw = get_oracle_data(name=effective_name, topic=topic, date_str="")
|
| 320 |
-
|
| 321 |
-
# FILTERING LOGIC (User Request: Only 3 sources, no BOS API/ELS)
|
| 322 |
-
# We construct a filtered dictionary
|
| 323 |
-
filtered_result = {
|
| 324 |
-
"wisdom_nodes": oracle_raw.get("wisdom_nodes", [])
|
| 325 |
-
}
|
| 326 |
-
# If wisdom_nodes is missing/empty, maybe keep raw but warn?
|
| 327 |
-
# Use strict filtering as requested.
|
| 328 |
-
|
| 329 |
-
tool_result = json.dumps(filtered_result, indent=2)
|
| 330 |
-
logger.info(f"[AGENT] ✅ Oracle Result Obtained (Filtered Size: {len(tool_result)} bytes)")
|
| 331 |
-
except Exception as e:
|
| 332 |
-
logger.error(f"[AGENT] ❌ Oracle Backend Error: {e}")
|
| 333 |
-
tool_result = f"Error executing oracle: {str(e)}"
|
| 334 |
-
else:
|
| 335 |
-
logger.warning("[AGENT] ⚠️ Oracle module not available")
|
| 336 |
-
tool_result = "Oracle module not available."
|
| 337 |
-
else:
|
| 338 |
-
logger.warning(f"[AGENT] ⚠️ Unknown tool requested: {tool_name}")
|
| 339 |
-
tool_result = f"Unknown tool: {tool_name}"
|
| 340 |
-
|
| 341 |
-
messages.append({"role": "assistant", "content": [{"type": "text", "text": current_turn_text}]})
|
| 342 |
-
|
| 343 |
-
tool_injection = f"""<tool_result>{tool_result}</tool_result>
|
| 344 |
-
Now interpret this result soulfully and poetically for the user. Do not mention JSON.
|
| 345 |
-
IMPORTANT: Connect this smoothly to your previous statement. Ensure a fluid, cohesive narrative without abrupt jumps."""
|
| 346 |
-
|
| 347 |
-
logger.info("[AGENT] 💉 Injecting Tool Result into context for interpretation...")
|
| 348 |
-
messages.append({"role": "user", "content": [{"type": "text", "text": tool_injection}]})
|
| 349 |
-
|
| 350 |
-
# Yield a special marker to say "Turn Finished"
|
| 351 |
-
yield "__TURN_END__"
|
| 352 |
-
continue
|
| 353 |
-
except Exception as e:
|
| 354 |
-
logger.error(f"[AGENT] 💥 Tool parsing/logic crash: {e}")
|
| 355 |
-
break
|
| 356 |
-
else:
|
| 357 |
-
logger.info("[AGENT] ✨ No tool calls. Finalizing response.")
|
| 358 |
-
break
|
| 359 |
-
|
| 360 |
-
# --- Voice Engine ---
|
| 361 |
-
async def generate_speech(text: str, lang: str = "English"):
|
| 362 |
-
import edge_tts
|
| 363 |
-
VOICES = {"English": "en-US-GuyNeural", "German": "de-DE-ConradNeural", "French": "fr-FR-HenriNeural"}
|
| 364 |
-
voice = VOICES.get(lang, VOICES["English"])
|
| 365 |
-
logger.debug(f"TRACE: generate_speech() called. Text len: {len(text)}, Lang: {lang}")
|
| 366 |
-
temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
|
| 367 |
-
communicate = edge_tts.Communicate(text, voice)
|
| 368 |
-
await communicate.save(temp_wav.name)
|
| 369 |
-
return temp_wav.name
|
| 370 |
-
|
| 371 |
-
def transcribe_audio(path: str):
|
| 372 |
-
logger.debug(f"TRACE: transcribe_audio() called with path: {path}")
|
| 373 |
-
return "Transcribed text"
|
| 374 |
-
|
| 375 |
-
# --- Gradio Wrappers ---
|
| 376 |
-
def voice_chat_wrapper(audio_path, history, threads, tid, vs_state, mh_state, short_answers):
|
| 377 |
-
if audio_path is None: yield history, threads, gr.update(), gr.update(), None; return
|
| 378 |
-
text = transcribe_audio(audio_path)
|
| 379 |
-
detected_lang = detect_language(text)
|
| 380 |
-
final_history, final_threads, final_update = history, threads, gr.update()
|
| 381 |
-
if text:
|
| 382 |
-
gen = chat_wrapper(text, history, threads, tid, vs_state, mh_state, short_answers=short_answers, lang=detected_lang)
|
| 383 |
-
for h, t, tr1, tr2, _ in gen:
|
| 384 |
-
final_history, final_threads, final_update = h, t, tr1
|
| 385 |
-
yield h, t, tr1, tr2, None
|
| 386 |
-
import asyncio
|
| 387 |
-
last_msg = final_history[-1]["content"] if final_history else ""
|
| 388 |
-
if last_msg:
|
| 389 |
-
voice_path = asyncio.run(generate_speech(last_msg, lang=detected_lang))
|
| 390 |
-
yield final_history, final_threads, final_update, final_update, voice_path
|
| 391 |
-
else:
|
| 392 |
-
yield final_history, final_threads, final_update, final_update, None
|
| 393 |
-
|
| 394 |
-
def chat_wrapper(message, history, threads, tid, vs_state, mh_state, short_answers=False, lang=None):
|
| 395 |
-
if not message.strip():
|
| 396 |
-
upd = gr.update(choices=[(v["title"], k) for k, v in threads.items()], value=tid)
|
| 397 |
-
yield history, threads, upd, upd, None
|
| 398 |
-
return
|
| 399 |
-
history.append({"role": "user", "content": message})
|
| 400 |
-
yield history, threads, gr.update(), gr.update(), None
|
| 401 |
-
|
| 402 |
-
# Start first response bubble
|
| 403 |
-
history.append({"role": "assistant", "content": ""})
|
| 404 |
-
|
| 405 |
-
for response_part in chat_agent_stream(message, history[:-2], vs_state, mh_state, user_lang=lang, short_answers=short_answers):
|
| 406 |
-
if response_part == "__TURN_END__":
|
| 407 |
-
# Start NEW bubble for next turn
|
| 408 |
-
history.append({"role": "assistant", "content": ""})
|
| 409 |
-
yield history, threads, gr.update(), gr.update(), None
|
| 410 |
-
else:
|
| 411 |
-
history[-1]["content"] = response_part
|
| 412 |
-
yield history, threads, gr.update(), gr.update(), None
|
| 413 |
-
|
| 414 |
-
# Cleanup empty bubble if exists (rare edge case)
|
| 415 |
-
if not history[-1]["content"]: history.pop()
|
| 416 |
-
|
| 417 |
-
if tid not in threads: threads[tid] = {"title": "Conversation", "history": []}
|
| 418 |
-
threads[tid]["history"] = history
|
| 419 |
-
if len(history) <= 2:
|
| 420 |
-
threads[tid]["title"] = (message[:25] + "..") if message else "Conversation"
|
| 421 |
-
choices = [(v["title"], k) for k, v in threads.items()]
|
| 422 |
-
upd = gr.update(choices=choices, value=tid)
|
| 423 |
-
yield history, threads, upd, upd, None
|
| 424 |
-
|
| 425 |
-
def stream_handler(stream, state):
|
| 426 |
-
if stream is None: return state, None
|
| 427 |
-
sr, y = stream
|
| 428 |
-
if y is None or len(y) == 0: return state, None
|
| 429 |
-
y = y.astype(np.float32)
|
| 430 |
-
y = y / np.max(np.abs(y)) if np.max(np.abs(y)) > 0 else y
|
| 431 |
-
rms = np.sqrt(np.mean(y**2))
|
| 432 |
-
SILENCE_THRESHOLD, SILENCE_CHUNKS = 0.01, 20
|
| 433 |
-
if state is None: state = {"buffer": [], "silence_counter": 0, "is_speaking": False}
|
| 434 |
-
state["buffer"].append((sr, stream[1]))
|
| 435 |
-
if rms > SILENCE_THRESHOLD:
|
| 436 |
-
state["is_speaking"], state["silence_counter"] = True, 0
|
| 437 |
-
elif state["is_speaking"]:
|
| 438 |
-
state["silence_counter"] += 1
|
| 439 |
-
if state["is_speaking"] and state["silence_counter"] > SILENCE_CHUNKS:
|
| 440 |
-
full_audio = np.concatenate([c[1] for c in state["buffer"]])
|
| 441 |
-
sr_final = state["buffer"][0][0]
|
| 442 |
-
temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
|
| 443 |
-
wavfile.write(temp_wav.name, sr_final, full_audio)
|
| 444 |
-
return {"buffer": [], "silence_counter": 0, "is_speaking": False}, temp_wav.name
|
| 445 |
-
return state, None
|
| 446 |
-
|
| 447 |
-
# --- INTERNAL CALLBACKS ---
|
| 448 |
-
def create_new_thread_callback(threads):
|
| 449 |
-
nid = str(uuid.uuid4())
|
| 450 |
-
threads[nid] = {"title": "New Conversation", "history": []}
|
| 451 |
-
choices = [(v["title"], k) for k, v in threads.items()]
|
| 452 |
-
return threads, nid, gr.update(choices=choices, value=nid), []
|
| 453 |
-
|
| 454 |
-
def switch_thread(tid, t_state):
|
| 455 |
-
logger.debug(f"TRACE: switch_thread() called for tid: {tid}")
|
| 456 |
-
if isinstance(tid, list):
|
| 457 |
-
if not tid: return [], gr.update(), gr.update(), gr.update()
|
| 458 |
-
tid = tid[0]
|
| 459 |
-
tid = str(tid)
|
| 460 |
-
history = t_state.get(tid, {}).get("history", [])
|
| 461 |
-
choices = [(v["title"], k) for k, v in t_state.items()]
|
| 462 |
-
upd = gr.update(value=tid, choices=choices)
|
| 463 |
-
return history, tid, upd, upd
|
| 464 |
-
|
| 465 |
-
def session_import_handler(file):
|
| 466 |
-
if not file: return [], {}, None, gr.update(), gr.update()
|
| 467 |
-
with open(file.name, "r") as f: data = json.load(f)
|
| 468 |
-
imported_threads = data.get("threads", {})
|
| 469 |
-
active_id = data.get("active_id", list(imported_threads.keys())[0] if imported_threads else None)
|
| 470 |
-
history = imported_threads.get(active_id, {}).get("history", []) if active_id else []
|
| 471 |
-
choices = [(v["title"], k) for k, v in imported_threads.items()]
|
| 472 |
-
upd = gr.update(choices=choices, value=active_id)
|
| 473 |
-
return history, imported_threads, active_id, upd, upd
|
| 474 |
-
|
| 475 |
-
def session_export_handler(chatbot_val, threads, active_id):
|
| 476 |
-
export_data = {"threads": threads, "active_id": active_id}
|
| 477 |
-
path = "sage_session_export.json"
|
| 478 |
-
with open(path, "w") as f: json.dump(export_data, f, indent=2)
|
| 479 |
-
return path
|
| 480 |
-
|
| 481 |
-
def build_demo() -> gr.Blocks:
|
| 482 |
-
initial_thread_id = str(uuid.uuid4())
|
| 483 |
-
with gr.Blocks(title="Gemma 3 Sage v6.5 SP1", theme="soft", css=PREMIUM_CSS) as demo:
|
| 484 |
-
threads_state = gr.State({initial_thread_id: {"title": "New Chat", "history": []}})
|
| 485 |
-
active_thread_id = gr.State(initial_thread_id)
|
| 486 |
-
vector_store_state = gr.State(None)
|
| 487 |
-
mongo_handler_state = gr.State(None)
|
| 488 |
-
|
| 489 |
-
with gr.Row(elem_classes="header-tray"):
|
| 490 |
-
gr.Markdown("# 🌌 Gemma 3 Sage <small>v6.5 SP1</small>")
|
| 491 |
-
|
| 492 |
-
with gr.Row():
|
| 493 |
-
# Desktop Sidebar (Radio List)
|
| 494 |
-
with gr.Column(scale=1, variant="panel", elem_classes="sidebar-panel glass-panel desktop-only"):
|
| 495 |
-
gr.Markdown("### 🕒 Recent Chats")
|
| 496 |
-
# Using Radio as a list selector
|
| 497 |
-
thread_list = gr.Radio(choices=[(f"New Chat", initial_thread_id)], value=initial_thread_id, label=None, interactive=True, container=False)
|
| 498 |
-
new_thread_btn = gr.Button("➕ New Conversation", variant="secondary")
|
| 499 |
-
|
| 500 |
-
with gr.Column(scale=4):
|
| 501 |
-
with gr.Tabs() as tabs:
|
| 502 |
-
with gr.Tab("💬 Live Conversation", id=0, elem_classes="glass-panel"):
|
| 503 |
-
|
| 504 |
-
# Mobile Menu (Accordion + Dropdown)
|
| 505 |
-
with gr.Accordion("🕒 Conversations (Mobile)", open=False, visible=True, elem_classes="mobile-only") as mobile_sessions:
|
| 506 |
-
m_thread_list = gr.Dropdown(choices=[("New Chat", initial_thread_id)], value=initial_thread_id, label="Select Session")
|
| 507 |
-
m_new_btn = gr.Button("➕ New Conversation", variant="secondary")
|
| 508 |
-
|
| 509 |
-
chatbot = gr.Chatbot(label="Sage", type="messages", height=600, show_label=False, autoscroll=False)
|
| 510 |
-
with gr.Row():
|
| 511 |
-
msg_textbox = gr.Textbox(placeholder="Whisper your heart or type...", label=None, scale=8, container=False)
|
| 512 |
-
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 513 |
-
# Moved Short Answer checkbox here for visibility
|
| 514 |
-
with gr.Row():
|
| 515 |
-
short_ans_cb = gr.Checkbox(label="Short Answers", value=False)
|
| 516 |
-
with gr.Row():
|
| 517 |
-
stream_state = gr.State({"buffer": [], "silence_counter": 0, "is_speaking": False})
|
| 518 |
-
audio_input = gr.Audio(label="Voice", sources="microphone", type="numpy", streaming=True)
|
| 519 |
-
processed_audio, audio_output = gr.State(None), gr.Audio(label="Sage Voice", autoplay=True, visible=False)
|
| 520 |
-
with gr.Row(elem_classes="glass-panel"):
|
| 521 |
-
export_btn = gr.Button("📤 Export Session", variant="secondary", size="sm")
|
| 522 |
-
import_file = gr.File(label="Import", file_count="single", height=60)
|
| 523 |
-
export_file = gr.File(label="Download", interactive=False, visible=False)
|
| 524 |
-
|
| 525 |
-
with gr.Tab("📚 Sacred Knowledge", id=1, elem_classes="glass-panel"):
|
| 526 |
-
file_uploader = gr.File(label="Upload", file_count="multiple", type="filepath")
|
| 527 |
-
index_button = gr.Button("🔄 Sync Index", variant="primary")
|
| 528 |
-
index_status = gr.Markdown("Bereit.")
|
| 529 |
-
with gr.Accordion("⚙️ MongoDB Settings", open=False):
|
| 530 |
-
mongo_uri = gr.Textbox(label="URI", value="mongodb://localhost:27017/")
|
| 531 |
-
mongo_db = gr.Textbox(label="DB", value="rag_db")
|
| 532 |
-
mongo_coll = gr.Textbox(label="Coll", value="gemma_chunks")
|
| 533 |
-
use_mongo_cb = gr.Checkbox(label="Sync to Mongo", value=True)
|
| 534 |
-
clear_mongo_btn = gr.Button("🗑️ Clear Mongo")
|
| 535 |
-
clear_idx_btn = gr.Button("🧹 Clear FAISS", variant="stop")
|
| 536 |
-
|
| 537 |
-
clear_mongo_btn.click(lambda u, d, c: MongoDBHandler(u, d, c).connect() and MongoDBHandler(u, d, c).clear() or "Mongo geleert", [mongo_uri, mongo_db, mongo_coll], index_status)
|
| 538 |
-
|
| 539 |
-
audio_input.stream(stream_handler, [audio_input, stream_state], [stream_state, processed_audio])
|
| 540 |
-
processed_audio.change(voice_chat_wrapper, [processed_audio, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output])
|
| 541 |
-
msg_textbox.submit(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
|
| 542 |
-
submit_btn.click(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
|
| 543 |
-
new_thread_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, thread_list, chatbot])
|
| 544 |
-
m_new_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, m_thread_list, chatbot])
|
| 545 |
-
thread_list.change(switch_thread, [thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
|
| 546 |
-
m_thread_list.change(switch_thread, [m_thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
|
| 547 |
-
index_button.click(index_files, [file_uploader, mongo_uri, mongo_db, mongo_coll, use_mongo_cb, vector_store_state, mongo_handler_state], [index_status, vector_store_state, mongo_handler_state], show_progress="full")
|
| 548 |
-
clear_idx_btn.click(clear_index, outputs=[index_status, vector_store_state, mongo_handler_state], show_progress="full")
|
| 549 |
-
import_file.change(session_import_handler, import_file, [chatbot, threads_state, active_thread_id, thread_list, m_thread_list], show_progress="full")
|
| 550 |
-
export_btn.click(session_export_handler, [chatbot, threads_state, active_thread_id], export_file, show_progress="full").then(lambda: gr.update(visible=True), None, export_file)
|
| 551 |
-
return demo
|
| 552 |
|
| 553 |
if __name__ == "__main__":
|
| 554 |
-
get_llm()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app_module import get_llm, build_demo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import time
|
| 5 |
+
import re
|
| 6 |
+
import codecs
|
| 7 |
+
import uuid
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import tempfile
|
| 11 |
+
import numpy as np
|
| 12 |
+
import scipy.io.wavfile as wavfile
|
| 13 |
+
import asyncio
|
| 14 |
+
import warnings
|
| 15 |
+
from typing import List, Tuple, Generator, Dict
|
| 16 |
+
from threading import Thread
|
| 17 |
+
|
| 18 |
+
# ML / Transformers
|
| 19 |
+
import transformers
|
| 20 |
+
transformers.utils.logging.set_verbosity_error()
|
| 21 |
+
warnings.filterwarnings("ignore", category=UserWarning, module="gradio.components.dropdown")
|
| 22 |
+
from transformers import AutoProcessor, Gemma3ForConditionalGeneration, TextIteratorStreamer
|
| 23 |
+
|
| 24 |
+
# --- Logging Setup ---
|
| 25 |
+
# Set root logger to ERROR to suppress external library noise
|
| 26 |
+
logging.basicConfig(level=logging.ERROR, format='%(name)s [%(levelname)s] %(message)s')
|
| 27 |
+
|
| 28 |
+
# Specific library suppressions
|
| 29 |
+
for lib in ["transformers", "accelerate", "httpx", "gradio", "langchain"]:
|
| 30 |
+
logging.getLogger(lib).setLevel(logging.ERROR)
|
| 31 |
+
|
| 32 |
+
# Application-level logger
|
| 33 |
+
logger = logging.getLogger("app")
|
| 34 |
+
logger.setLevel(logging.DEBUG)
|
| 35 |
+
logger.propagate = False # DO NOT propagate to root to avoid double-logging or filtering
|
| 36 |
+
ch = logging.StreamHandler()
|
| 37 |
+
ch.setLevel(logging.DEBUG)
|
| 38 |
+
ch.setFormatter(logging.Formatter('[app] [%(levelname)s] %(message)s'))
|
| 39 |
+
logger.addHandler(ch)
|
| 40 |
+
|
| 41 |
+
# --------------------------------------------------------------------
|
| 42 |
+
# Konfiguration & Globale States
|
| 43 |
+
# --------------------------------------------------------------------
|
| 44 |
+
EMBED_MODEL_ID = "google/embeddinggemma-300m"
|
| 45 |
+
LLM_MODEL_ID = "google/gemma-3-4b-it"
|
| 46 |
+
|
| 47 |
+
EMBEDDING_FUNCTION = None
|
| 48 |
+
LLM_MODEL = None
|
| 49 |
+
LLM_PROCESSOR = None
|
| 50 |
+
|
| 51 |
+
# --- UI Premium Aesthetics ---
|
| 52 |
+
PREMIUM_CSS = """
|
| 53 |
+
.glass-panel {
|
| 54 |
+
background: rgba(255, 255, 255, 0.05) !important;
|
| 55 |
+
backdrop-filter: blur(10px) !important;
|
| 56 |
+
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 57 |
+
border-radius: 15px !important;
|
| 58 |
+
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37) !important;
|
| 59 |
+
}
|
| 60 |
+
.sidebar-panel {
|
| 61 |
+
border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 62 |
+
height: 100vh;
|
| 63 |
+
}
|
| 64 |
+
border-bottom: 2px solid #0f3460;
|
| 65 |
+
}
|
| 66 |
+
.desktop-only { display: block; }
|
| 67 |
+
.mobile-only { display: none; }
|
| 68 |
+
@media (max-width: 768px) {
|
| 69 |
+
.desktop-only { display: none !important; }
|
| 70 |
+
.mobile-only { display: block !important; }
|
| 71 |
+
.sidebar-panel { display: none !important; }
|
| 72 |
+
}
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
from pypdf import PdfReader
|
| 77 |
+
from langchain_community.vectorstores import FAISS
|
| 78 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 79 |
+
from langchain_core.documents import Document
|
| 80 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 81 |
+
from mongochain import MongoDBHandler
|
| 82 |
+
except ImportError:
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
# Spiritual Integration
|
| 86 |
+
try:
|
| 87 |
+
from spiritual_bridge import get_oracle_data
|
| 88 |
+
except ImportError:
|
| 89 |
+
get_oracle_data = None
|
| 90 |
+
|
| 91 |
+
# --- Model Loading ---
|
| 92 |
+
def get_device() -> torch.device:
|
| 93 |
+
if torch.cuda.is_available(): return torch.device("cuda")
|
| 94 |
+
return torch.device("cpu")
|
| 95 |
+
|
| 96 |
+
def get_embedding_function():
|
| 97 |
+
global EMBEDDING_FUNCTION
|
| 98 |
+
if EMBEDDING_FUNCTION is None:
|
| 99 |
+
device = get_device()
|
| 100 |
+
logger.debug(f"Initialisiere Embedding-Modell '{EMBED_MODEL_ID}' auf Device '{device}'.")
|
| 101 |
+
EMBEDDING_FUNCTION = HuggingFaceEmbeddings(
|
| 102 |
+
model_name=EMBED_MODEL_ID,
|
| 103 |
+
model_kwargs={'device': device}
|
| 104 |
+
)
|
| 105 |
+
logger.debug("Embedding-Modell erfolgreich initialisiert.")
|
| 106 |
+
return EMBEDDING_FUNCTION
|
| 107 |
+
|
| 108 |
+
def get_llm():
|
| 109 |
+
global LLM_MODEL, LLM_PROCESSOR
|
| 110 |
+
if LLM_MODEL is None or LLM_PROCESSOR is None:
|
| 111 |
+
device = get_device()
|
| 112 |
+
logger.debug(f"Initialisiere LLM '{LLM_MODEL_ID}' auf Device '{device}'.")
|
| 113 |
+
dtype = torch.bfloat16 if "cuda" in device.type else torch.float32
|
| 114 |
+
LLM_MODEL = Gemma3ForConditionalGeneration.from_pretrained(
|
| 115 |
+
LLM_MODEL_ID,
|
| 116 |
+
dtype=dtype,
|
| 117 |
+
device_map="auto",
|
| 118 |
+
).eval()
|
| 119 |
+
LLM_PROCESSOR = AutoProcessor.from_pretrained(LLM_MODEL_ID)
|
| 120 |
+
logger.debug("LLM und Prozessor erfolgreich initialisiert.")
|
| 121 |
+
return LLM_MODEL, LLM_PROCESSOR
|
| 122 |
+
|
| 123 |
+
# --- Language Detection ---
|
| 124 |
+
def detect_language(text: str) -> str:
|
| 125 |
+
if not text or len(text) < 3: return "English"
|
| 126 |
+
model, processor = get_llm()
|
| 127 |
+
prompt = f"Detect the language of the following text and return ONLY the language name (e.g., 'English', 'German', 'French'):\n\n\"{text}\""
|
| 128 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 129 |
+
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
|
| 130 |
+
with torch.no_grad():
|
| 131 |
+
outputs = model.generate(inputs, max_new_tokens=20, do_sample=False)
|
| 132 |
+
raw_output = processor.batch_decode(outputs[:, inputs.shape[1]:], skip_special_tokens=True)[0].strip()
|
| 133 |
+
logger.debug(f"DEBUG: Raw Language Detection Output: '{raw_output}'")
|
| 134 |
+
|
| 135 |
+
keywords = ["English", "German", "French", "Spanish", "Italian", "Dutch", "Russian", "Chinese", "Japanese"]
|
| 136 |
+
for k in keywords:
|
| 137 |
+
if k.lower() in raw_output.lower():
|
| 138 |
+
logger.debug(f"DEBUG: Detected User Language (Normalized): '{k}'")
|
| 139 |
+
return k
|
| 140 |
+
return "English"
|
| 141 |
+
|
| 142 |
+
# --- Document Handling ---
|
| 143 |
+
def extract_text_from_file(path: str) -> str:
|
| 144 |
+
ext = os.path.splitext(path)[1].lower()
|
| 145 |
+
if ext in [".txt", ".md", ".markdown"]:
|
| 146 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
|
| 147 |
+
if ext == ".pdf":
|
| 148 |
+
text_parts = []
|
| 149 |
+
try:
|
| 150 |
+
reader = PdfReader(path)
|
| 151 |
+
for page in reader.pages:
|
| 152 |
+
page_text = page.extract_text()
|
| 153 |
+
if page_text: text_parts.append(page_text)
|
| 154 |
+
return "\n\n".join(text_parts)
|
| 155 |
+
except Exception as e:
|
| 156 |
+
logger.error(f"Error reading PDF {path}: {e}"); return ""
|
| 157 |
+
try:
|
| 158 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read()
|
| 159 |
+
except Exception: return ""
|
| 160 |
+
|
| 161 |
+
def get_text_splitter() -> RecursiveCharacterTextSplitter:
|
| 162 |
+
return RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, length_function=len)
|
| 163 |
+
|
| 164 |
+
# --- RAG Core ---
|
| 165 |
+
def index_files(file_paths, mongo_uri, db_name, coll_name, use_mongo, vs_state, mh_state, progress=gr.Progress(track_tqdm=True)):
|
| 166 |
+
if not file_paths: return "Keine Dateien zum Indexieren ausgewählt.", vs_state, mh_state
|
| 167 |
+
|
| 168 |
+
logger.debug(f"Indexierung gestartet für {len(file_paths)} Datei(en).")
|
| 169 |
+
embed_fn = get_embedding_function()
|
| 170 |
+
splitter = get_text_splitter()
|
| 171 |
+
documents = []
|
| 172 |
+
|
| 173 |
+
for path in progress.tqdm(file_paths, desc="1/2: Dateien verarbeiten"):
|
| 174 |
+
if path is None: continue
|
| 175 |
+
text = extract_text_from_file(path)
|
| 176 |
+
if not text.strip(): continue
|
| 177 |
+
chunks = splitter.split_text(text)
|
| 178 |
+
source_name = os.path.basename(path)
|
| 179 |
+
for c in chunks:
|
| 180 |
+
documents.append(Document(page_content=c, metadata={"source": source_name}))
|
| 181 |
+
|
| 182 |
+
logger.debug(f"Total chunks created: {len(documents)}")
|
| 183 |
+
if not documents: return "Kein Text zum Indexieren gefunden.", vs_state, mh_state
|
| 184 |
+
|
| 185 |
+
progress(0.7, desc="2/2: Indexing...")
|
| 186 |
+
new_vs = FAISS.from_documents(documents, embed_fn)
|
| 187 |
+
if vs_state:
|
| 188 |
+
vs_state.merge_from(new_vs)
|
| 189 |
+
else:
|
| 190 |
+
vs_state = new_vs
|
| 191 |
+
|
| 192 |
+
mh_state = None
|
| 193 |
+
if use_mongo:
|
| 194 |
+
try:
|
| 195 |
+
mh_state = MongoDBHandler(uri=mongo_uri, db_name=db_name, collection_name=coll_name)
|
| 196 |
+
mh_state.connect()
|
| 197 |
+
logger.debug(f"Pushe {len(documents)} Chunks nach MongoDB...")
|
| 198 |
+
for doc in documents:
|
| 199 |
+
mh_state.insert_chunk(doc.page_content, doc.metadata)
|
| 200 |
+
logger.debug("MongoDB-Sync abgeschlossen.")
|
| 201 |
+
except Exception as e:
|
| 202 |
+
logger.error(f"Mongo Error: {e}")
|
| 203 |
+
|
| 204 |
+
logger.debug(f"Indexierung abgeschlossen. Gesamt: {vs_state.index.ntotal} Chunks.")
|
| 205 |
+
return f"Index aktualisiert: {vs_state.index.ntotal} Chunks insgesamt.", vs_state, mh_state
|
| 206 |
+
|
| 207 |
+
def clear_index():
|
| 208 |
+
import gc; gc.collect()
|
| 209 |
+
logger.debug("Vektor-Index wurde geleert.")
|
| 210 |
+
return "Index geleert.", None, None
|
| 211 |
+
|
| 212 |
+
def retrieve_relevant_chunks(query, vs_state, mh_state, top_k=3):
|
| 213 |
+
if not vs_state: return []
|
| 214 |
+
logger.debug(f"Suche in FAISS: '{query}'")
|
| 215 |
+
docs = vs_state.similarity_search(query, k=top_k)
|
| 216 |
+
return [{"content": d.page_content, "source": d.metadata.get("source", "Unknown")} for d in docs]
|
| 217 |
+
|
| 218 |
+
def build_rag_prompt(user_question: str, retrieved_chunks: List[Dict]) -> str:
|
| 219 |
+
if not retrieved_chunks: context_str = "Kein relevanter Kontext gefunden."
|
| 220 |
+
else:
|
| 221 |
+
context_parts = [f"[{i}] (Quelle: {ch['source']}): \"{ch['content']}\"" for i, ch in enumerate(retrieved_chunks, 1)]
|
| 222 |
+
context_str = "\n\n".join(context_parts)
|
| 223 |
+
return (f"Beantworte die Benutzerfrage nur basierend auf dem Kontext.\n\n"
|
| 224 |
+
f"--- Kontext ---\n{context_str}\n\n"
|
| 225 |
+
f"--- Frage ---\n{user_question}\n\n"
|
| 226 |
+
f"--- Antwort ---")
|
| 227 |
+
|
| 228 |
+
# --- Agent System ---
|
| 229 |
+
def build_agent_prompt(query, context, history, language="English", short_answers=False):
|
| 230 |
+
context_str = "\n".join([f"- {c['content']} (Source: {c['source']})" for i, c in enumerate(context)])
|
| 231 |
+
|
| 232 |
+
style_instruction = "Be concise." if short_answers else ""
|
| 233 |
+
|
| 234 |
+
system = f"""You are Sage 6.5, a spiritual AI guide.
|
| 235 |
+
Respond in {language}. {style_instruction}
|
| 236 |
+
If you need to use a tool, you MUST use the following JSON format inside <tool_call> tags:
|
| 237 |
+
<tool_call>{{"name": "tool_name", "arguments": {{"arg1": "val1"}}}}</tool_call>
|
| 238 |
+
|
| 239 |
+
Available Tools:
|
| 240 |
+
1. oracle_consultation: Consult the archive for deep wisdom. Arguments: {{"topic": "str", "name": "str (Optional. Use ONLY if the user explicitly stated their name, otherwise omit)"}}
|
| 241 |
+
"""
|
| 242 |
+
return system + f"\n\nContext:\n{context_str}\n\nUser Question: {query}"
|
| 243 |
+
|
| 244 |
+
def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
|
| 245 |
+
model, processor = get_llm()
|
| 246 |
+
lang = user_lang if user_lang else detect_language(query)
|
| 247 |
+
context = retrieve_relevant_chunks(query, vs_state, mh_state)
|
| 248 |
+
prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
|
| 249 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 250 |
+
|
| 251 |
+
logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
|
| 252 |
+
|
| 253 |
+
def chat_agent_stream(query, history, vs_state, mh_state, user_lang=None, short_answers=False):
|
| 254 |
+
model, processor = get_llm()
|
| 255 |
+
lang = user_lang if user_lang else detect_language(query)
|
| 256 |
+
context = retrieve_relevant_chunks(query, vs_state, mh_state)
|
| 257 |
+
prompt = build_agent_prompt(query, context, history, language=lang, short_answers=short_answers)
|
| 258 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 259 |
+
|
| 260 |
+
logger.info(f"[AGENT] 🏁 Starting Agent Loop for Query: '{query}' (Lang: {lang})")
|
| 261 |
+
|
| 262 |
+
max_turns = 3
|
| 263 |
+
for turn in range(max_turns):
|
| 264 |
+
logger.info(f"[AGENT] 🔄 Turn {turn+1}/{max_turns}")
|
| 265 |
+
|
| 266 |
+
input_ids = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
|
| 267 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 268 |
+
|
| 269 |
+
gen_kwargs = {"input_ids": input_ids, "streamer": streamer, "max_new_tokens": 512, "do_sample": False}
|
| 270 |
+
thread = Thread(target=model.generate, kwargs=gen_kwargs)
|
| 271 |
+
thread.start()
|
| 272 |
+
|
| 273 |
+
current_turn_text = ""
|
| 274 |
+
# We yield a TUPLE: (accumulated_text_for_THIS_turn, is_final)
|
| 275 |
+
# But wait, the wrapper needs to handle new messages.
|
| 276 |
+
# Strategy: Yield just the text of THIS turn. Wrapper handles appending to a NEW history item each turn.
|
| 277 |
+
|
| 278 |
+
logger.info("[AGENT] ⏳ Streaming response...")
|
| 279 |
+
for new_text in streamer:
|
| 280 |
+
current_turn_text += new_text
|
| 281 |
+
clean_chunk = re.sub(r"<tool_call>.*?</tool_call>", "", current_turn_text, flags=re.DOTALL)
|
| 282 |
+
yield clean_chunk.strip()
|
| 283 |
+
|
| 284 |
+
logger.info(f"[AGENT] 🛑 Raw Model Output: {current_turn_text}")
|
| 285 |
+
|
| 286 |
+
# Tool Detection
|
| 287 |
+
tool_match = re.search(r"<tool_call>(.*?)</tool_call>", current_turn_text, re.DOTALL)
|
| 288 |
+
if tool_match:
|
| 289 |
+
# If tool found, this turn is OVER regarding user output.
|
| 290 |
+
# We yield a special signal to indicate "End of Message, Start Next Logic"?
|
| 291 |
+
# actually, if we yield, the wrapper updates history[-1].
|
| 292 |
+
# If we want a NEW message, we need to tell wrapper to append.
|
| 293 |
+
# Simplified: Use a separator? No, wrapper loop is easier.
|
| 294 |
+
|
| 295 |
+
# For now, let's keep the generator simple.
|
| 296 |
+
# It yields text updates for the CURRENT turn.
|
| 297 |
+
# Once loop breaks (tool found), we start next turn.
|
| 298 |
+
# BUT: How to tell wrapper "This turn is done, start a new bubble"?
|
| 299 |
+
# Generator yields: {"text": "...", "new_bubble": True/False}
|
| 300 |
+
|
| 301 |
+
try:
|
| 302 |
+
tool_data = json.loads(tool_match.group(1))
|
| 303 |
+
logger.info(f"[AGENT] 🛠️ Tool Call Detected: {tool_data}")
|
| 304 |
+
|
| 305 |
+
tool_name = tool_data.get("name")
|
| 306 |
+
tool_args = tool_data.get("arguments", {})
|
| 307 |
+
|
| 308 |
+
if tool_name == "oracle_consultation":
|
| 309 |
+
topic = tool_args.get("topic", "")
|
| 310 |
+
|
| 311 |
+
# Name Handling: Use provided name or default to 'Seeker'
|
| 312 |
+
req_name = tool_args.get("name", "").strip()
|
| 313 |
+
effective_name = req_name if req_name else "Seeker"
|
| 314 |
+
|
| 315 |
+
logger.info(f"[AGENT] 🔮 Executing Oracle with topic: '{topic}' for '{effective_name}'")
|
| 316 |
+
if get_oracle_data:
|
| 317 |
+
try:
|
| 318 |
+
# Call backend
|
| 319 |
+
oracle_raw = get_oracle_data(name=effective_name, topic=topic, date_str="")
|
| 320 |
+
|
| 321 |
+
# FILTERING LOGIC (User Request: Only 3 sources, no BOS API/ELS)
|
| 322 |
+
# We construct a filtered dictionary
|
| 323 |
+
filtered_result = {
|
| 324 |
+
"wisdom_nodes": oracle_raw.get("wisdom_nodes", [])
|
| 325 |
+
}
|
| 326 |
+
# If wisdom_nodes is missing/empty, maybe keep raw but warn?
|
| 327 |
+
# Use strict filtering as requested.
|
| 328 |
+
|
| 329 |
+
tool_result = json.dumps(filtered_result, indent=2)
|
| 330 |
+
logger.info(f"[AGENT] ✅ Oracle Result Obtained (Filtered Size: {len(tool_result)} bytes)")
|
| 331 |
+
except Exception as e:
|
| 332 |
+
logger.error(f"[AGENT] ❌ Oracle Backend Error: {e}")
|
| 333 |
+
tool_result = f"Error executing oracle: {str(e)}"
|
| 334 |
+
else:
|
| 335 |
+
logger.warning("[AGENT] ⚠️ Oracle module not available")
|
| 336 |
+
tool_result = "Oracle module not available."
|
| 337 |
+
else:
|
| 338 |
+
logger.warning(f"[AGENT] ⚠️ Unknown tool requested: {tool_name}")
|
| 339 |
+
tool_result = f"Unknown tool: {tool_name}"
|
| 340 |
+
|
| 341 |
+
messages.append({"role": "assistant", "content": [{"type": "text", "text": current_turn_text}]})
|
| 342 |
+
|
| 343 |
+
tool_injection = f"""<tool_result>{tool_result}</tool_result>
|
| 344 |
+
Now interpret this result soulfully and poetically for the user. Do not mention JSON.
|
| 345 |
+
IMPORTANT: Connect this smoothly to your previous statement. Ensure a fluid, cohesive narrative without abrupt jumps."""
|
| 346 |
+
|
| 347 |
+
logger.info("[AGENT] 💉 Injecting Tool Result into context for interpretation...")
|
| 348 |
+
messages.append({"role": "user", "content": [{"type": "text", "text": tool_injection}]})
|
| 349 |
+
|
| 350 |
+
# Yield a special marker to say "Turn Finished"
|
| 351 |
+
yield "__TURN_END__"
|
| 352 |
+
continue
|
| 353 |
+
except Exception as e:
|
| 354 |
+
logger.error(f"[AGENT] 💥 Tool parsing/logic crash: {e}")
|
| 355 |
+
break
|
| 356 |
+
else:
|
| 357 |
+
logger.info("[AGENT] ✨ No tool calls. Finalizing response.")
|
| 358 |
+
break
|
| 359 |
+
|
| 360 |
+
# --- Voice Engine ---
|
| 361 |
+
async def generate_speech(text: str, lang: str = "English"):
|
| 362 |
+
import edge_tts
|
| 363 |
+
VOICES = {"English": "en-US-GuyNeural", "German": "de-DE-ConradNeural", "French": "fr-FR-HenriNeural"}
|
| 364 |
+
voice = VOICES.get(lang, VOICES["English"])
|
| 365 |
+
logger.debug(f"TRACE: generate_speech() called. Text len: {len(text)}, Lang: {lang}")
|
| 366 |
+
temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
|
| 367 |
+
communicate = edge_tts.Communicate(text, voice)
|
| 368 |
+
await communicate.save(temp_wav.name)
|
| 369 |
+
return temp_wav.name
|
| 370 |
+
|
| 371 |
+
def transcribe_audio(path: str):
|
| 372 |
+
logger.debug(f"TRACE: transcribe_audio() called with path: {path}")
|
| 373 |
+
return "Transcribed text"
|
| 374 |
+
|
| 375 |
+
# --- Gradio Wrappers ---
|
| 376 |
+
def voice_chat_wrapper(audio_path, history, threads, tid, vs_state, mh_state, short_answers):
|
| 377 |
+
if audio_path is None: yield history, threads, gr.update(), gr.update(), None; return
|
| 378 |
+
text = transcribe_audio(audio_path)
|
| 379 |
+
detected_lang = detect_language(text)
|
| 380 |
+
final_history, final_threads, final_update = history, threads, gr.update()
|
| 381 |
+
if text:
|
| 382 |
+
gen = chat_wrapper(text, history, threads, tid, vs_state, mh_state, short_answers=short_answers, lang=detected_lang)
|
| 383 |
+
for h, t, tr1, tr2, _ in gen:
|
| 384 |
+
final_history, final_threads, final_update = h, t, tr1
|
| 385 |
+
yield h, t, tr1, tr2, None
|
| 386 |
+
import asyncio
|
| 387 |
+
last_msg = final_history[-1]["content"] if final_history else ""
|
| 388 |
+
if last_msg:
|
| 389 |
+
voice_path = asyncio.run(generate_speech(last_msg, lang=detected_lang))
|
| 390 |
+
yield final_history, final_threads, final_update, final_update, voice_path
|
| 391 |
+
else:
|
| 392 |
+
yield final_history, final_threads, final_update, final_update, None
|
| 393 |
+
|
| 394 |
+
def chat_wrapper(message, history, threads, tid, vs_state, mh_state, short_answers=False, lang=None):
|
| 395 |
+
if not message.strip():
|
| 396 |
+
upd = gr.update(choices=[(v["title"], k) for k, v in threads.items()], value=tid)
|
| 397 |
+
yield history, threads, upd, upd, None
|
| 398 |
+
return
|
| 399 |
+
history.append({"role": "user", "content": message})
|
| 400 |
+
yield history, threads, gr.update(), gr.update(), None
|
| 401 |
+
|
| 402 |
+
# Start first response bubble
|
| 403 |
+
history.append({"role": "assistant", "content": ""})
|
| 404 |
+
|
| 405 |
+
for response_part in chat_agent_stream(message, history[:-2], vs_state, mh_state, user_lang=lang, short_answers=short_answers):
|
| 406 |
+
if response_part == "__TURN_END__":
|
| 407 |
+
# Start NEW bubble for next turn
|
| 408 |
+
history.append({"role": "assistant", "content": ""})
|
| 409 |
+
yield history, threads, gr.update(), gr.update(), None
|
| 410 |
+
else:
|
| 411 |
+
history[-1]["content"] = response_part
|
| 412 |
+
yield history, threads, gr.update(), gr.update(), None
|
| 413 |
+
|
| 414 |
+
# Cleanup empty bubble if exists (rare edge case)
|
| 415 |
+
if not history[-1]["content"]: history.pop()
|
| 416 |
+
|
| 417 |
+
if tid not in threads: threads[tid] = {"title": "Conversation", "history": []}
|
| 418 |
+
threads[tid]["history"] = history
|
| 419 |
+
if len(history) <= 2:
|
| 420 |
+
threads[tid]["title"] = (message[:25] + "..") if message else "Conversation"
|
| 421 |
+
choices = [(v["title"], k) for k, v in threads.items()]
|
| 422 |
+
upd = gr.update(choices=choices, value=tid)
|
| 423 |
+
yield history, threads, upd, upd, None
|
| 424 |
+
|
| 425 |
+
def stream_handler(stream, state):
|
| 426 |
+
if stream is None: return state, None
|
| 427 |
+
sr, y = stream
|
| 428 |
+
if y is None or len(y) == 0: return state, None
|
| 429 |
+
y = y.astype(np.float32)
|
| 430 |
+
y = y / np.max(np.abs(y)) if np.max(np.abs(y)) > 0 else y
|
| 431 |
+
rms = np.sqrt(np.mean(y**2))
|
| 432 |
+
SILENCE_THRESHOLD, SILENCE_CHUNKS = 0.01, 20
|
| 433 |
+
if state is None: state = {"buffer": [], "silence_counter": 0, "is_speaking": False}
|
| 434 |
+
state["buffer"].append((sr, stream[1]))
|
| 435 |
+
if rms > SILENCE_THRESHOLD:
|
| 436 |
+
state["is_speaking"], state["silence_counter"] = True, 0
|
| 437 |
+
elif state["is_speaking"]:
|
| 438 |
+
state["silence_counter"] += 1
|
| 439 |
+
if state["is_speaking"] and state["silence_counter"] > SILENCE_CHUNKS:
|
| 440 |
+
full_audio = np.concatenate([c[1] for c in state["buffer"]])
|
| 441 |
+
sr_final = state["buffer"][0][0]
|
| 442 |
+
temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
|
| 443 |
+
wavfile.write(temp_wav.name, sr_final, full_audio)
|
| 444 |
+
return {"buffer": [], "silence_counter": 0, "is_speaking": False}, temp_wav.name
|
| 445 |
+
return state, None
|
| 446 |
+
|
| 447 |
+
# --- INTERNAL CALLBACKS ---
|
| 448 |
+
def create_new_thread_callback(threads):
|
| 449 |
+
nid = str(uuid.uuid4())
|
| 450 |
+
threads[nid] = {"title": "New Conversation", "history": []}
|
| 451 |
+
choices = [(v["title"], k) for k, v in threads.items()]
|
| 452 |
+
return threads, nid, gr.update(choices=choices, value=nid), []
|
| 453 |
+
|
| 454 |
+
def switch_thread(tid, t_state):
|
| 455 |
+
logger.debug(f"TRACE: switch_thread() called for tid: {tid}")
|
| 456 |
+
if isinstance(tid, list):
|
| 457 |
+
if not tid: return [], gr.update(), gr.update(), gr.update()
|
| 458 |
+
tid = tid[0]
|
| 459 |
+
tid = str(tid)
|
| 460 |
+
history = t_state.get(tid, {}).get("history", [])
|
| 461 |
+
choices = [(v["title"], k) for k, v in t_state.items()]
|
| 462 |
+
upd = gr.update(value=tid, choices=choices)
|
| 463 |
+
return history, tid, upd, upd
|
| 464 |
+
|
| 465 |
+
def session_import_handler(file):
|
| 466 |
+
if not file: return [], {}, None, gr.update(), gr.update()
|
| 467 |
+
with open(file.name, "r") as f: data = json.load(f)
|
| 468 |
+
imported_threads = data.get("threads", {})
|
| 469 |
+
active_id = data.get("active_id", list(imported_threads.keys())[0] if imported_threads else None)
|
| 470 |
+
history = imported_threads.get(active_id, {}).get("history", []) if active_id else []
|
| 471 |
+
choices = [(v["title"], k) for k, v in imported_threads.items()]
|
| 472 |
+
upd = gr.update(choices=choices, value=active_id)
|
| 473 |
+
return history, imported_threads, active_id, upd, upd
|
| 474 |
+
|
| 475 |
+
def session_export_handler(chatbot_val, threads, active_id):
|
| 476 |
+
export_data = {"threads": threads, "active_id": active_id}
|
| 477 |
+
path = "sage_session_export.json"
|
| 478 |
+
with open(path, "w") as f: json.dump(export_data, f, indent=2)
|
| 479 |
+
return path
|
| 480 |
+
|
| 481 |
+
def build_demo() -> gr.Blocks:
|
| 482 |
+
initial_thread_id = str(uuid.uuid4())
|
| 483 |
+
with gr.Blocks(title="Gemma 3 Sage v6.5 SP1", theme="soft", css=PREMIUM_CSS) as demo:
|
| 484 |
+
threads_state = gr.State({initial_thread_id: {"title": "New Chat", "history": []}})
|
| 485 |
+
active_thread_id = gr.State(initial_thread_id)
|
| 486 |
+
vector_store_state = gr.State(None)
|
| 487 |
+
mongo_handler_state = gr.State(None)
|
| 488 |
+
|
| 489 |
+
with gr.Row(elem_classes="header-tray"):
|
| 490 |
+
gr.Markdown("# 🌌 Gemma 3 Sage <small>v6.5 SP1</small>")
|
| 491 |
+
|
| 492 |
+
with gr.Row():
|
| 493 |
+
# Desktop Sidebar (Radio List)
|
| 494 |
+
with gr.Column(scale=1, variant="panel", elem_classes="sidebar-panel glass-panel desktop-only"):
|
| 495 |
+
gr.Markdown("### 🕒 Recent Chats")
|
| 496 |
+
# Using Radio as a list selector
|
| 497 |
+
thread_list = gr.Radio(choices=[(f"New Chat", initial_thread_id)], value=initial_thread_id, label=None, interactive=True, container=False)
|
| 498 |
+
new_thread_btn = gr.Button("➕ New Conversation", variant="secondary")
|
| 499 |
+
|
| 500 |
+
with gr.Column(scale=4):
|
| 501 |
+
with gr.Tabs() as tabs:
|
| 502 |
+
with gr.Tab("💬 Live Conversation", id=0, elem_classes="glass-panel"):
|
| 503 |
+
|
| 504 |
+
# Mobile Menu (Accordion + Dropdown)
|
| 505 |
+
with gr.Accordion("🕒 Conversations (Mobile)", open=False, visible=True, elem_classes="mobile-only") as mobile_sessions:
|
| 506 |
+
m_thread_list = gr.Dropdown(choices=[("New Chat", initial_thread_id)], value=initial_thread_id, label="Select Session")
|
| 507 |
+
m_new_btn = gr.Button("➕ New Conversation", variant="secondary")
|
| 508 |
+
|
| 509 |
+
chatbot = gr.Chatbot(label="Sage", type="messages", height=600, show_label=False, autoscroll=False)
|
| 510 |
+
with gr.Row():
|
| 511 |
+
msg_textbox = gr.Textbox(placeholder="Whisper your heart or type...", label=None, scale=8, container=False)
|
| 512 |
+
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 513 |
+
# Moved Short Answer checkbox here for visibility
|
| 514 |
+
with gr.Row():
|
| 515 |
+
short_ans_cb = gr.Checkbox(label="Short Answers", value=False)
|
| 516 |
+
with gr.Row():
|
| 517 |
+
stream_state = gr.State({"buffer": [], "silence_counter": 0, "is_speaking": False})
|
| 518 |
+
audio_input = gr.Audio(label="Voice", sources="microphone", type="numpy", streaming=True)
|
| 519 |
+
processed_audio, audio_output = gr.State(None), gr.Audio(label="Sage Voice", autoplay=True, visible=False)
|
| 520 |
+
with gr.Row(elem_classes="glass-panel"):
|
| 521 |
+
export_btn = gr.Button("📤 Export Session", variant="secondary", size="sm")
|
| 522 |
+
import_file = gr.File(label="Import", file_count="single", height=60)
|
| 523 |
+
export_file = gr.File(label="Download", interactive=False, visible=False)
|
| 524 |
+
|
| 525 |
+
with gr.Tab("📚 Sacred Knowledge", id=1, elem_classes="glass-panel"):
|
| 526 |
+
file_uploader = gr.File(label="Upload", file_count="multiple", type="filepath")
|
| 527 |
+
index_button = gr.Button("🔄 Sync Index", variant="primary")
|
| 528 |
+
index_status = gr.Markdown("Bereit.")
|
| 529 |
+
with gr.Accordion("⚙️ MongoDB Settings", open=False):
|
| 530 |
+
mongo_uri = gr.Textbox(label="URI", value="mongodb://localhost:27017/")
|
| 531 |
+
mongo_db = gr.Textbox(label="DB", value="rag_db")
|
| 532 |
+
mongo_coll = gr.Textbox(label="Coll", value="gemma_chunks")
|
| 533 |
+
use_mongo_cb = gr.Checkbox(label="Sync to Mongo", value=True)
|
| 534 |
+
clear_mongo_btn = gr.Button("🗑️ Clear Mongo")
|
| 535 |
+
clear_idx_btn = gr.Button("🧹 Clear FAISS", variant="stop")
|
| 536 |
+
|
| 537 |
+
clear_mongo_btn.click(lambda u, d, c: MongoDBHandler(u, d, c).connect() and MongoDBHandler(u, d, c).clear() or "Mongo geleert", [mongo_uri, mongo_db, mongo_coll], index_status)
|
| 538 |
+
|
| 539 |
+
audio_input.stream(stream_handler, [audio_input, stream_state], [stream_state, processed_audio])
|
| 540 |
+
processed_audio.change(voice_chat_wrapper, [processed_audio, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output])
|
| 541 |
+
msg_textbox.submit(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
|
| 542 |
+
submit_btn.click(chat_wrapper, [msg_textbox, chatbot, threads_state, active_thread_id, vector_store_state, mongo_handler_state, short_ans_cb], [chatbot, threads_state, thread_list, m_thread_list, audio_output]).then(lambda: "", None, msg_textbox)
|
| 543 |
+
new_thread_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, thread_list, chatbot])
|
| 544 |
+
m_new_btn.click(create_new_thread_callback, [threads_state], [threads_state, active_thread_id, m_thread_list, chatbot])
|
| 545 |
+
thread_list.change(switch_thread, [thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
|
| 546 |
+
m_thread_list.change(switch_thread, [m_thread_list, threads_state], [chatbot, active_thread_id, thread_list, m_thread_list])
|
| 547 |
+
index_button.click(index_files, [file_uploader, mongo_uri, mongo_db, mongo_coll, use_mongo_cb, vector_store_state, mongo_handler_state], [index_status, vector_store_state, mongo_handler_state], show_progress="full")
|
| 548 |
+
clear_idx_btn.click(clear_index, outputs=[index_status, vector_store_state, mongo_handler_state], show_progress="full")
|
| 549 |
+
import_file.change(session_import_handler, import_file, [chatbot, threads_state, active_thread_id, thread_list, m_thread_list], show_progress="full")
|
| 550 |
+
export_btn.click(session_export_handler, [chatbot, threads_state, active_thread_id], export_file, show_progress="full").then(lambda: gr.update(visible=True), None, export_file)
|
| 551 |
+
return demo
|
| 552 |
+
|
| 553 |
+
|
tests/rag_reproduce_test.py
CHANGED
|
@@ -7,7 +7,7 @@ import time
|
|
| 7 |
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 8 |
sys.path.append(project_root)
|
| 9 |
|
| 10 |
-
from
|
| 11 |
index_files,
|
| 12 |
answer_with_rag,
|
| 13 |
get_embedding_function,
|
|
|
|
| 7 |
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 8 |
sys.path.append(project_root)
|
| 9 |
|
| 10 |
+
from app_module import (
|
| 11 |
index_files,
|
| 12 |
answer_with_rag,
|
| 13 |
get_embedding_function,
|
tests/suite_test.py
CHANGED
|
@@ -7,7 +7,7 @@ project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
|
| 7 |
sys.path.append(project_root)
|
| 8 |
|
| 9 |
# Import components to test
|
| 10 |
-
from
|
| 11 |
from mongochain import MongoDBHandler
|
| 12 |
|
| 13 |
class TestRAGFunctions(unittest.TestCase):
|
|
|
|
| 7 |
sys.path.append(project_root)
|
| 8 |
|
| 9 |
# Import components to test
|
| 10 |
+
from app_module import extract_text_from_file, get_text_splitter, Document
|
| 11 |
from mongochain import MongoDBHandler
|
| 12 |
|
| 13 |
class TestRAGFunctions(unittest.TestCase):
|
tests/test_accumulation_bug.py
CHANGED
|
@@ -1,15 +1,15 @@
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
-
from
|
| 4 |
import re
|
| 5 |
import json
|
| 6 |
|
| 7 |
class TestAccumulationBug(unittest.TestCase):
|
| 8 |
|
| 9 |
-
@patch('
|
| 10 |
-
@patch('
|
| 11 |
-
@patch('
|
| 12 |
-
@patch('
|
| 13 |
def test_multi_turn_accumulation(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 14 |
"""
|
| 15 |
Simulates:
|
|
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
+
from app_module import chat_agent_stream
|
| 4 |
import re
|
| 5 |
import json
|
| 6 |
|
| 7 |
class TestAccumulationBug(unittest.TestCase):
|
| 8 |
|
| 9 |
+
@patch('app_module.get_llm')
|
| 10 |
+
@patch('app_module.TextIteratorStreamer')
|
| 11 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 12 |
+
@patch('app_module.detect_language')
|
| 13 |
def test_multi_turn_accumulation(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 14 |
"""
|
| 15 |
Simulates:
|
tests/test_agent.py
CHANGED
|
@@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patch
|
|
| 6 |
# Ensure project root is in path
|
| 7 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 8 |
|
| 9 |
-
from
|
| 10 |
|
| 11 |
def test_build_agent_prompt_structure():
|
| 12 |
"""Verifies that the agent prompt contains the Proactivity Patch rules."""
|
|
|
|
| 6 |
# Ensure project root is in path
|
| 7 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 8 |
|
| 9 |
+
from app_module import build_agent_prompt, detect_language
|
| 10 |
|
| 11 |
def test_build_agent_prompt_structure():
|
| 12 |
"""Verifies that the agent prompt contains the Proactivity Patch rules."""
|
tests/test_agent_tools.py
CHANGED
|
@@ -2,7 +2,7 @@ import unittest
|
|
| 2 |
import json
|
| 3 |
import re
|
| 4 |
from unittest.mock import MagicMock, patch
|
| 5 |
-
from
|
| 6 |
|
| 7 |
# Import backend tool function to verify it exists
|
| 8 |
try:
|
|
@@ -30,7 +30,7 @@ class TestAgentTools(unittest.TestCase):
|
|
| 30 |
self.assertEqual(data["name"], "oracle_consultation")
|
| 31 |
self.assertEqual(data["arguments"]["topic"], "life")
|
| 32 |
|
| 33 |
-
@patch('
|
| 34 |
def test_oracle_dispatch_mock(self, mock_oracle):
|
| 35 |
"""Verify valid tool calls trigger the backend function."""
|
| 36 |
mock_oracle.return_value = {"mock": "result"}
|
|
|
|
| 2 |
import json
|
| 3 |
import re
|
| 4 |
from unittest.mock import MagicMock, patch
|
| 5 |
+
from app_module import build_agent_prompt, chat_agent_stream
|
| 6 |
|
| 7 |
# Import backend tool function to verify it exists
|
| 8 |
try:
|
|
|
|
| 30 |
self.assertEqual(data["name"], "oracle_consultation")
|
| 31 |
self.assertEqual(data["arguments"]["topic"], "life")
|
| 32 |
|
| 33 |
+
@patch('app_module.get_oracle_data')
|
| 34 |
def test_oracle_dispatch_mock(self, mock_oracle):
|
| 35 |
"""Verify valid tool calls trigger the backend function."""
|
| 36 |
mock_oracle.return_value = {"mock": "result"}
|
tests/test_final_suite.py
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
-
from
|
| 4 |
import json
|
| 5 |
|
| 6 |
class TestFinalSuite(unittest.TestCase):
|
| 7 |
|
| 8 |
-
@patch('
|
| 9 |
-
@patch('
|
| 10 |
-
@patch('
|
| 11 |
-
@patch('
|
| 12 |
def test_multi_message_bubbles(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 13 |
"""
|
| 14 |
Verify that multi-turn agent responses result in multiple distinct message bubbles in history.
|
|
@@ -51,11 +51,11 @@ class TestFinalSuite(unittest.TestCase):
|
|
| 51 |
self.assertEqual(final_history[2]["content"], "Final Answer")
|
| 52 |
|
| 53 |
|
| 54 |
-
@patch('
|
| 55 |
-
@patch('
|
| 56 |
-
@patch('
|
| 57 |
-
@patch('
|
| 58 |
-
@patch('
|
| 59 |
def test_oracle_filtering(self, mock_oracle, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 60 |
"""
|
| 61 |
Verify that ONLY wisdom_nodes are passed to the tool result string, masking 'els_revelation' etc.
|
|
@@ -120,10 +120,10 @@ class TestFinalSuite(unittest.TestCase):
|
|
| 120 |
|
| 121 |
self.assertTrue(found_filtered, "Tool Result did not contain filtered data (or contained forbidden keys).")
|
| 122 |
|
| 123 |
-
@patch('
|
| 124 |
-
@patch('
|
| 125 |
-
@patch('
|
| 126 |
-
@patch('
|
| 127 |
def test_prompt_fluidity_instruction(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 128 |
"""
|
| 129 |
Verify that the injected prompt contains the 'connect smoothly' instruction.
|
|
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
+
from app_module import chat_wrapper, chat_agent_stream, get_oracle_data
|
| 4 |
import json
|
| 5 |
|
| 6 |
class TestFinalSuite(unittest.TestCase):
|
| 7 |
|
| 8 |
+
@patch('app_module.get_llm')
|
| 9 |
+
@patch('app_module.TextIteratorStreamer')
|
| 10 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 11 |
+
@patch('app_module.detect_language')
|
| 12 |
def test_multi_message_bubbles(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 13 |
"""
|
| 14 |
Verify that multi-turn agent responses result in multiple distinct message bubbles in history.
|
|
|
|
| 51 |
self.assertEqual(final_history[2]["content"], "Final Answer")
|
| 52 |
|
| 53 |
|
| 54 |
+
@patch('app_module.get_llm')
|
| 55 |
+
@patch('app_module.TextIteratorStreamer')
|
| 56 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 57 |
+
@patch('app_module.detect_language')
|
| 58 |
+
@patch('app_module.get_oracle_data')
|
| 59 |
def test_oracle_filtering(self, mock_oracle, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 60 |
"""
|
| 61 |
Verify that ONLY wisdom_nodes are passed to the tool result string, masking 'els_revelation' etc.
|
|
|
|
| 120 |
|
| 121 |
self.assertTrue(found_filtered, "Tool Result did not contain filtered data (or contained forbidden keys).")
|
| 122 |
|
| 123 |
+
@patch('app_module.get_llm')
|
| 124 |
+
@patch('app_module.TextIteratorStreamer')
|
| 125 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 126 |
+
@patch('app_module.detect_language')
|
| 127 |
def test_prompt_fluidity_instruction(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 128 |
"""
|
| 129 |
Verify that the injected prompt contains the 'connect smoothly' instruction.
|
tests/test_full_coverage.py
CHANGED
|
@@ -17,7 +17,7 @@ with patch('transformers.AutoProcessor.from_pretrained'), \
|
|
| 17 |
patch('langchain_huggingface.HuggingFaceEmbeddings'), \
|
| 18 |
patch('langchain_community.vectorstores.FAISS'):
|
| 19 |
import app
|
| 20 |
-
from
|
| 21 |
detect_language, build_agent_prompt, get_device, get_embedding_function, get_llm,
|
| 22 |
extract_text_from_file, get_text_splitter, index_files, clear_index,
|
| 23 |
retrieve_relevant_chunks, build_rag_prompt, chat_agent_stream,
|
|
@@ -29,7 +29,7 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 29 |
|
| 30 |
# --- Group 1: Utils & ML Logic ---
|
| 31 |
|
| 32 |
-
@patch('
|
| 33 |
def test_detect_language(self, mock_get_llm):
|
| 34 |
mock_model = MagicMock()
|
| 35 |
mock_processor = MagicMock()
|
|
@@ -55,7 +55,7 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 55 |
device = get_device()
|
| 56 |
self.assertIsInstance(device, torch.device)
|
| 57 |
|
| 58 |
-
@patch('
|
| 59 |
def test_get_embedding_function(self, mock_emb):
|
| 60 |
# Reset global
|
| 61 |
app.EMBEDDING_FUNCTION = None
|
|
@@ -63,8 +63,8 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 63 |
self.assertIsNotNone(func)
|
| 64 |
mock_emb.assert_called_once()
|
| 65 |
|
| 66 |
-
@patch('
|
| 67 |
-
@patch('
|
| 68 |
def test_get_llm(self, mock_model, mock_proc):
|
| 69 |
app.LLM_MODEL = None
|
| 70 |
app.LLM_PROCESSOR = None
|
|
@@ -72,7 +72,7 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 72 |
self.assertIsNotNone(m)
|
| 73 |
self.assertIsNotNone(p)
|
| 74 |
|
| 75 |
-
@patch('
|
| 76 |
def test_extract_text_from_file_pdf(self, mock_pdf):
|
| 77 |
mock_reader = mock_pdf.return_value
|
| 78 |
mock_reader.pages = [MagicMock(extract_text=lambda: "Page 1 content")]
|
|
@@ -90,10 +90,10 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 90 |
|
| 91 |
# --- Group 2: RAG & Indexing ---
|
| 92 |
|
| 93 |
-
@patch('
|
| 94 |
-
@patch('
|
| 95 |
-
@patch('
|
| 96 |
-
@patch('
|
| 97 |
def test_index_files(self, mock_mongo, mock_faiss, mock_splitter, mock_extract):
|
| 98 |
mock_extract.return_value = "Long text content"
|
| 99 |
mock_splitter.return_value.split_text.return_value = ["chunk1", "chunk2"]
|
|
@@ -136,7 +136,7 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 136 |
self.assertIsNotNone(w)
|
| 137 |
mock_load.assert_called_once()
|
| 138 |
|
| 139 |
-
@patch('
|
| 140 |
def test_transcribe_audio(self, mock_get_w):
|
| 141 |
mock_w = mock_get_w.return_value
|
| 142 |
mock_w.transcribe.return_value = {"text": "Transcribed text"}
|
|
@@ -166,9 +166,9 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 166 |
|
| 167 |
# --- Group 4: Actions & Orchestration ---
|
| 168 |
|
| 169 |
-
@patch('
|
| 170 |
-
@patch('
|
| 171 |
-
@patch('
|
| 172 |
def test_chat_agent_stream(self, mock_detect, mock_rag, mock_get_llm):
|
| 173 |
mock_model = MagicMock()
|
| 174 |
mock_processor = MagicMock()
|
|
@@ -180,10 +180,10 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 180 |
gen = chat_agent_stream("msg", [], None, None)
|
| 181 |
self.assertTrue(hasattr(gen, '__next__'))
|
| 182 |
|
| 183 |
-
@patch('
|
| 184 |
-
@patch('
|
| 185 |
-
@patch('
|
| 186 |
-
@patch('
|
| 187 |
def test_purification(self, mock_detect, mock_rag, mock_streamer, mock_get_llm):
|
| 188 |
mock_model = MagicMock()
|
| 189 |
mock_processor = MagicMock()
|
|
@@ -203,10 +203,10 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 203 |
self.assertIn("Hello", responses[-1])
|
| 204 |
self.assertIn("World", responses[-1])
|
| 205 |
|
| 206 |
-
@patch('
|
| 207 |
-
@patch('
|
| 208 |
-
@patch('
|
| 209 |
-
@patch('
|
| 210 |
def test_voice_chat_wrapper(self, mock_detect, mock_tts, mock_stt, mock_chat):
|
| 211 |
mock_detect.return_value = "English"
|
| 212 |
mock_stt.return_value = "Hello"
|
|
@@ -227,7 +227,7 @@ class TestSageFullCoverage(unittest.TestCase):
|
|
| 227 |
res = r
|
| 228 |
self.assertEqual(res[4], "out.mp3")
|
| 229 |
|
| 230 |
-
@patch('
|
| 231 |
def test_chat_wrapper(self, mock_agent):
|
| 232 |
mock_agent.return_value = iter(["Part 1", "Part 2"])
|
| 233 |
history = []
|
|
|
|
| 17 |
patch('langchain_huggingface.HuggingFaceEmbeddings'), \
|
| 18 |
patch('langchain_community.vectorstores.FAISS'):
|
| 19 |
import app
|
| 20 |
+
from app_module import (
|
| 21 |
detect_language, build_agent_prompt, get_device, get_embedding_function, get_llm,
|
| 22 |
extract_text_from_file, get_text_splitter, index_files, clear_index,
|
| 23 |
retrieve_relevant_chunks, build_rag_prompt, chat_agent_stream,
|
|
|
|
| 29 |
|
| 30 |
# --- Group 1: Utils & ML Logic ---
|
| 31 |
|
| 32 |
+
@patch('app_module.get_llm')
|
| 33 |
def test_detect_language(self, mock_get_llm):
|
| 34 |
mock_model = MagicMock()
|
| 35 |
mock_processor = MagicMock()
|
|
|
|
| 55 |
device = get_device()
|
| 56 |
self.assertIsInstance(device, torch.device)
|
| 57 |
|
| 58 |
+
@patch('app_module.HuggingFaceEmbeddings')
|
| 59 |
def test_get_embedding_function(self, mock_emb):
|
| 60 |
# Reset global
|
| 61 |
app.EMBEDDING_FUNCTION = None
|
|
|
|
| 63 |
self.assertIsNotNone(func)
|
| 64 |
mock_emb.assert_called_once()
|
| 65 |
|
| 66 |
+
@patch('app_module.AutoProcessor.from_pretrained')
|
| 67 |
+
@patch('app_module.Gemma3ForConditionalGeneration.from_pretrained')
|
| 68 |
def test_get_llm(self, mock_model, mock_proc):
|
| 69 |
app.LLM_MODEL = None
|
| 70 |
app.LLM_PROCESSOR = None
|
|
|
|
| 72 |
self.assertIsNotNone(m)
|
| 73 |
self.assertIsNotNone(p)
|
| 74 |
|
| 75 |
+
@patch('app_module.PdfReader')
|
| 76 |
def test_extract_text_from_file_pdf(self, mock_pdf):
|
| 77 |
mock_reader = mock_pdf.return_value
|
| 78 |
mock_reader.pages = [MagicMock(extract_text=lambda: "Page 1 content")]
|
|
|
|
| 90 |
|
| 91 |
# --- Group 2: RAG & Indexing ---
|
| 92 |
|
| 93 |
+
@patch('app_module.extract_text_from_file')
|
| 94 |
+
@patch('app_module.get_text_splitter')
|
| 95 |
+
@patch('app_module.FAISS')
|
| 96 |
+
@patch('app_module.MongoDBHandler')
|
| 97 |
def test_index_files(self, mock_mongo, mock_faiss, mock_splitter, mock_extract):
|
| 98 |
mock_extract.return_value = "Long text content"
|
| 99 |
mock_splitter.return_value.split_text.return_value = ["chunk1", "chunk2"]
|
|
|
|
| 136 |
self.assertIsNotNone(w)
|
| 137 |
mock_load.assert_called_once()
|
| 138 |
|
| 139 |
+
@patch('app_module.get_whisper')
|
| 140 |
def test_transcribe_audio(self, mock_get_w):
|
| 141 |
mock_w = mock_get_w.return_value
|
| 142 |
mock_w.transcribe.return_value = {"text": "Transcribed text"}
|
|
|
|
| 166 |
|
| 167 |
# --- Group 4: Actions & Orchestration ---
|
| 168 |
|
| 169 |
+
@patch('app_module.get_llm')
|
| 170 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 171 |
+
@patch('app_module.detect_language')
|
| 172 |
def test_chat_agent_stream(self, mock_detect, mock_rag, mock_get_llm):
|
| 173 |
mock_model = MagicMock()
|
| 174 |
mock_processor = MagicMock()
|
|
|
|
| 180 |
gen = chat_agent_stream("msg", [], None, None)
|
| 181 |
self.assertTrue(hasattr(gen, '__next__'))
|
| 182 |
|
| 183 |
+
@patch('app_module.get_llm')
|
| 184 |
+
@patch('app_module.TextIteratorStreamer')
|
| 185 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 186 |
+
@patch('app_module.detect_language')
|
| 187 |
def test_purification(self, mock_detect, mock_rag, mock_streamer, mock_get_llm):
|
| 188 |
mock_model = MagicMock()
|
| 189 |
mock_processor = MagicMock()
|
|
|
|
| 203 |
self.assertIn("Hello", responses[-1])
|
| 204 |
self.assertIn("World", responses[-1])
|
| 205 |
|
| 206 |
+
@patch('app_module.chat_wrapper')
|
| 207 |
+
@patch('app_module.transcribe_audio')
|
| 208 |
+
@patch('app_module.generate_speech')
|
| 209 |
+
@patch('app_module.detect_language')
|
| 210 |
def test_voice_chat_wrapper(self, mock_detect, mock_tts, mock_stt, mock_chat):
|
| 211 |
mock_detect.return_value = "English"
|
| 212 |
mock_stt.return_value = "Hello"
|
|
|
|
| 227 |
res = r
|
| 228 |
self.assertEqual(res[4], "out.mp3")
|
| 229 |
|
| 230 |
+
@patch('app_module.chat_agent_stream')
|
| 231 |
def test_chat_wrapper(self, mock_agent):
|
| 232 |
mock_agent.return_value = iter(["Part 1", "Part 2"])
|
| 233 |
history = []
|
tests/test_name_extraction.py
CHANGED
|
@@ -18,7 +18,7 @@ sys.modules["accelerate"] = MagicMock()
|
|
| 18 |
# Add parent directory to path to import app
|
| 19 |
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 20 |
|
| 21 |
-
from
|
| 22 |
|
| 23 |
class TestNameExtraction(unittest.TestCase):
|
| 24 |
def setUp(self):
|
|
@@ -34,11 +34,11 @@ class TestNameExtraction(unittest.TestCase):
|
|
| 34 |
expected_part = '"name": "str (Optional. Use ONLY if the user explicitly stated their name, otherwise omit)"'
|
| 35 |
self.assertIn(expected_part, prompt)
|
| 36 |
|
| 37 |
-
@patch('
|
| 38 |
-
@patch('
|
| 39 |
-
@patch('
|
| 40 |
-
@patch('
|
| 41 |
-
@patch('
|
| 42 |
def test_oracle_call_with_name(self, mock_get_oracle_data, mock_detect, mock_retrieve, mock_streamer_cls, mock_get_llm):
|
| 43 |
"""Test that the agent calls get_oracle_data with the extracted name."""
|
| 44 |
|
|
@@ -80,11 +80,11 @@ class TestNameExtraction(unittest.TestCase):
|
|
| 80 |
self.assertEqual(call_args.kwargs.get('name'), "Julian")
|
| 81 |
self.assertEqual(call_args.kwargs.get('topic'), "Future")
|
| 82 |
|
| 83 |
-
@patch('
|
| 84 |
-
@patch('
|
| 85 |
-
@patch('
|
| 86 |
-
@patch('
|
| 87 |
-
@patch('
|
| 88 |
def test_oracle_call_without_name_defaults_to_seeker(self, mock_get_oracle_data, mock_detect, mock_retrieve, mock_streamer_cls, mock_get_llm):
|
| 89 |
"""Test that the agent defaults to 'Seeker' if no name is provided."""
|
| 90 |
|
|
|
|
| 18 |
# Add parent directory to path to import app
|
| 19 |
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 20 |
|
| 21 |
+
from app_module import build_agent_prompt, chat_agent_stream
|
| 22 |
|
| 23 |
class TestNameExtraction(unittest.TestCase):
|
| 24 |
def setUp(self):
|
|
|
|
| 34 |
expected_part = '"name": "str (Optional. Use ONLY if the user explicitly stated their name, otherwise omit)"'
|
| 35 |
self.assertIn(expected_part, prompt)
|
| 36 |
|
| 37 |
+
@patch('app_module.get_llm')
|
| 38 |
+
@patch('app_module.TextIteratorStreamer')
|
| 39 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 40 |
+
@patch('app_module.detect_language')
|
| 41 |
+
@patch('app_module.get_oracle_data')
|
| 42 |
def test_oracle_call_with_name(self, mock_get_oracle_data, mock_detect, mock_retrieve, mock_streamer_cls, mock_get_llm):
|
| 43 |
"""Test that the agent calls get_oracle_data with the extracted name."""
|
| 44 |
|
|
|
|
| 80 |
self.assertEqual(call_args.kwargs.get('name'), "Julian")
|
| 81 |
self.assertEqual(call_args.kwargs.get('topic'), "Future")
|
| 82 |
|
| 83 |
+
@patch('app_module.get_llm')
|
| 84 |
+
@patch('app_module.TextIteratorStreamer')
|
| 85 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 86 |
+
@patch('app_module.detect_language')
|
| 87 |
+
@patch('app_module.get_oracle_data')
|
| 88 |
def test_oracle_call_without_name_defaults_to_seeker(self, mock_get_oracle_data, mock_detect, mock_retrieve, mock_streamer_cls, mock_get_llm):
|
| 89 |
"""Test that the agent defaults to 'Seeker' if no name is provided."""
|
| 90 |
|
tests/test_regression_v6_5.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
import gradio as gr
|
| 4 |
-
from
|
| 5 |
|
| 6 |
class TestSageRegressionV6_5(unittest.TestCase):
|
| 7 |
|
|
@@ -22,8 +22,8 @@ class TestSageRegressionV6_5(unittest.TestCase):
|
|
| 22 |
h, tid, ud, um = switch_thread([], t_state)
|
| 23 |
self.assertEqual(h, [])
|
| 24 |
|
| 25 |
-
@patch('
|
| 26 |
-
@patch('
|
| 27 |
def test_agent_role_alternation(self, mock_oracle, mock_detect):
|
| 28 |
"""Verifies Assistant -> Tool -> Execution -> Assistant sequence."""
|
| 29 |
mock_detect.return_value = "English"
|
|
@@ -56,7 +56,7 @@ class TestSageRegressionV6_5(unittest.TestCase):
|
|
| 56 |
# Verify final response
|
| 57 |
self.assertIn("Peace", responses[-1])
|
| 58 |
|
| 59 |
-
@patch('
|
| 60 |
def test_chat_purification_logic(self, mock_detect):
|
| 61 |
"""Verifies that <tool_call> tags are stripped from streaming output."""
|
| 62 |
mock_detect.return_value = "English"
|
|
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
import gradio as gr
|
| 4 |
+
from app_module import chat_wrapper, chat_agent_stream, switch_thread
|
| 5 |
|
| 6 |
class TestSageRegressionV6_5(unittest.TestCase):
|
| 7 |
|
|
|
|
| 22 |
h, tid, ud, um = switch_thread([], t_state)
|
| 23 |
self.assertEqual(h, [])
|
| 24 |
|
| 25 |
+
@patch('app_module.detect_language')
|
| 26 |
+
@patch('app_module.get_oracle_data')
|
| 27 |
def test_agent_role_alternation(self, mock_oracle, mock_detect):
|
| 28 |
"""Verifies Assistant -> Tool -> Execution -> Assistant sequence."""
|
| 29 |
mock_detect.return_value = "English"
|
|
|
|
| 56 |
# Verify final response
|
| 57 |
self.assertIn("Peace", responses[-1])
|
| 58 |
|
| 59 |
+
@patch('app_module.detect_language')
|
| 60 |
def test_chat_purification_logic(self, mock_detect):
|
| 61 |
"""Verifies that <tool_call> tags are stripped from streaming output."""
|
| 62 |
mock_detect.return_value = "English"
|
tests/test_ui_logic.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
import gradio as gr
|
| 4 |
-
from
|
| 5 |
|
| 6 |
class TestUILogic(unittest.TestCase):
|
| 7 |
|
|
@@ -44,10 +44,10 @@ class TestUILogic(unittest.TestCase):
|
|
| 44 |
prompt_short = build_agent_prompt("Hi", [], [], short_answers=True)
|
| 45 |
self.assertIn("Be concise", prompt_short)
|
| 46 |
|
| 47 |
-
@patch('
|
| 48 |
-
@patch('
|
| 49 |
-
@patch('
|
| 50 |
-
@patch('
|
| 51 |
def test_accumulative_chat_streaming(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 52 |
"""Verify that streaming yields growing strings (Accumulation) instead of chunks."""
|
| 53 |
mock_detect.return_value = "English"
|
|
|
|
| 1 |
import unittest
|
| 2 |
from unittest.mock import MagicMock, patch
|
| 3 |
import gradio as gr
|
| 4 |
+
from app_module import switch_thread, create_new_thread_callback, build_agent_prompt, chat_agent_stream
|
| 5 |
|
| 6 |
class TestUILogic(unittest.TestCase):
|
| 7 |
|
|
|
|
| 44 |
prompt_short = build_agent_prompt("Hi", [], [], short_answers=True)
|
| 45 |
self.assertIn("Be concise", prompt_short)
|
| 46 |
|
| 47 |
+
@patch('app_module.get_llm')
|
| 48 |
+
@patch('app_module.TextIteratorStreamer')
|
| 49 |
+
@patch('app_module.retrieve_relevant_chunks')
|
| 50 |
+
@patch('app_module.detect_language')
|
| 51 |
def test_accumulative_chat_streaming(self, mock_detect, mock_rag, mock_streamer, mock_llm):
|
| 52 |
"""Verify that streaming yields growing strings (Accumulation) instead of chunks."""
|
| 53 |
mock_detect.return_value = "English"
|