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ist Multi-Agent Shell (Refactored & Fixed)
|
| 4 |
+
See header of assistant response for features & notes.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
import json
|
| 10 |
+
import textwrap
|
| 11 |
+
import traceback
|
| 12 |
+
import re
|
| 13 |
+
import tempfile
|
| 14 |
+
import subprocess
|
| 15 |
+
from typing import Dict, List, Tuple, Optional, Any
|
| 16 |
+
import io
|
| 17 |
+
import logging
|
| 18 |
+
from logging.handlers import RotatingFileHandler
|
| 19 |
+
|
| 20 |
+
import gradio as gr
|
| 21 |
+
from openai import OpenAI
|
| 22 |
+
from huggingface_hub import HfApi, hf_hub_download, list_repo_files
|
| 23 |
+
from typing import Tuple
|
| 24 |
+
|
| 25 |
+
# ---------------------------
|
| 26 |
+
# Logging configuration
|
| 27 |
+
# ---------------------------
|
| 28 |
+
LOG_DIR = os.environ.get("OHAMLAB_LOG_DIR", ".")
|
| 29 |
+
os.makedirs(LOG_DIR, exist_ok=True)
|
| 30 |
+
LOG_FILE = os.path.join(LOG_DIR, "ohamlab.log")
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger("ohamlab")
|
| 33 |
+
logger.setLevel(logging.DEBUG)
|
| 34 |
+
|
| 35 |
+
# Console handler (INFO)
|
| 36 |
+
ch = logging.StreamHandler()
|
| 37 |
+
ch.setLevel(logging.INFO)
|
| 38 |
+
ch_formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s - %(message)s", "%Y-%m-%d %H:%M:%S")
|
| 39 |
+
ch.setFormatter(ch_formatter)
|
| 40 |
+
logger.addHandler(ch)
|
| 41 |
+
|
| 42 |
+
# Rotating file handler (DEBUG)
|
| 43 |
+
fh = RotatingFileHandler(LOG_FILE, maxBytes=5 * 1024 * 1024, backupCount=3)
|
| 44 |
+
fh.setLevel(logging.DEBUG)
|
| 45 |
+
fh_formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s [%(filename)s:%(lineno)d] - %(message)s", "%Y-%m-%d %H:%M:%S")
|
| 46 |
+
fh.setFormatter(fh_formatter)
|
| 47 |
+
logger.addHandler(fh)
|
| 48 |
+
|
| 49 |
+
logger.info("Starting Ohamlab (logging initialized).")
|
| 50 |
+
|
| 51 |
+
# ---------------------------
|
| 52 |
+
# CONFIG
|
| 53 |
+
# ---------------------------
|
| 54 |
+
# Accept HF token env var in multiple common names
|
| 55 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or os.environ.get("HUGGINGFACE_TOKEN")
|
| 56 |
+
if not HF_TOKEN:
|
| 57 |
+
logger.critical("Missing HF_TOKEN / OPENAI_API_KEY / HUGGINGFACE_TOKEN environment variable.")
|
| 58 |
+
raise RuntimeError("ERROR: set env var HF_TOKEN or OPENAI_API_KEY with your Hugging Face / Router token.")
|
| 59 |
+
|
| 60 |
+
MODEL_ID = "openai/gpt-oss-20b" # chat model via HF router
|
| 61 |
+
EMBED_MODEL = "text-embedding-3-small"
|
| 62 |
+
|
| 63 |
+
HF_REPO = "rahul7star/LLM-Brain"
|
| 64 |
+
HF_REPO_DIR = "./hf_capsules" # local download folder
|
| 65 |
+
|
| 66 |
+
ALLOWED_EXT = (".md",)
|
| 67 |
+
MAX_CONTEXT_CHARS = 5000 # increased to allow larger capsules
|
| 68 |
+
CHUNK_SIZE = 1600
|
| 69 |
+
CHUNK_OVERLAP = 200
|
| 70 |
+
TOP_K_PASSAGES = 3
|
| 71 |
+
|
| 72 |
+
CHAT_MAX_TOKENS = 1400
|
| 73 |
+
RESEARCH_MAX_TOKENS = 4000
|
| 74 |
+
CODING_MAX_TOKENS = 3000
|
| 75 |
+
|
| 76 |
+
PY_SANDBOX_TIMEOUT = 16 # seconds
|
| 77 |
+
|
| 78 |
+
SUMMARY_CACHE_FILE = ".capsule_summaries.json"
|
| 79 |
+
|
| 80 |
+
telemetry = {
|
| 81 |
+
"model_calls": 0,
|
| 82 |
+
"tokens_used_est": 0,
|
| 83 |
+
"last_call_ms": None,
|
| 84 |
+
"calls": [],
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
# ---------------------------
|
| 88 |
+
# Client (OpenAI router via HF)
|
| 89 |
+
# ---------------------------
|
| 90 |
+
try:
|
| 91 |
+
client = OpenAI(base_url="https://router.huggingface.co/v1", api_key=HF_TOKEN)
|
| 92 |
+
logger.info("OpenAI client initialized via HF router.")
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.exception("Failed initializing OpenAI client: %s", e)
|
| 95 |
+
raise
|
| 96 |
+
|
| 97 |
+
# ---------------------------
|
| 98 |
+
# Utilities
|
| 99 |
+
# ---------------------------
|
| 100 |
+
def now_ms(): return int(time.time() * 1000)
|
| 101 |
+
|
| 102 |
+
def normalize_text(s: str) -> str:
|
| 103 |
+
s = s.lower()
|
| 104 |
+
s = re.sub(r"\s+", " ", s)
|
| 105 |
+
s = re.sub(r"[^0-9a-zA-Z\s\-_/\.]", " ", s)
|
| 106 |
+
return s.strip()
|
| 107 |
+
|
| 108 |
+
def tokenize_terms(s: str) -> List[str]:
|
| 109 |
+
return [t for t in normalize_text(s).split() if len(t) > 1]
|
| 110 |
+
|
| 111 |
+
def simple_overlap_score(query: str, passage: str) -> float:
|
| 112 |
+
q_terms = set(tokenize_terms(query))
|
| 113 |
+
p_terms = tokenize_terms(passage)
|
| 114 |
+
if not q_terms or not p_terms:
|
| 115 |
+
return 0.0
|
| 116 |
+
overlap = sum(1 for t in p_terms if t in q_terms)
|
| 117 |
+
score = overlap / (len(p_terms) ** 0.5 + 1e-6)
|
| 118 |
+
return float(score)
|
| 119 |
+
|
| 120 |
+
# ---------------------------
|
| 121 |
+
# Hugging Face fetch
|
| 122 |
+
# ---------------------------
|
| 123 |
+
def fetch_md_from_hf(local_dir: str = HF_REPO_DIR) -> List[str]:
|
| 124 |
+
"""
|
| 125 |
+
Download all .md files in HF_REPO into local_dir.
|
| 126 |
+
Returns list of local file paths.
|
| 127 |
+
"""
|
| 128 |
+
os.makedirs(local_dir, exist_ok=True)
|
| 129 |
+
api = HfApi()
|
| 130 |
+
try:
|
| 131 |
+
repo_files = list_repo_files(HF_REPO)
|
| 132 |
+
logger.debug("Listed files in HF repo '%s': %d entries.", HF_REPO, len(repo_files))
|
| 133 |
+
except Exception as e:
|
| 134 |
+
logger.warning("list_repo_files failed for %s: %s", HF_REPO, e)
|
| 135 |
+
repo_files = []
|
| 136 |
+
|
| 137 |
+
md_files = [f for f in repo_files if f.lower().endswith(".md")]
|
| 138 |
+
downloaded = []
|
| 139 |
+
for f in md_files:
|
| 140 |
+
try:
|
| 141 |
+
local_path = hf_hub_download(repo_id=HF_REPO, filename=f, repo_type="model", local_dir=local_dir, token=HF_TOKEN)
|
| 142 |
+
downloaded.append(local_path)
|
| 143 |
+
logger.info("Downloaded %s -> %s", f, local_path)
|
| 144 |
+
except Exception as e:
|
| 145 |
+
# continue but report
|
| 146 |
+
logger.warning("Failed to download %s: %s", f, e)
|
| 147 |
+
# If list_repo_files returned nothing (private repo?), try scanning local dir only.
|
| 148 |
+
if not md_files:
|
| 149 |
+
logger.debug("No markdown files discovered via HF list; will rely on local directory scanning.")
|
| 150 |
+
return downloaded
|
| 151 |
+
|
| 152 |
+
# ---------------------------
|
| 153 |
+
# Knowledge Store
|
| 154 |
+
# ---------------------------
|
| 155 |
+
class KnowledgeStore:
|
| 156 |
+
def __init__(self, root: str = HF_REPO_DIR, exts: Tuple[str, ...] = ALLOWED_EXT):
|
| 157 |
+
self.root = root
|
| 158 |
+
self.exts = exts
|
| 159 |
+
self.capsules: Dict[str, Dict[str, Any]] = {}
|
| 160 |
+
self.summary_cache: Dict[str, Dict] = {}
|
| 161 |
+
os.makedirs(self.root, exist_ok=True)
|
| 162 |
+
self._load_summary_cache()
|
| 163 |
+
self._load_all()
|
| 164 |
+
|
| 165 |
+
def _read_file(self, path: str) -> str:
|
| 166 |
+
try:
|
| 167 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 168 |
+
return f.read()
|
| 169 |
+
except Exception as e:
|
| 170 |
+
logger.error("Error reading %s: %s", path, e)
|
| 171 |
+
return f"[Error reading {os.path.basename(path)}: {e}]"
|
| 172 |
+
|
| 173 |
+
def _chunk_text(self, text: str) -> List[str]:
|
| 174 |
+
chunks = []
|
| 175 |
+
i = 0
|
| 176 |
+
length = len(text)
|
| 177 |
+
while i < length:
|
| 178 |
+
chunk = text[i:i+CHUNK_SIZE]
|
| 179 |
+
chunks.append(chunk)
|
| 180 |
+
i += CHUNK_SIZE - CHUNK_OVERLAP
|
| 181 |
+
return chunks or [text]
|
| 182 |
+
|
| 183 |
+
def _scan_local_md_files(self) -> List[str]:
|
| 184 |
+
paths = []
|
| 185 |
+
for root, _, files in os.walk(self.root):
|
| 186 |
+
for name in files:
|
| 187 |
+
if name.lower().endswith(self.exts):
|
| 188 |
+
paths.append(os.path.join(root, name))
|
| 189 |
+
logger.debug("Scanned %d local markdown files under %s", len(paths), self.root)
|
| 190 |
+
return sorted(paths)
|
| 191 |
+
|
| 192 |
+
def _load_all(self):
|
| 193 |
+
# first attempt: download from HF into local dir (safe to call repeatedly)
|
| 194 |
+
try:
|
| 195 |
+
fetch_md_from_hf(self.root)
|
| 196 |
+
except Exception as e:
|
| 197 |
+
logger.warning("fetch_md_from_hf failed during load_all: %s", e)
|
| 198 |
+
|
| 199 |
+
files = self._scan_local_md_files()
|
| 200 |
+
total_len = 0
|
| 201 |
+
for path in files:
|
| 202 |
+
name = os.path.basename(path)
|
| 203 |
+
try:
|
| 204 |
+
mtime = os.path.getmtime(path)
|
| 205 |
+
except Exception:
|
| 206 |
+
mtime = 0
|
| 207 |
+
key = os.path.splitext(name)[0].lower()
|
| 208 |
+
text = self._read_file(path)
|
| 209 |
+
if len(text) > MAX_CONTEXT_CHARS:
|
| 210 |
+
text = text[:MAX_CONTEXT_CHARS] + "\n\n[TRUNCATED]\n"
|
| 211 |
+
logger.debug("Truncated %s to MAX_CONTEXT_CHARS", name)
|
| 212 |
+
chunks = self._chunk_text(text)
|
| 213 |
+
self.capsules[key] = {"filename": name, "text": text, "chunks": chunks, "mtime": mtime, "path": path}
|
| 214 |
+
total_len += len(text)
|
| 215 |
+
logger.info("Loaded capsule '%s' (file=%s, chars=%d, chunks=%d)", key, name, len(text), len(chunks))
|
| 216 |
+
logger.info("[KnowledgeStore] Loaded %d capsule(s). total_chars=%d", len(self.capsules), total_len)
|
| 217 |
+
|
| 218 |
+
def maybe_reload(self):
|
| 219 |
+
# Reload any file that changed
|
| 220 |
+
changed = False
|
| 221 |
+
for key, meta in list(self.capsules.items()):
|
| 222 |
+
path = meta.get("path")
|
| 223 |
+
if not path or not os.path.exists(path):
|
| 224 |
+
continue
|
| 225 |
+
try:
|
| 226 |
+
mtime = os.path.getmtime(path)
|
| 227 |
+
except Exception:
|
| 228 |
+
mtime = None
|
| 229 |
+
if mtime and mtime != meta.get("mtime"):
|
| 230 |
+
logger.info("Detected change in capsule %s; reloading.", key)
|
| 231 |
+
text = self._read_file(path)
|
| 232 |
+
if len(text) > MAX_CONTEXT_CHARS:
|
| 233 |
+
text = text[:MAX_CONTEXT_CHARS] + "\n\n[TRUNCATED]\n"
|
| 234 |
+
chunks = self._chunk_text(text)
|
| 235 |
+
self.capsules[key].update({"text": text, "chunks": chunks, "mtime": mtime})
|
| 236 |
+
if key in self.summary_cache:
|
| 237 |
+
del self.summary_cache[key]
|
| 238 |
+
self._persist_summary_cache()
|
| 239 |
+
changed = True
|
| 240 |
+
if changed:
|
| 241 |
+
logger.debug("maybe_reload: changes detected in knowledge store.")
|
| 242 |
+
return changed
|
| 243 |
+
|
| 244 |
+
def refresh_all(self):
|
| 245 |
+
logger.info("Refreshing all capsules from HF and local dir.")
|
| 246 |
+
fetch_md_from_hf(self.root)
|
| 247 |
+
self.capsules = {}
|
| 248 |
+
self._load_all()
|
| 249 |
+
self.summary_cache = {}
|
| 250 |
+
self._persist_summary_cache()
|
| 251 |
+
|
| 252 |
+
def list_agents(self) -> List[str]:
|
| 253 |
+
return sorted(list(self.capsules.keys()))
|
| 254 |
+
|
| 255 |
+
def get_capsule(self, key: str) -> Optional[Dict]:
|
| 256 |
+
return self.capsules.get(key)
|
| 257 |
+
|
| 258 |
+
# Embeddings (lazy)
|
| 259 |
+
def _embed_text(self, text: str) -> Optional[List[float]]:
|
| 260 |
+
try:
|
| 261 |
+
r = client.embeddings.create(model=EMBED_MODEL, input=[text])
|
| 262 |
+
emb = r.data[0].embedding
|
| 263 |
+
logger.debug("Generated embedding (len=%d) for text snippet (chars=%d)", len(emb), len(text))
|
| 264 |
+
return emb
|
| 265 |
+
except Exception as e:
|
| 266 |
+
logger.warning("Embedding generation failed: %s", e)
|
| 267 |
+
return None
|
| 268 |
+
|
| 269 |
+
def build_embeddings_for_capsule(self, key: str):
|
| 270 |
+
meta = self.get_capsule(key)
|
| 271 |
+
if not meta:
|
| 272 |
+
logger.warning("build_embeddings_for_capsule: missing capsule %s", key)
|
| 273 |
+
return
|
| 274 |
+
if meta.get("embeddings"):
|
| 275 |
+
logger.debug("build_embeddings_for_capsule: embeddings already exist for %s", key)
|
| 276 |
+
return
|
| 277 |
+
embeddings = []
|
| 278 |
+
for i, chunk in enumerate(meta["chunks"], 1):
|
| 279 |
+
emb = self._embed_text(chunk)
|
| 280 |
+
embeddings.append(emb)
|
| 281 |
+
logger.debug("Embedding chunk %d/%d for capsule %s", i, len(meta["chunks"]), key)
|
| 282 |
+
meta["embeddings"] = embeddings
|
| 283 |
+
logger.info("Built embeddings for capsule %s (%d chunks)", key, len(embeddings))
|
| 284 |
+
|
| 285 |
+
@staticmethod
|
| 286 |
+
def _cosine(a: List[float], b: List[float]) -> float:
|
| 287 |
+
if a is None or b is None:
|
| 288 |
+
return -1.0
|
| 289 |
+
import math
|
| 290 |
+
dot = sum(x*y for x,y in zip(a,b))
|
| 291 |
+
na = math.sqrt(sum(x*x for x in a))
|
| 292 |
+
nb = math.sqrt(sum(x*x for x in b))
|
| 293 |
+
if na==0 or nb==0:
|
| 294 |
+
return -1.0
|
| 295 |
+
return dot / (na*nb)
|
| 296 |
+
|
| 297 |
+
# Find relevant capsules (embedding fallback to overlap)
|
| 298 |
+
def find_relevant_capsules(self, query: str, top_n: int = 3) -> List[Tuple[str, float]]:
|
| 299 |
+
query_emb = None
|
| 300 |
+
try:
|
| 301 |
+
query_emb = self._embed_text(query)
|
| 302 |
+
except Exception as e:
|
| 303 |
+
query_emb = None
|
| 304 |
+
logger.debug("Embedding query failed during find_relevant_capsules: %s", e)
|
| 305 |
+
scores = []
|
| 306 |
+
for key, meta in self.capsules.items():
|
| 307 |
+
best_score = 0.0
|
| 308 |
+
if meta.get("embeddings") and query_emb:
|
| 309 |
+
for emb in meta["embeddings"]:
|
| 310 |
+
sc = self._cosine(query_emb, emb)
|
| 311 |
+
if sc > best_score:
|
| 312 |
+
best_score = sc
|
| 313 |
+
else:
|
| 314 |
+
for chunk in meta.get("chunks", []):
|
| 315 |
+
sc = simple_overlap_score(query, chunk)
|
| 316 |
+
if sc > best_score:
|
| 317 |
+
best_score = sc
|
| 318 |
+
if key in normalize_text(query):
|
| 319 |
+
best_score += 0.15
|
| 320 |
+
if best_score > 0:
|
| 321 |
+
scores.append((key, best_score))
|
| 322 |
+
scores.sort(key=lambda x: x[1], reverse=True)
|
| 323 |
+
logger.debug("find_relevant_capsules for query '%s' -> top: %s", query[:80], scores[:top_n])
|
| 324 |
+
return scores[:top_n]
|
| 325 |
+
|
| 326 |
+
def get_top_passages_for_capsule(self, capsule_key: str, query: str, k: int = TOP_K_PASSAGES) -> List[Tuple[str, float]]:
|
| 327 |
+
meta = self.get_capsule(capsule_key) or {}
|
| 328 |
+
chunks = meta.get("chunks", [])
|
| 329 |
+
scored = []
|
| 330 |
+
|
| 331 |
+
query_emb = None
|
| 332 |
+
try:
|
| 333 |
+
query_emb = self._embed_text(query)
|
| 334 |
+
except Exception as e:
|
| 335 |
+
query_emb = None
|
| 336 |
+
logger.debug("Query embedding failed for top passages: %s", e)
|
| 337 |
+
|
| 338 |
+
if meta.get("embeddings") and query_emb:
|
| 339 |
+
for chunk, emb in zip(chunks, meta.get("embeddings", [])):
|
| 340 |
+
score = self._cosine(query_emb, emb) or 0.0
|
| 341 |
+
scored.append((chunk, float(score)))
|
| 342 |
+
else:
|
| 343 |
+
scored = [(chunk, simple_overlap_score(query, chunk)) for chunk in chunks]
|
| 344 |
+
|
| 345 |
+
scored = [s for s in scored if s[1] > 0]
|
| 346 |
+
scored.sort(key=lambda x: x[1], reverse=True)
|
| 347 |
+
logger.debug("Top passages for capsule %s (query=%s): %d hits", capsule_key, query[:80], len(scored))
|
| 348 |
+
return scored[:k]
|
| 349 |
+
|
| 350 |
+
# Summaries
|
| 351 |
+
def _load_summary_cache(self):
|
| 352 |
+
if os.path.exists(SUMMARY_CACHE_FILE):
|
| 353 |
+
try:
|
| 354 |
+
with open(SUMMARY_CACHE_FILE, "r", encoding="utf-8") as f:
|
| 355 |
+
self.summary_cache = json.load(f)
|
| 356 |
+
logger.info("Loaded summary cache (%d items).", len(self.summary_cache))
|
| 357 |
+
except Exception as e:
|
| 358 |
+
self.summary_cache = {}
|
| 359 |
+
logger.warning("Failed to load summary cache: %s", e)
|
| 360 |
+
else:
|
| 361 |
+
self.summary_cache = {}
|
| 362 |
+
logger.debug("No summary cache file found; starting fresh.")
|
| 363 |
+
|
| 364 |
+
def _persist_summary_cache(self):
|
| 365 |
+
try:
|
| 366 |
+
with open(SUMMARY_CACHE_FILE, "w", encoding="utf-8") as f:
|
| 367 |
+
json.dump(self.summary_cache, f, indent=2)
|
| 368 |
+
logger.debug("Persisted summary cache (%d items).", len(self.summary_cache))
|
| 369 |
+
except Exception as e:
|
| 370 |
+
logger.warning("Failed to persist summary cache: %s", e)
|
| 371 |
+
|
| 372 |
+
def get_or_build_summary(self, key: str, force: bool = False) -> str:
|
| 373 |
+
if not force and key in self.summary_cache:
|
| 374 |
+
logger.debug("Returning cached summary for %s", key)
|
| 375 |
+
return self.summary_cache[key]["summary"]
|
| 376 |
+
meta = self.get_capsule(key)
|
| 377 |
+
if not meta:
|
| 378 |
+
logger.debug("get_or_build_summary: no capsule for key %s", key)
|
| 379 |
+
return ""
|
| 380 |
+
top_chunks = meta.get("chunks", [])[:6]
|
| 381 |
+
combined = "\n\n".join(top_chunks)
|
| 382 |
+
prompt = textwrap.dedent(f"""
|
| 383 |
+
Summarize the following markdown content into a concise (4-8 sentence) technical summary.
|
| 384 |
+
----- BEGIN CONTENT -----
|
| 385 |
+
{combined}
|
| 386 |
+
----- END CONTENT -----
|
| 387 |
+
""").strip()
|
| 388 |
+
try:
|
| 389 |
+
messages = [{"role":"system","content":"You are a succinct summarizer."},
|
| 390 |
+
{"role":"user","content":prompt}]
|
| 391 |
+
logger.debug("Requesting summary for capsule %s (chars=%d)", key, len(combined))
|
| 392 |
+
resp = client.chat.completions.create(model=MODEL_ID, messages=messages, max_tokens=400, temperature=0.0)
|
| 393 |
+
summary = resp.choices[0].message.content.strip()
|
| 394 |
+
# if usage is available, log it
|
| 395 |
+
usage = getattr(resp, "usage", None)
|
| 396 |
+
if usage:
|
| 397 |
+
try:
|
| 398 |
+
telemetry['tokens_used_est'] += int(usage.total_tokens)
|
| 399 |
+
except Exception:
|
| 400 |
+
pass
|
| 401 |
+
logger.info("Summary built for %s (usage=%s)", key, usage)
|
| 402 |
+
except Exception as e:
|
| 403 |
+
logger.warning("Failed to build summary via model for %s: %s", key, e)
|
| 404 |
+
summary = combined[:800] + ("\n\n[TRUNCATED]" if len(combined) > 800 else "")
|
| 405 |
+
self.summary_cache[key] = {"summary": summary, "updated": int(time.time())}
|
| 406 |
+
self._persist_summary_cache()
|
| 407 |
+
return summary
|
| 408 |
+
|
| 409 |
+
# PDF β capsule helper
|
| 410 |
+
def add_pdf_capsule(self, capsule_name: str, filepath: str) -> None:
|
| 411 |
+
"""
|
| 412 |
+
Create a .md capsule from PDF content at filepath.
|
| 413 |
+
"""
|
| 414 |
+
if not os.path.exists(filepath):
|
| 415 |
+
logger.error("add_pdf_capsule: filepath does not exist: %s", filepath)
|
| 416 |
+
raise FileNotFoundError(filepath)
|
| 417 |
+
# Extract text bytes
|
| 418 |
+
try:
|
| 419 |
+
b = open(filepath, "rb").read()
|
| 420 |
+
except Exception as e:
|
| 421 |
+
logger.exception("Failed to read uploaded pdf bytes: %s", e)
|
| 422 |
+
raise
|
| 423 |
+
txt = _extract_text_from_pdf_bytes(b)
|
| 424 |
+
md_name = f"{capsule_name}.md"
|
| 425 |
+
out_path = os.path.join(self.root, md_name)
|
| 426 |
+
try:
|
| 427 |
+
with open(out_path, "w", encoding="utf-8") as f:
|
| 428 |
+
f.write(f"# {capsule_name}\n\n")
|
| 429 |
+
f.write(txt)
|
| 430 |
+
logger.info("Wrote PDF capsule to %s", out_path)
|
| 431 |
+
except Exception as e:
|
| 432 |
+
logger.exception("Failed to write capsule file %s: %s", out_path, e)
|
| 433 |
+
raise
|
| 434 |
+
# reload into store
|
| 435 |
+
self._load_all()
|
| 436 |
+
|
| 437 |
+
store = KnowledgeStore(HF_REPO_DIR)
|
| 438 |
+
|
| 439 |
+
# ---------------------------
|
| 440 |
+
# Conversation manager
|
| 441 |
+
# ---------------------------
|
| 442 |
+
class ConversationManager:
|
| 443 |
+
def __init__(self):
|
| 444 |
+
self.histories: Dict[str, List[Dict]] = {}
|
| 445 |
+
def get_history(self, key):
|
| 446 |
+
if key not in self.histories:
|
| 447 |
+
self.histories[key] = []
|
| 448 |
+
return self.histories[key]
|
| 449 |
+
def append(self, key, role, content):
|
| 450 |
+
logger.debug("Appending to history: agent=%s role=%s chars=%d", key, role, len(content or ""))
|
| 451 |
+
self.get_history(key).append({"role": role, "content": content})
|
| 452 |
+
def reset_agent(self, key):
|
| 453 |
+
logger.info("Resetting history for agent %s", key)
|
| 454 |
+
self.histories[key] = []
|
| 455 |
+
def reset_all(self):
|
| 456 |
+
logger.info("Resetting all conversation histories")
|
| 457 |
+
self.histories = {}
|
| 458 |
+
|
| 459 |
+
conv_manager = ConversationManager()
|
| 460 |
+
|
| 461 |
+
# ---------------------------
|
| 462 |
+
# Python sandbox helpers
|
| 463 |
+
# ---------------------------
|
| 464 |
+
def run_user_code_simple(code: str) -> str:
|
| 465 |
+
"""
|
| 466 |
+
Simple local exec (not safe for untrusted code). Kept for quick tests only.
|
| 467 |
+
We will prefer the sandbox-run below for actual user-run code paths.
|
| 468 |
+
"""
|
| 469 |
+
try:
|
| 470 |
+
exec_globals = {}
|
| 471 |
+
exec(code, exec_globals)
|
| 472 |
+
logger.info("run_user_code_simple executed code successfully (chars=%d)", len(code))
|
| 473 |
+
return "β
Code ran without errors."
|
| 474 |
+
except Exception:
|
| 475 |
+
tb = traceback.format_exc()
|
| 476 |
+
logger.error("run_user_code_simple error: %s", tb)
|
| 477 |
+
return f"β Error:\n{tb}"
|
| 478 |
+
|
| 479 |
+
def run_python_sandbox(code: str, timeout: int = PY_SANDBOX_TIMEOUT) -> Tuple[str, str]:
|
| 480 |
+
blocked = ["os.system", "subprocess", "socket", "pty", "multiprocessing", "shutil", "requests", "urllib", "open("]
|
| 481 |
+
lowered = code.lower()
|
| 482 |
+
for b in blocked:
|
| 483 |
+
if b in lowered:
|
| 484 |
+
logger.warning("Refused to run sandboxed code due to blocked pattern: %s", b)
|
| 485 |
+
return "", f"Refused to run: code contains blocked pattern '{b}'."
|
| 486 |
+
with tempfile.TemporaryDirectory() as d:
|
| 487 |
+
script_path = os.path.join(d, "script.py")
|
| 488 |
+
with open(script_path, "w", encoding="utf-8") as f: f.write(code)
|
| 489 |
+
try:
|
| 490 |
+
proc = subprocess.Popen(
|
| 491 |
+
["python", script_path],
|
| 492 |
+
stdout=subprocess.PIPE,
|
| 493 |
+
stderr=subprocess.PIPE,
|
| 494 |
+
cwd=d,
|
| 495 |
+
text=True,
|
| 496 |
+
env={"PYTHONPATH": d}
|
| 497 |
+
)
|
| 498 |
+
try:
|
| 499 |
+
out, err = proc.communicate(timeout=timeout)
|
| 500 |
+
except subprocess.TimeoutExpired:
|
| 501 |
+
proc.kill()
|
| 502 |
+
logger.warning("Sandbox code timed out after %ds", timeout)
|
| 503 |
+
return "", f"Execution timed out after {timeout}s."
|
| 504 |
+
logger.info("Sandbox executed successfully (stdout=%d bytes, stderr=%d bytes)", len(out or ""), len(err or ""))
|
| 505 |
+
return out, err
|
| 506 |
+
except Exception as e:
|
| 507 |
+
logger.exception("Sandbox execution failed: %s", e)
|
| 508 |
+
return "", f"Execution failed: {e}"
|
| 509 |
+
|
| 510 |
+
# ---------------------------
|
| 511 |
+
# Diffusers / HF codeblock helpers
|
| 512 |
+
# ---------------------------
|
| 513 |
+
CODEBLOCK_RE = re.compile(r"```(?:python)?\n(.*?)```", re.S | re.I)
|
| 514 |
+
def extract_codeblocks_from_text(text: str) -> List[str]:
|
| 515 |
+
return [m.group(1).strip() for m in CODEBLOCK_RE.finditer(text)]
|
| 516 |
+
|
| 517 |
+
def diffusers_helper_for_capsule(key: str) -> str:
|
| 518 |
+
cap = store.get_capsule(key)
|
| 519 |
+
if not cap:
|
| 520 |
+
logger.debug("diffusers_helper_for_capsule: no capsule found for %s", key)
|
| 521 |
+
return "No capsule selected or capsule not found."
|
| 522 |
+
codeblocks = extract_codeblocks_from_text(cap["text"])
|
| 523 |
+
relevant = [cb for cb in codeblocks if "diffusers" in cb or "huggingface" in cb or "transformers" in cb]
|
| 524 |
+
if not relevant:
|
| 525 |
+
logger.debug("No diffusers/transformers blocks in capsule %s", key)
|
| 526 |
+
return "No diffusers/transformers code blocks found in capsule."
|
| 527 |
+
instructions = "Found Diffusers-related code blocks:\n\n"
|
| 528 |
+
for i, cb in enumerate(relevant,1):
|
| 529 |
+
header = f"--- Code Block {i} ---\n"
|
| 530 |
+
instructions += header + cb[:2000] + ("\n\n[TRUNCATED]\n" if len(cb)>2000 else "\n\n")
|
| 531 |
+
instructions += "Ensure `pip install diffusers accelerate transformers torch` before running."
|
| 532 |
+
logger.info("diffusers helper produced %d blocks for %s", len(relevant), key)
|
| 533 |
+
return instructions
|
| 534 |
+
|
| 535 |
+
# ---------------------------
|
| 536 |
+
# PDF extraction helper
|
| 537 |
+
# ---------------------------
|
| 538 |
+
def _extract_text_from_pdf_bytes(b: bytes) -> str:
|
| 539 |
+
try:
|
| 540 |
+
from PyPDF2 import PdfReader
|
| 541 |
+
except Exception:
|
| 542 |
+
logger.warning("PyPDF2 not installed; PDF extraction unavailable.")
|
| 543 |
+
return "[PDF text extraction not available: PyPDF2 not installed]"
|
| 544 |
+
try:
|
| 545 |
+
reader = PdfReader(io.BytesIO(b))
|
| 546 |
+
texts = []
|
| 547 |
+
for i, page in enumerate(reader.pages):
|
| 548 |
+
try:
|
| 549 |
+
t = page.extract_text()
|
| 550 |
+
if t:
|
| 551 |
+
texts.append(t)
|
| 552 |
+
except Exception as e:
|
| 553 |
+
logger.debug("PDF page %d extraction error: %s", i, e)
|
| 554 |
+
continue
|
| 555 |
+
result = "\n\n".join(texts) if texts else "[No extractable text in PDF pages]"
|
| 556 |
+
logger.info("Extracted text from PDF (pages=%d, chars=%d)", len(reader.pages), len(result))
|
| 557 |
+
return result
|
| 558 |
+
except Exception as e:
|
| 559 |
+
logger.exception("PDF extraction failed: %s", e)
|
| 560 |
+
return f"[PDF extraction failed: {e}]"
|
| 561 |
+
|
| 562 |
+
# ---------------------------
|
| 563 |
+
# Routing & chat helpers
|
| 564 |
+
# ---------------------------
|
| 565 |
+
def pick_agent_and_passages(user_message: str) -> Tuple[str, List[Tuple[str, float]]]:
|
| 566 |
+
logger.debug("pick_agent_and_passages for message (chars=%d): %s", len(user_message or ""), (user_message or "")[:120])
|
| 567 |
+
store.maybe_reload()
|
| 568 |
+
# explicit "agent: <name>" pattern
|
| 569 |
+
m = re.search(r"agent[:=]\s*([a-z0-9_\-]+)", user_message.lower())
|
| 570 |
+
if m:
|
| 571 |
+
candidate = m.group(1)
|
| 572 |
+
if candidate in store.capsules:
|
| 573 |
+
passages = store.get_top_passages_for_capsule(candidate, user_message, k=TOP_K_PASSAGES)
|
| 574 |
+
logger.info("User requested explicit agent '%s' -> %d passages", candidate, len(passages))
|
| 575 |
+
return candidate, passages
|
| 576 |
+
lowered = normalize_text(user_message)
|
| 577 |
+
for key in store.list_agents():
|
| 578 |
+
if key in lowered:
|
| 579 |
+
passages = store.get_top_passages_for_capsule(key, user_message, k=TOP_K_PASSAGES)
|
| 580 |
+
logger.info("Agent key found in message: %s", key)
|
| 581 |
+
return key, passages
|
| 582 |
+
relevant = store.find_relevant_capsules(user_message, top_n=3)
|
| 583 |
+
if relevant:
|
| 584 |
+
best_key, best_score = relevant[0]
|
| 585 |
+
logger.debug("find_relevant_capsules top: %s score=%.3f", best_key, best_score)
|
| 586 |
+
if best_score < 0.03:
|
| 587 |
+
logger.debug("Best score below threshold (%.3f) -> general", best_score)
|
| 588 |
+
return "general", []
|
| 589 |
+
passages = store.get_top_passages_for_capsule(best_key, user_message, k=TOP_K_PASSAGES)
|
| 590 |
+
return best_key, passages
|
| 591 |
+
return "general", []
|
| 592 |
+
|
| 593 |
+
def build_system_prompt_for_agent(agent_key: str, mode: str, passages: List[Tuple[str, float]]) -> str:
|
| 594 |
+
agent_name = agent_key.capitalize() if agent_key else "General"
|
| 595 |
+
meta = store.get_capsule(agent_key) or {}
|
| 596 |
+
filename = meta.get("filename", "unknown")
|
| 597 |
+
passage_texts = []
|
| 598 |
+
for i,(p,score) in enumerate(passages,1):
|
| 599 |
+
excerpt = p.strip()
|
| 600 |
+
if len(excerpt)>1400: excerpt = excerpt[:1400]+"\n\n[TRUNCATED]"
|
| 601 |
+
passage_texts.append(f"--- Passage {i} (score={score:.3f}) from {filename} ---\n{excerpt}")
|
| 602 |
+
summary = store.get_or_build_summary(agent_key) if agent_key in store.capsules else ""
|
| 603 |
+
context_block = "\n\n".join(passage_texts) or f"[No direct passages matched. Capsule summary:]\n{summary or '[No summary available]'}"
|
| 604 |
+
|
| 605 |
+
if mode == "chat":
|
| 606 |
+
mask = f"""
|
| 607 |
+
You are Ohamlab β PhD-level specialist in **{agent_name}**.
|
| 608 |
+
MODE: Conversational.
|
| 609 |
+
--- CONTEXT ---
|
| 610 |
+
{context_block}
|
| 611 |
+
"""
|
| 612 |
+
elif mode == "research":
|
| 613 |
+
mask = f"""
|
| 614 |
+
You are Ohamlab β PhD-level research AI in **{agent_name}**.
|
| 615 |
+
MODE: Research / Analytical.
|
| 616 |
+
--- CONTEXT ---
|
| 617 |
+
{context_block}
|
| 618 |
+
"""
|
| 619 |
+
elif mode == "coding":
|
| 620 |
+
mask = f"""
|
| 621 |
+
You are Ohamlab β an expert **coding assistant**.
|
| 622 |
+
MODE: Debugging / Code Fixer.
|
| 623 |
+
|
| 624 |
+
User may provide: (a) code, (b) error messages, (c) questions about programming.
|
| 625 |
+
|
| 626 |
+
Your job:
|
| 627 |
+
- Carefully analyze the code and error.
|
| 628 |
+
- Explain what went wrong in simple terms.
|
| 629 |
+
- Show the corrected code (with a Python/JS block if possible).
|
| 630 |
+
- Give step-by-step reasoning why your fix works.
|
| 631 |
+
- If multiple issues, list them clearly.
|
| 632 |
+
|
| 633 |
+
--- CONTEXT ---
|
| 634 |
+
{context_block}
|
| 635 |
+
"""
|
| 636 |
+
else:
|
| 637 |
+
mask = f"You are Ohamlab β General Specialist.\n--- CONTEXT ---\n{context_block}"
|
| 638 |
+
|
| 639 |
+
logger.debug("Built system prompt for agent=%s mode=%s (context_chars=%d)", agent_key, mode, len(context_block or ""))
|
| 640 |
+
return textwrap.dedent(mask).strip()
|
| 641 |
+
|
| 642 |
+
def call_model_get_response(model_id: str, messages: list, max_tokens: int = 1200, temperature: float = 0.2):
|
| 643 |
+
start = now_ms()
|
| 644 |
+
telemetry['model_calls'] += 1
|
| 645 |
+
logger.info("Calling model %s (max_tokens=%d, temp=%s). Messages=%d", model_id, max_tokens, temperature, len(messages))
|
| 646 |
+
try:
|
| 647 |
+
resp = client.chat.completions.create(model=model_id, messages=messages, max_tokens=max_tokens, temperature=temperature)
|
| 648 |
+
choice = resp.choices[0]
|
| 649 |
+
elapsed = now_ms()-start
|
| 650 |
+
telemetry['last_call_ms'] = elapsed
|
| 651 |
+
telemetry['calls'].append({'time_ms': elapsed,'max_tokens':max_tokens,'temperature':temperature})
|
| 652 |
+
# try to use usage if present
|
| 653 |
+
usage = getattr(resp, "usage", None)
|
| 654 |
+
if usage:
|
| 655 |
+
try:
|
| 656 |
+
telemetry['tokens_used_est'] += int(usage.total_tokens)
|
| 657 |
+
logger.debug("Model usage reported: %s", usage)
|
| 658 |
+
except Exception:
|
| 659 |
+
pass
|
| 660 |
+
# fallback token estimation
|
| 661 |
+
chars = sum(len(m.get('content','')) for m in messages)
|
| 662 |
+
telemetry['tokens_used_est'] += int(chars/4)
|
| 663 |
+
response = getattr(choice.message, "content", None)
|
| 664 |
+
if not response:
|
| 665 |
+
logger.warning("LLM returned no response for model %s", model_id)
|
| 666 |
+
return "β οΈ LLM returned no response."
|
| 667 |
+
logger.info("Model call completed in %d ms; tokens_est=%d", elapsed, telemetry.get('tokens_used_est', 0))
|
| 668 |
+
return response.strip()
|
| 669 |
+
except Exception as e:
|
| 670 |
+
tb = traceback.format_exc()
|
| 671 |
+
logger.exception("Model call failed: %s", e)
|
| 672 |
+
raise RuntimeError(f"Model call failed: {e}\n{tb}")
|
| 673 |
+
|
| 674 |
+
def chat_with_model(user_message: str, chat_history_ui: List[Tuple[str,str]], selected_agent: str, mode: str):
|
| 675 |
+
"""
|
| 676 |
+
Primary chat function used by Gradio callbacks.
|
| 677 |
+
- user_message: text
|
| 678 |
+
- chat_history_ui: current Chatbot tuples
|
| 679 |
+
- selected_agent: value of agent_selector dropdown (e.g. 'general' or capsule key)
|
| 680 |
+
- mode: 'chat'|'research'|'coding'
|
| 681 |
+
Returns (cleared_input, updated_chat_history)
|
| 682 |
+
"""
|
| 683 |
+
if not user_message or not str(user_message).strip():
|
| 684 |
+
logger.debug("chat_with_model called with empty message.")
|
| 685 |
+
return "", chat_history_ui
|
| 686 |
+
try:
|
| 687 |
+
# If user explicitly selected an agent via UI, prefer it. Otherwise pick via content.
|
| 688 |
+
if selected_agent and selected_agent != "general":
|
| 689 |
+
agent_key = selected_agent
|
| 690 |
+
passages = store.get_top_passages_for_capsule(agent_key, user_message, k=TOP_K_PASSAGES)
|
| 691 |
+
logger.debug("User selected agent %s", agent_key)
|
| 692 |
+
else:
|
| 693 |
+
agent_key, passages = pick_agent_and_passages(user_message)
|
| 694 |
+
logger.debug("Auto-picked agent %s", agent_key)
|
| 695 |
+
|
| 696 |
+
system_prompt = build_system_prompt_for_agent(agent_key, mode, passages)
|
| 697 |
+
history_msgs_struct = conv_manager.get_history(agent_key)
|
| 698 |
+
# Convert our stored history (list of dicts) into model messages
|
| 699 |
+
msgs_for_model = [{"role":"system","content":system_prompt}]
|
| 700 |
+
msgs_for_model += history_msgs_struct
|
| 701 |
+
msgs_for_model.append({"role":"user","content":user_message})
|
| 702 |
+
|
| 703 |
+
max_toks = RESEARCH_MAX_TOKENS if mode == "research" else (CODING_MAX_TOKENS if mode == "coding" else CHAT_MAX_TOKENS)
|
| 704 |
+
reply = call_model_get_response(MODEL_ID, msgs_for_model, max_tokens=max_toks, temperature=0.15 if mode!="research" else 0.0)
|
| 705 |
+
|
| 706 |
+
# Append to conversation manager
|
| 707 |
+
conv_manager.append(agent_key, "user", user_message)
|
| 708 |
+
conv_manager.append(agent_key, "assistant", reply)
|
| 709 |
+
|
| 710 |
+
chat_history_ui = chat_history_ui + [(user_message, reply)]
|
| 711 |
+
logger.info("chat_with_model: responded for agent=%s mode=%s", agent_key, mode)
|
| 712 |
+
return "", chat_history_ui
|
| 713 |
+
except Exception as e:
|
| 714 |
+
tb = traceback.format_exc()
|
| 715 |
+
logger.exception("chat_with_model ERROR: %s", e)
|
| 716 |
+
return f"[ERROR] {e}\n{tb}", chat_history_ui
|
| 717 |
+
|
| 718 |
+
# ---------------------------
|
| 719 |
+
# UI & callbacks
|
| 720 |
+
# ---------------------------
|
| 721 |
+
def reset_agent_ui(selected_agent: str):
|
| 722 |
+
conv_manager.reset_agent(selected_agent)
|
| 723 |
+
return []
|
| 724 |
+
|
| 725 |
+
def reset_all_ui():
|
| 726 |
+
conv_manager.reset_all()
|
| 727 |
+
return []
|
| 728 |
+
|
| 729 |
+
def refresh_capsules_ui():
|
| 730 |
+
logger.info("UI requested refresh_capsules_ui")
|
| 731 |
+
store.refresh_all()
|
| 732 |
+
return gr.update(choices=["general"] + store.list_agents())
|
| 733 |
+
|
| 734 |
+
from typing import Tuple
|
| 735 |
+
|
| 736 |
+
def add_uploaded_pdf_as_capsule(filepath) -> Tuple[str, dict]:
|
| 737 |
+
"""
|
| 738 |
+
Add uploaded PDF as a new capsule and return updated agent selector choices.
|
| 739 |
+
"""
|
| 740 |
+
if not filepath:
|
| 741 |
+
logger.warning("add_uploaded_pdf_as_capsule: no file provided")
|
| 742 |
+
return "β οΈ No file uploaded", gr.update()
|
| 743 |
+
try:
|
| 744 |
+
capsule_name = os.path.splitext(os.path.basename(filepath))[0]
|
| 745 |
+
store.add_pdf_capsule(capsule_name, filepath)
|
| 746 |
+
new_choices = ["general"] + store.list_agents()
|
| 747 |
+
logger.info("Added PDF capsule via UI: %s", capsule_name)
|
| 748 |
+
return f"β
Added PDF Capsule: {capsule_name}", gr.update(choices=new_choices, value=capsule_name)
|
| 749 |
+
except Exception as e:
|
| 750 |
+
logger.exception("Failed to add PDF capsule: %s", e)
|
| 751 |
+
return f"β Failed to add PDF: {str(e)}", gr.update()
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def copy_all_chat(chat_list):
|
| 755 |
+
return "\n\n".join([f"{u}:\n{a}" for u,a in chat_list])
|
| 756 |
+
|
| 757 |
+
def chat_to_markdown(chat_list):
|
| 758 |
+
md_lines = []
|
| 759 |
+
for u, a in chat_list:
|
| 760 |
+
md_lines.append(f"**{u}**\n```\n{a}\n```")
|
| 761 |
+
return "\n\n".join(md_lines)
|
| 762 |
+
|
| 763 |
+
# ---------------------------
|
| 764 |
+
# Build Gradio app
|
| 765 |
+
# ---------------------------
|
| 766 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 767 |
+
gr.Markdown("<h2 style='text-align:center;'>π€ Ohamlab AI β PhD Specialist Multi-Agent Shell</h2>")
|
| 768 |
+
|
| 769 |
+
# Top controls
|
| 770 |
+
with gr.Row():
|
| 771 |
+
agent_selector = gr.Dropdown(choices=["general"] + store.list_agents(), value="general", label="Select Agent", interactive=True)
|
| 772 |
+
mode_selector = gr.Radio(choices=["chat","research","coding"], value="chat", label="Conversation Mode", interactive=True)
|
| 773 |
+
refresh_btn = gr.Button("π Refresh Capsules")
|
| 774 |
+
summary_btn = gr.Button("π Show Capsule Summary")
|
| 775 |
+
diff_btn = gr.Button("π Show Diffusers Helper")
|
| 776 |
+
|
| 777 |
+
# PDF Upload
|
| 778 |
+
with gr.Row():
|
| 779 |
+
pdf_upload = gr.File(file_types=[".pdf"], type="filepath", label="π Upload a PDF (file path)", interactive=True)
|
| 780 |
+
upload_status = gr.Textbox(label="Upload Status", interactive=False)
|
| 781 |
+
|
| 782 |
+
# Chat window
|
| 783 |
+
chat_window = gr.Chatbot([], label="Conversation", height=600, type="tuples", show_copy_button=True)
|
| 784 |
+
|
| 785 |
+
# Input row
|
| 786 |
+
with gr.Row():
|
| 787 |
+
user_input = gr.Textbox(placeholder="Type your message here...", lines=3)
|
| 788 |
+
send_btn = gr.Button("π Send")
|
| 789 |
+
|
| 790 |
+
# Bottom controls
|
| 791 |
+
with gr.Row():
|
| 792 |
+
clear_agent_btn = gr.Button("π§Ή Clear Agent History")
|
| 793 |
+
clear_all_btn = gr.Button("π§Ό Reset All Histories")
|
| 794 |
+
copy_btn = gr.Button("π Copy All")
|
| 795 |
+
share_md_btn = gr.Button("π Share as Markdown")
|
| 796 |
+
|
| 797 |
+
# Summary & diff output boxes (static)
|
| 798 |
+
summary_output = gr.Textbox(lines=10, interactive=False, label="Capsule Summary")
|
| 799 |
+
diff_output = gr.Textbox(lines=12, interactive=False, label="Diffusers Helper")
|
| 800 |
+
copied_output = gr.Textbox(label="Copied Chat", interactive=True)
|
| 801 |
+
md_export_output = gr.Textbox(label="Markdown Export", interactive=True)
|
| 802 |
+
|
| 803 |
+
# Callbacks wiring
|
| 804 |
+
refresh_btn.click(fn=refresh_capsules_ui, outputs=[agent_selector])
|
| 805 |
+
|
| 806 |
+
pdf_upload.upload(fn=add_uploaded_pdf_as_capsule, inputs=[pdf_upload], outputs=[upload_status, agent_selector])
|
| 807 |
+
|
| 808 |
+
# Send (pass agent and mode)
|
| 809 |
+
send_btn.click(fn=chat_with_model, inputs=[user_input, chat_window, agent_selector, mode_selector], outputs=[user_input, chat_window])
|
| 810 |
+
user_input.submit(fn=chat_with_model, inputs=[user_input, chat_window, agent_selector, mode_selector], outputs=[user_input, chat_window])
|
| 811 |
+
|
| 812 |
+
clear_agent_btn.click(fn=reset_agent_ui, inputs=[agent_selector], outputs=[chat_window])
|
| 813 |
+
clear_all_btn.click(fn=reset_all_ui, inputs=None, outputs=[chat_window])
|
| 814 |
+
|
| 815 |
+
summary_btn.click(fn=lambda a: store.get_or_build_summary(a) if a in store.capsules else "No capsule selected.", inputs=[agent_selector], outputs=[summary_output])
|
| 816 |
+
diff_btn.click(fn=diffusers_helper_for_capsule, inputs=[agent_selector], outputs=[diff_output])
|
| 817 |
+
|
| 818 |
+
copy_btn.click(fn=copy_all_chat, inputs=[chat_window], outputs=[copied_output])
|
| 819 |
+
share_md_btn.click(fn=chat_to_markdown, inputs=[chat_window], outputs=[md_export_output])
|
| 820 |
+
|
| 821 |
+
# Show loaded capsules
|
| 822 |
+
capsule_md = "### Loaded Agents / Capsules\n\n" + "\n".join([f"- **{k}** (file: `{v['filename']}`)" for k,v in store.capsules.items()])
|
| 823 |
+
gr.Markdown(capsule_md)
|
| 824 |
+
|
| 825 |
+
# ---------------------------
|
| 826 |
+
# Run
|
| 827 |
+
# ---------------------------
|
| 828 |
+
if __name__ == "__main__":
|
| 829 |
+
logger.info("Launching Gradio app.")
|
| 830 |
+
demo.launch(server_name="0.0.0.0", share=False)
|