""" model_registry.py — Central registry of model choices (LLM / VLM / STT / visual retriever) shown in the UI dropdowns, plus shared path/size constants, and the "rescan GGUF folder" action that rebuilds MODEL_OPTIONS at runtime. """ import os import re from typing import Optional from backend import llama_backend from backend import user_config from backend import whisper_cpp_backend from backend.hardware import HardwareManager from backend.paths import user_data_dir from ui.i18n import LANGUAGES # ────────────────────────────────────────────────────────────────── # Provider sentinels — each model type can run via one of three # backends. Persisted per‑tab so every chat tab can pick its own. # ────────────────────────────────────────────────────────────────── PROVIDER_LOCAL_HF = "__provider_local_hf__" PROVIDER_LLAMA_CPP_PYTHON = "__provider_llama_cpp_python__" PROVIDER_SERVER = "__provider_server__" PROVIDER_HF_API = "__provider_hf_api__" PROVIDER_LITELLM = "__provider_litellm__" # Label -> sentinel — shared UI labels that use the sentinel when # the model is configured through the shared HF fields below. HF_API_ENTRY_LABEL = "🌐 Hugging Face Inference API (remote)" HF_INFERENCE_API_SENTINEL = "__hf_inference_api__" # Fixed remote defaults for the HF Inference API sentinel path. The # Settings '🤗 HF Model ID' field is gone — the per-tab curated pickers # (hf_api_models.csv) are the ONLY HF API model selector — so these keep # the sentinel path (STT / embedding model types have no curated catalog) # usable with a sensible model of the right type when nothing was ever # saved. The curated LLM/VLM pickers never hit these (they send their own # id directly). HF_API_DEFAULT_LLM_ID = "deepseek-ai/DeepSeek-V4-Flash-0731" HF_API_DEFAULT_VLM_ID = "Qwen/Qwen3-VL-30B-A3B-Instruct" HF_API_DEFAULT_STT_ID = "openai/whisper-small" HF_API_DEFAULT_EMBED_ID = "BAAI/bge-m3" # Curated remote text-generation models for the Hugging Face Inference # API — loaded from hf_api_models.csv (label -> model_id, same external- # registry pattern as the local hf_models.csv). These power the searchable # "🤗 HF Model ID" dropdown in Settings so users pick a known remote model # (DeepSeek-V4-Flash, Kimi-K3, GLM-5.2, …) instead of typing from memory. # Kept SEPARATE from BASE_MODEL_OPTIONS: hf_models.csv entries are LOCAL # downloads; the HF Inference API is a remote inference endpoint with its # own model catalog. HF_API_MODEL_OPTIONS: dict[str, str] = {} LITELLM_ENTRY_LABEL = "🔗 LiteLLM (OpenAI/Anthropic/Groq/…)" LITELLM_SENTINEL = "__litellm__" LLM_PROVIDER_OPTIONS = { "🧩 Local HuggingFace": PROVIDER_LOCAL_HF, "🦙 llama-cpp-python (in-process)": PROVIDER_LLAMA_CPP_PYTHON, "🖥️ llama.cpp server": PROVIDER_SERVER, "🌐 HF Inference API": PROVIDER_HF_API, "🔗 LiteLLM (OpenAI/Anthropic/…)": PROVIDER_LITELLM, } VLM_PROVIDER_OPTIONS = { "🧩 Local HuggingFace": PROVIDER_LOCAL_HF, "🦙 llama-cpp-python (in-process)": PROVIDER_LLAMA_CPP_PYTHON, "🖥️ llama.cpp server": PROVIDER_SERVER, "🌐 HF Inference API": PROVIDER_HF_API, } STT_PROVIDER_OPTIONS = { "🧩 Local HuggingFace": PROVIDER_LOCAL_HF, "🦙 whisper-cpp (in-process)": PROVIDER_LLAMA_CPP_PYTHON, "🖥️ whisper.cpp server": PROVIDER_SERVER, "🌐 HF Inference API": PROVIDER_HF_API, } EMBED_PROVIDER_OPTIONS = { "🧩 Local HuggingFace": PROVIDER_LOCAL_HF, "🦙 llama-cpp-python (in-process)": PROVIDER_LLAMA_CPP_PYTHON, "🖥️ llama.cpp server": PROVIDER_SERVER, "🌐 HF Inference API": PROVIDER_HF_API, } # Per-tab provider persistence keys. _PROVIDER_KEYS = { "gen": "provider_gen", "rag": "provider_rag", "data": "provider_data", "dr": "provider_dr", "vlm": "provider_vlm", "stt": "provider_stt", "embed": "provider_embed", # The STT tab's transcript→report analysis LLM — its own provider/model # dropdown inside the STT tab (saved under "stt_report"). chat.py's # analyse_transcript_to_report reads this key; without it the pick never # persisted and the report always used the default provider. "stt_report": "provider_stt_report", } _DEFAULT_PROVIDER = PROVIDER_LOCAL_HF # Per-tab MODEL persistence keys — the dropdown LABEL the user last chose # for each tab, paired 1:1 with _PROVIDER_KEYS (a model label is only # meaningful relative to its tab's provider). Unlike providers, which are # validated against a fixed sentinel set, a model label is validated # against the LIVE per-provider choices at read time (GGUF discovery / CSV # can change the catalog between sessions) — see get_saved_model / the # /api/meta consumption in web_api.py, which falls back to the provider's # default model when the saved label is no longer a choice. _MODEL_KEYS = { "gen": "model_gen", "rag": "model_rag", "data": "model_data", "dr": "model_dr", "vlm": "model_vlm", "stt": "model_stt", "embed": "model_embed", "stt_report": "model_stt_report", } def get_saved_provider(tab_key: str) -> str: """Persisted provider sentinel for a tab, falling back to local HF.""" config_key = _PROVIDER_KEYS.get(tab_key) if config_key is None: return _DEFAULT_PROVIDER return str(user_config.USER_CONFIG.get(config_key, _DEFAULT_PROVIDER)) def set_saved_provider(tab_key: str, sentinel: str) -> None: config_key = _PROVIDER_KEYS.get(tab_key) if config_key: user_config.save_user_config({config_key: sentinel}) def get_saved_model(tab_key: str) -> str: """The persisted model LABEL for a tab, or '' when nothing was saved. The caller validates it against the tab's current per-provider choices (a GGUF file removed / CSV edited between sessions makes a stale label invalid); an empty string means "no explicit pick — use the default".""" config_key = _MODEL_KEYS.get(tab_key) if config_key is None: return "" return str(user_config.USER_CONFIG.get(config_key, "") or "") def set_saved_model(tab_key: str, label: str) -> None: """Persist the model LABEL a tab should reopen on. Unknown tabs are ignored (never stored); an empty label clears the pick back to the provider default.""" config_key = _MODEL_KEYS.get(tab_key) if config_key: user_config.save_user_config({config_key: str(label or "")}) def get_provider_label(provider_map: dict, sentinel: str) -> str: """Reverse‑lookup the dropdown label for a provider sentinel.""" for label, val in provider_map.items(): if val == sentinel: return label return next(iter(provider_map)) # ────────────────────────────────────────────────────────────────── # Model‑list filtering — each provider shows a different set of # model choices in the dropdown. # ────────────────────────────────────────────────────────────────── # Whether THIS machine can run a model bigger than the small Gemma-4-E2B # (a real GPU tier, 8 GB+ VRAM). Detected ONCE at import — the same pattern # as the DEFAULT_LLM_LABEL / DEFAULT_EMBED_MODEL tier ladders — so the # per-request /api/meta path (get_model_dropdown_defaults) never re-probes # hardware (nvidia-smi / WMI) on every call. CPU-only / unknown hardware # keeps the small E2B default everywhere. _DATA_AGENT_HW_STRONG = HardwareManager.detect_hardware_tier() not in ( HardwareManager.TIER_CPU_ONLY, HardwareManager.TIER_UNKNOWN, ) def get_data_agent_default_label(provider: str) -> str: """Default LLM label for the Data Analysis tab's CodeAgent. The Data tab runs a smolagents CodeAgent that writes and executes Python, so it needs a genuinely capable model — the app's documented agentic threshold is Gemma-4-E4B+. On 8 GB+ hardware the Data tab therefore defaults to Gemma-4-E4B (never the small E2B, which is what the CSV default / GGUF first-choice would otherwise give every machine); on CPU-only / unknown hardware E2B stays the safe default. The llama.cpp/GGUF providers use the E2B/E4B QAT Q4_0 presets — the official QAT family the Data agent has been verified on (tools/run_data_tool_test.py); Local HuggingFace uses the E4B / E2B instruct checkpoints. Falls back to the global default when the preferred label is missing from the registry. """ if provider in (PROVIDER_SERVER, PROVIDER_LLAMA_CPP_PYTHON): wanted = ("google/gemma-4-E4B-it-qat-q4_0-gguf" if _DATA_AGENT_HW_STRONG else "google/gemma-4-E2B-it-qat-q4_0-gguf") lbl = _label_for_model_id(wanted, PRESET_GGUF_MODELS) if lbl: return lbl else: wanted = "google/gemma-4-E4B-it" if _DATA_AGENT_HW_STRONG else "google/gemma-4-E2B-it" lbl = _label_for_model_id(wanted, BASE_MODEL_OPTIONS) if lbl: return lbl return DEFAULT_LLM_LABEL def _hf_api_default_label(model_type: str) -> str: """The default model dropdown label for the HF Inference API provider. The per-tab pickers are the only HF API model selector (the Settings '🤗 HF Model ID' field is gone), so the default is always a curated entry: a legacy saved Settings id when it still maps to a curated catalog entry (existing installs keep their model), else the headline remote model for the model type (DeepSeek-V4-Flash for LLM tabs, a Qwen3-VL vision model for the Vision tab).""" saved = get_saved_hf_model_id() if saved: base = saved.split(":", 1)[0] for label, mid in HF_API_MODEL_OPTIONS.items(): if mid == saved or mid.split(":", 1)[0] == base: return label wanted = HF_API_DEFAULT_VLM_ID if model_type == "vlm" else HF_API_DEFAULT_LLM_ID for label, mid in HF_API_MODEL_OPTIONS.items(): if mid == wanted: return label return next(iter(HF_API_MODEL_OPTIONS), "") if HF_API_MODEL_OPTIONS else "" def get_model_dropdown_defaults(tab_key: str, model_type: str) -> tuple: """Return (choices, default_value) for the *model_type* dropdown of *tab_key* filtered by the tab's saved provider (so e.g. the Vision tab only lists GGUF VLM pairs when the provider is llama.cpp, instead of mixing in HuggingFace models). Falls back to the model type's default label when it's present in the filtered set, otherwise to the first valid choice.""" provider = get_saved_provider(tab_key) choices = list(get_model_options_for_provider(provider, model_type).keys()) if provider == PROVIDER_HF_API and model_type in ("llm", "vlm"): default_label = _hf_api_default_label(model_type) elif tab_key == "data" and model_type == "llm": default_label = get_data_agent_default_label(provider) elif model_type == "vlm": default_label = DEFAULT_VLM_LABEL elif model_type == "stt": default_label = DEFAULT_STT_LABEL elif model_type == "embed": default_label = get_default_embed_label(provider) else: default_label = DEFAULT_LLM_LABEL default_value = default_label if default_label in choices else (choices[0] if choices else None) return choices, default_value def get_llm_dropdown_defaults(tab_key: str) -> tuple: """Return (choices, default_value) for the LLM dropdown of *tab_key* filtered by the tab's saved provider. Falls back to the first valid choice when DEFAULT_LLM_LABEL is not in the filtered set.""" return get_model_dropdown_defaults(tab_key, "llm") PRESET_GGUF_MODELS: dict[str, str] = { "🦙 Gemma-4-E2B QAT Q4_0 (~1.8 GB download | GGUF | HF Hub)": "google/gemma-4-E2B-it-qat-q4_0-gguf", "🦙 Gemma-4-E4B QAT Q4_0 (~2.8 GB download | GGUF | HF Hub)": "google/gemma-4-E4B-it-qat-q4_0-gguf", "🦙 Gemma-4-12B QAT Q4_0 (~7.5 GB download | GGUF | HF Hub)": "google/gemma-4-12B-it-qat-q4_0-gguf", "🦙 Gemma-4-26B-A4B QAT Q4_0 (~15.2 GB download | MoE GGUF | HF Hub)": "google/gemma-4-26B-A4B-it-qat-q4_0-gguf", "🦙 Gemma-4-31B QAT Q4_0 (~18.5 GB download | GGUF | HF Hub)": "google/gemma-4-31B-it-qat-q4_0-gguf", } def get_model_options_for_provider(provider: str, model_type: str) -> dict: """Return the label→model_id dict that should appear in the dropdown for *model_type* ('llm' / 'vlm' / 'stt' / 'embed') when the user has chosen *provider*.""" if provider == PROVIDER_HF_API: # Curated HF Inference API catalog (hf_api_models.csv) — when the # user picks the HF API provider the model dropdown lists the actual # remote models (DeepSeek-V4-Flash, GLM-5.2, Qwen3.6-27B, …) so each # tab picks its own. The per-tab pickers are the ONLY HF API model # selector (the Settings '🤗 HF Model ID' field was removed), so the # LLM/VLM list is the curated catalog alone — no sentinel entry, no # custom/free-text model. Only LLM/VLM model types have a curated # remote catalog here; whisper-STT and embedding models have no chat # models in it, so those keep the single Settings-backed entry, # which maps to the fixed per-type remote default (see # get_hf_api_model_id_for). if model_type == "llm": return dict(HF_API_MODEL_OPTIONS) if model_type == "vlm": # Only show VLM-capable models in the Vision tab — text-only # remote models would just burn an API call without seeing images. return {k: v for k, v in HF_API_MODEL_OPTIONS.items() if is_multimodal_model(v, provider=PROVIDER_HF_API) or any(kw in v.lower() for kw in ( "vision", "vl-", "vlm", "smolvlm", "gemma-4", "qwen2.5-vl", "qwen3-vl", ))} return {HF_API_ENTRY_LABEL: HF_INFERENCE_API_SENTINEL} if provider == PROVIDER_LITELLM: return {LITELLM_ENTRY_LABEL: LITELLM_SENTINEL} if provider in (PROVIDER_SERVER, PROVIDER_LLAMA_CPP_PYTHON): if model_type == "llm": out = {} for k, v in llama_backend.discover_gguf_models().items(): out[k] = v for k, v in PRESET_GGUF_MODELS.items(): if v not in out.values(): out[k] = v return out elif model_type == "vlm": out = {} for k, (mpath, _) in llama_backend.discover_gguf_vlm_models().items(): out[k] = mpath for k, v in PRESET_GGUF_MODELS.items(): if v not in out.values(): out[k] = v # VLM-only GGUF presets (gguf_models.csv 'vlm' category — e.g. the # Qwen3-VL GGUF repos) — the multimodal text models in # PRESET_GGUF_MODELS also work as VLMs, but a vision-only preset # must still appear in the Vision dropdown under llama.cpp # providers. for k, v in PRESET_GGUF_VLM_MODELS.items(): if v not in out.values(): out[k] = v return out elif model_type == "stt": out = {} for k, v in whisper_cpp_backend.discover_whisper_models().items(): out[k] = v for k, v in PRESET_GGUF_STT_MODELS.items(): if v not in out.values(): out[k] = v return out elif model_type == "embed": return dict(PRESET_GGUF_EMBED_MODELS) return {} # PROVIDER_LOCAL_HF — only local HF entries from hf_models.csv (no .gguf, no remote API sentinels) if model_type == "llm": return {k: v for k, v in BASE_MODEL_OPTIONS.items() if v not in (HF_INFERENCE_API_SENTINEL, LITELLM_SENTINEL)} elif model_type == "vlm": return {k: v for k, v in BASE_VLM_OPTIONS.items() if v not in (HF_INFERENCE_API_SENTINEL, LITELLM_SENTINEL)} elif model_type == "stt": return dict(STT_OPTIONS) elif model_type == "embed": return dict(EMBED_OPTIONS) return {} def resolve_stt_model_id(model_label: str, provider: Optional[str] = None) -> str: """Resolve an STT dropdown LABEL to the model id/path its provider needs. The web endpoints used to resolve through STT_OPTIONS alone — the LOCAL HuggingFace list — so a whisper.cpp-server label (a discovered local file or a GGUF STT preset like 'ggerganov/whisper.cpp#ggml-base.bin') never resolved and every transcribe/load call silently fell back to DEFAULT_STT_MODEL. This resolver covers ALL providers' option sources, and for the llama.cpp/whisper.cpp server providers turns a repo-style id into a CONCRETE local file path when one is already on disk (the whisper backends take a filesystem path, never a repo id). An id whose file is missing stays a repo id so /api/model-check can offer the download. """ label = str(model_label or "").strip() prov = provider or get_saved_provider("stt") mid = "" if prov in (PROVIDER_SERVER, PROVIDER_LLAMA_CPP_PYTHON): mid = get_model_options_for_provider(prov, "stt").get(label, "") if mid: local = _find_local_stt_file(mid) if local: return local if not mid: mid = STT_OPTIONS.get(label, "") return mid or label def _find_local_stt_file(model_id: str) -> str: """Locate a downloaded repo-style STT id on disk ('repo#file.bin', 'repo/file.gguf', or a bare filename) and return its concrete path. Searches every standard model folder via llama_backend.find_downloaded_model_file. Returns '' when the file is not downloaded yet (the caller keeps the repo id so the download flow can pick it up) or when the id is not file-shaped (a plain HF repo id that transformers loads directly must pass through untouched). """ filename = model_id.split("#", 1)[1] if "#" in model_id else model_id.rsplit("/", 1)[-1] filename = filename.strip() if (not filename or "/" in filename or "#" in filename or not filename.lower().endswith((".bin", ".ggml", ".gguf"))): return "" return llama_backend.find_downloaded_model_file(filename) def get_model_label_for_id(options: dict, model_id: str, fallback: str) -> str: """Reverse‑lookup a model dropdown label from its value.""" for label, val in options.items(): if val == model_id: return label return fallback # ────────────────────────────────────────────────────────────────── # Shared constants # ────────────────────────────────────────────────────────────────── # Embedding model — dynamic default based on detected hardware tier, # mirroring the "Embedding Model" column of README.md's "Model combos by # hardware tier" table exactly: # CPU-only / 8GB / 16GB VRAM -> BGE-M3 (small, works everywhere) # 24GB VRAM -> Qwen3-Embedding-4B # 48GB+ VRAM -> Jina Embeddings v4 # Unknown hardware (detection failed) falls back to BGE-M3 — the safest # default, since guessing a larger embedding model on unknown hardware # risks an OOM on the very first index/query call. # # This only changes the DEFAULT — like context_window (see # get_saved_context_window() below), a value the user explicitly saved # to user_config.json always wins over the hardware-detected default, so # switching hardware tiers never silently overrides a deliberate choice. # ────────────────────────────────────────────────────────────────── _BACKEND_DIR = os.path.dirname(os.path.abspath(__file__)) _ROOT_DIR = os.path.dirname(_BACKEND_DIR) MODEL_CSV_ALT_PATH = ( os.path.join(_BACKEND_DIR, "hf_models.csv") if os.path.exists(os.path.join(_BACKEND_DIR, "hf_models.csv")) else os.path.join(_ROOT_DIR, "hf_models.csv") ) MODEL_CSV_PATH = ( os.path.join(_BACKEND_DIR, "models.csv") if os.path.exists(os.path.join(_BACKEND_DIR, "models.csv")) else os.path.join(_ROOT_DIR, "models.csv") ) GGUF_MODEL_CSV_ALT_PATH = ( os.path.join(_BACKEND_DIR, "gguf_models.csv") if os.path.exists(os.path.join(_BACKEND_DIR, "gguf_models.csv")) else os.path.join(_ROOT_DIR, "gguf_models.csv") ) HF_API_MODEL_CSV_ALT_PATH = ( os.path.join(_BACKEND_DIR, "hf_api_models.csv") if os.path.exists(os.path.join(_BACKEND_DIR, "hf_api_models.csv")) else os.path.join(_ROOT_DIR, "hf_api_models.csv") ) BASE_MODEL_OPTIONS: dict[str, str] = {} BASE_VLM_OPTIONS: dict[str, str] = {} EMBED_OPTIONS: dict[str, str] = {} STT_OPTIONS: dict[str, str] = {} PRESET_GGUF_MODELS: dict[str, str] = {} PRESET_GGUF_VLM_MODELS: dict[str, str] = {} PRESET_GGUF_EMBED_MODELS: dict[str, str] = {} PRESET_GGUF_STT_MODELS: dict[str, str] = {} GEMMA4_IDS: set[str] = set() GPTQ_AWQ_IDS: set[str] = set() DOWNLOAD_SIZE_GB: dict[str, float] = {} CSV_DEFAULT_LLM_LABEL: Optional[str] = None CSV_DEFAULT_VLM_LABEL: Optional[str] = None CSV_DEFAULT_EMBED_MODEL: Optional[str] = None CSV_DEFAULT_STT_LABEL: Optional[str] = None def load_models_from_csv(csv_path: Optional[str] = None) -> None: """Load all model options, architecture guards, and download sizes dynamically from models.csv (or hf_models.csv) so users can add, remove, or edit models easily without changing code. """ global CSV_DEFAULT_LLM_LABEL, CSV_DEFAULT_VLM_LABEL, CSV_DEFAULT_EMBED_MODEL, CSV_DEFAULT_STT_LABEL path = csv_path if not path: path = MODEL_CSV_ALT_PATH if os.path.exists(MODEL_CSV_ALT_PATH) else MODEL_CSV_PATH BASE_MODEL_OPTIONS.clear() BASE_VLM_OPTIONS.clear() EMBED_OPTIONS.clear() STT_OPTIONS.clear() GEMMA4_IDS.clear() GPTQ_AWQ_IDS.clear() DOWNLOAD_SIZE_GB.clear() CSV_DEFAULT_LLM_LABEL = None CSV_DEFAULT_VLM_LABEL = None CSV_DEFAULT_EMBED_MODEL = None CSV_DEFAULT_STT_LABEL = None if os.path.exists(path): import csv with open(path, "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: cat = str(row.get("category", "")).strip().lower() label = str(row.get("label", "")).strip() model_id = str(row.get("model_id", "")).strip() size_str = str(row.get("download_size_gb", "")).strip() is_default = str(row.get("default", "")).strip().lower() in ("default", "true", "1", "yes") if not label or not model_id: continue if size_str: try: DOWNLOAD_SIZE_GB[model_id] = float(size_str) except ValueError: pass mid_lower = model_id.lower() if "gemma-4" in mid_lower or "gemma4" in mid_lower: GEMMA4_IDS.add(model_id) if any(kw in mid_lower for kw in ("4bit", "3bit", "bnb", "mlx", "qat", "ct", "gptq", "awq")): GPTQ_AWQ_IDS.add(model_id) if cat in ("both", "llm"): BASE_MODEL_OPTIONS[label] = model_id if is_default and not CSV_DEFAULT_LLM_LABEL: CSV_DEFAULT_LLM_LABEL = label if cat in ("both", "vlm"): BASE_VLM_OPTIONS[label] = model_id if is_default and not CSV_DEFAULT_VLM_LABEL: CSV_DEFAULT_VLM_LABEL = label if cat == "embed": EMBED_OPTIONS[label] = model_id if is_default and not CSV_DEFAULT_EMBED_MODEL: CSV_DEFAULT_EMBED_MODEL = model_id if cat == "stt": STT_OPTIONS[label] = model_id if is_default and not CSV_DEFAULT_STT_LABEL: CSV_DEFAULT_STT_LABEL = label # Built-in fallbacks if CSV file was missing or empty if not BASE_MODEL_OPTIONS: BASE_MODEL_OPTIONS["🧠 Gemma-4-E2B Mobile QAT (2.18 GB download | CPU/edge tier)"] = "google/gemma-4-E2B-it-qat-mobile-transformers" BASE_MODEL_OPTIONS["🔵 Gemma-4-E2B (4.8 GB download → 3 GB VRAM @4-bit | CPU/<8GB tier)"] = "google/gemma-4-E2B-it" BASE_MODEL_OPTIONS["🟢 Gemma-4-E4B (7.4 GB download → 5 GB VRAM @4-bit | 8-12GB tier)"] = "google/gemma-4-E4B-it" BASE_MODEL_OPTIONS["🔴 Gemma-4-26B-A4B QAT (26 GB download | QAT-optimized MoE)"] = "google/gemma-4-26B-A4B-it-qat-q4_0-unquantized" GEMMA4_IDS.update(BASE_MODEL_OPTIONS.values()) if not BASE_VLM_OPTIONS: BASE_VLM_OPTIONS["🧠 Gemma-4-E2B Mobile QAT (2.18 GB download | CPU/edge tier)"] = "google/gemma-4-E2B-it-qat-mobile-transformers" BASE_VLM_OPTIONS["🟢 Gemma-4-E4B (7.4 GB download → 5 GB VRAM @4-bit | 8-12GB tier)"] = "google/gemma-4-E4B-it" if not EMBED_OPTIONS: EMBED_OPTIONS["BGE-M3 (2.2 GB download | multilingual, recommended default)"] = "BAAI/bge-m3" if not STT_OPTIONS: STT_OPTIONS["🟢 Whisper-tiny (0.04 GB download | fastest)"] = "openai/whisper-tiny" STT_OPTIONS["🟡 Whisper-small (0.23 GB download | recommended)"] = "openai/whisper-small" STT_OPTIONS["🇰🇭 Whisper-small — ខ្មែរ (0.23 GB download | Khmer-tuned)"] = "seanghay/whisper-small-khmer-v2" def load_hf_api_models_from_csv(csv_path: Optional[str] = None) -> None: """Load the curated Hugging Face Inference API model list from hf_api_models.csv (label -> model_id) so users can add/remove remote model options without touching Python code — same external-registry pattern as hf_models.csv / gguf_models.csv. Populates HF_API_MODEL_OPTIONS; missing/empty CSV degrades to an empty list (the Settings HF Model ID field stays a plain free-text input). Optional `price_in_usd` / `price_out_usd` columns (minimum USD per 1M tokens across the providers that serve the model) are appended to the LABEL as "— $X/M in · $Y/M out" so the price shows next to the model in the picker. The VALUE stays the raw model id, so selection and the API call are unaffected.""" path = csv_path or HF_API_MODEL_CSV_ALT_PATH HF_API_MODEL_OPTIONS.clear() if os.path.exists(path): import csv with open(path, "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: label = str(row.get("label", "")).strip() model_id = str(row.get("model_id", "")).strip() if not label or not model_id: continue price_in = str(row.get("price_in_usd", "")).strip() price_out = str(row.get("price_out_usd", "")).strip() if price_in or price_out: bits = [] if price_in: bits.append(f"${price_in}/M in") if price_out: bits.append(f"${price_out}/M out") label = f"{label} — {' · '.join(bits)}" HF_API_MODEL_OPTIONS[label] = model_id def get_hf_api_model_options() -> dict: """label -> model_id dict of curated HF Inference API models (from hf_api_models.csv), used by the Settings '🤗 HF Model ID' searchable dropdown. The VALUES are the model ids saved to user_config's hf_model_id key; users may still type any custom model id. Labels may carry a "— $X/M in · $Y/M out" price suffix (see load_hf_api_models_from_csv).""" return dict(HF_API_MODEL_OPTIONS) def get_hf_api_model_ids() -> list: """Deduped model-id list of the curated HF Inference API models — the datalist option VALUES for the Settings HF Model ID dropdown (the price-carrying labels are only for display; the id is what's saved).""" seen: list = [] for label, mid in HF_API_MODEL_OPTIONS.items(): if mid not in seen: seen.append(mid) return seen def get_hf_api_model_choices() -> list: """[{value, label}] pairs for the Settings '🤗 HF Model ID' picker — `label` is the display text (model name + provider list + price suffix), `value` is the raw model id so selecting a choice saves the id, not the label. Mirrors the Gradio datalist's value/label split.""" return [{"value": model_id, "label": label} for label, model_id in HF_API_MODEL_OPTIONS.items()] def load_gguf_models_from_csv(csv_path: Optional[str] = None) -> None: """Load preset GGUF models dynamically from gguf_models.csv so users can edit or add options easily.""" path = csv_path or GGUF_MODEL_CSV_ALT_PATH PRESET_GGUF_MODELS.clear() PRESET_GGUF_VLM_MODELS.clear() PRESET_GGUF_EMBED_MODELS.clear() PRESET_GGUF_STT_MODELS.clear() if os.path.exists(path): import csv with open(path, "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: cat = str(row.get("category", "")).strip().lower() label = str(row.get("label", "")).strip() model_id = str(row.get("model_id", "")).strip() size_str = str(row.get("download_size_gb", "")).strip() if not label or not model_id: continue if size_str: try: DOWNLOAD_SIZE_GB[model_id] = float(size_str) except ValueError: pass if cat in ("both", "llm"): PRESET_GGUF_MODELS[label] = model_id if cat in ("both", "vlm"): PRESET_GGUF_VLM_MODELS[label] = model_id if cat == "embed": PRESET_GGUF_EMBED_MODELS[label] = model_id if cat == "stt": PRESET_GGUF_STT_MODELS[label] = model_id if not PRESET_GGUF_MODELS: PRESET_GGUF_MODELS["🦙 Gemma-4-E2B QAT Q4_0 (~1.8 GB download | GGUF | HF Hub)"] = "google/gemma-4-E2B-it-qat-q4_0-gguf" PRESET_GGUF_MODELS["🦙 Gemma-4-E4B QAT Q4_0 (~2.8 GB download | GGUF | HF Hub)"] = "google/gemma-4-E4B-it-qat-q4_0-gguf" PRESET_GGUF_MODELS["🦙 Gemma-4-12B QAT Q4_0 (~7.5 GB download | GGUF | HF Hub)"] = "google/gemma-4-12B-it-qat-q4_0-gguf" PRESET_GGUF_MODELS["🦙 Gemma-4-26B-A4B QAT Q4_0 (~15.2 GB download | MoE GGUF | HF Hub)"] = "google/gemma-4-26B-A4B-it-qat-q4_0-gguf" PRESET_GGUF_MODELS["🦙 Gemma-4-31B QAT Q4_0 (~18.5 GB download | GGUF | HF Hub)"] = "google/gemma-4-31B-it-qat-q4_0-gguf" load_models_from_csv() load_gguf_models_from_csv() load_hf_api_models_from_csv() _EMBED_MODEL_BY_TIER = { HardwareManager.TIER_48GB_VRAM: "jinaai/jina-embeddings-v4", HardwareManager.TIER_24GB_VRAM: "Qwen/Qwen3-Embedding-4B", HardwareManager.TIER_16GB_VRAM: "BAAI/bge-m3", HardwareManager.TIER_8GB_VRAM: "BAAI/bge-m3", HardwareManager.TIER_CPU_ONLY: "BAAI/bge-m3", HardwareManager.TIER_UNKNOWN: "BAAI/bge-m3", } def get_recommended_embed_model() -> str: """The embedding model README.md's hardware-tier table recommends for THIS machine, based on live-detected VRAM/RAM. Uses CSV default if set.""" if CSV_DEFAULT_EMBED_MODEL: return CSV_DEFAULT_EMBED_MODEL tier = HardwareManager.detect_hardware_tier() return _EMBED_MODEL_BY_TIER.get(tier, "BAAI/bge-m3") def get_embed_model_id(label: str) -> str: """Resolve an embedding dropdown LABEL to its real model id (HF repo id, a .gguf path, or the HF-API / LiteLLM sentinel). Returns the input unchanged when it is already an id or no mapping exists — never raises. The KB (embed) tab persists the model id via set_embed_model(); the dropdown only knows the display LABEL, so every save must map LABEL→id. Storing the literal label (which is decorated with emoji / sizes / '|' text) as the id was the root cause of the indexing failure ``Repo id must use alphanumeric chars… 'sentence-transformers/🔎 Qwen3…'`` — SentenceTransformer() then received the pretty label instead of the real repo id.""" if not label: return label if label in EMBED_OPTIONS: return EMBED_OPTIONS[label] if label in PRESET_GGUF_EMBED_MODELS: return PRESET_GGUF_EMBED_MODELS[label] if label == HF_API_ENTRY_LABEL: return HF_INFERENCE_API_SENTINEL if label == LITELLM_ENTRY_LABEL: return LITELLM_SENTINEL return label def _is_valid_embed_id(v: str) -> bool: """True when *v* already looks like a usable embedding model id (not a decorated display label): a known registry id, a .gguf path, an API sentinel, or a bare ``owner/name`` HF repo id with only safe chars.""" if not v: return False if v in EMBED_OPTIONS.values() or v in PRESET_GGUF_EMBED_MODELS.values(): return True if v in (HF_INFERENCE_API_SENTINEL, LITELLM_SENTINEL): return True if str(v).lower().endswith(".gguf"): return True return bool(re.match(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$", str(v))) def get_default_embed_model(provider: Optional[str] = None) -> str: """The embedding model actually used unless the user has a saved override in user_config.json — a persisted choice always wins (same pattern as get_saved_context_window()), so re-detecting hardware on every restart never silently reverts an explicit user pick. If *provider* is specified (or read from saved provider_embed), the default model matches that provider's catalog (e.g. HF API sentinel for PROVIDER_HF_API, GGUF preset for PROVIDER_SERVER, SentenceTransformer for PROVIDER_LOCAL_HF).""" prov = provider or get_saved_provider("embed") if prov == PROVIDER_HF_API: return HF_INFERENCE_API_SENTINEL if prov in (PROVIDER_SERVER, PROVIDER_LLAMA_CPP_PYTHON): saved = user_config.USER_CONFIG.get("embed_model") if saved and (saved in PRESET_GGUF_EMBED_MODELS.values() or str(saved).lower().endswith(".gguf")): return saved saved_lbl = get_saved_model("embed") if saved_lbl in PRESET_GGUF_EMBED_MODELS: return PRESET_GGUF_EMBED_MODELS[saved_lbl] return next(iter(PRESET_GGUF_EMBED_MODELS.values())) if PRESET_GGUF_EMBED_MODELS else "BAAI/bge-m3" saved = user_config.USER_CONFIG.get("embed_model") if saved: if _is_valid_embed_id(saved): return saved resolved = get_embed_model_id(saved) if resolved != saved and _is_valid_embed_id(resolved): return resolved saved_lbl = get_saved_model("embed") if saved_lbl in EMBED_OPTIONS: return EMBED_OPTIONS[saved_lbl] return get_recommended_embed_model() def set_embed_model(model_id: str) -> None: """Persist an explicit embedding-model choice — mirrors llama_backend.set_model_dir() / set_context_window()'s persistence pattern. NOTE: changing this only takes effect on the next embedding model load (models.get_embed_model() caches the loaded model); if one is already loaded, the caller is responsible for resetting models._embed_model, since an embedding model can't be hot-swapped mid-session without also fully re-indexing every stored vector in ChromaDB (embeddings from different models aren't comparable). The input is the dropdown LABEL; it is resolved to the real model id so the persisted value is always loadable.""" user_config.save_user_config({"embed_model": get_embed_model_id(model_id)}) def get_default_embed_label(provider: Optional[str] = None) -> str: """Reverse-lookup the dropdown label matching the currently active embedding model id (persisted override, or the hardware-tier recommendation if nothing was ever saved) — mirrors get_saved_context_window_label()'s pattern. Used to initialize the UI's "🧩 Embedding Model" dropdown to the right value on load.""" prov = provider or get_saved_provider("embed") opts = get_model_options_for_provider(prov, "embed") if not opts: opts = EMBED_OPTIONS saved_lbl = get_saved_model("embed") if saved_lbl in opts: return saved_lbl current = get_default_embed_model(prov) for label, model_id in opts.items(): if model_id == current: return label return next(iter(opts.keys())) # Best-effort vector dimensions for each EMBED_OPTIONS entry — used only # to make the UI's switch-embedding-model warning more concrete (telling # the user the actual before/after dimensions instead of just "they might # differ"). NOT used to block or validate anything: if a future model's # real dimension differs from what's listed here, knowledge_base.py's # actual runtime check (peeking at a real stored vector, and catching # ChromaDB's own dimension-mismatch error) is always the source of truth, # not this table. EMBED_MODEL_DIMENSIONS = { "BAAI/bge-m3": 1024, "Qwen/Qwen3-Embedding-4B": 2560, "jinaai/jina-embeddings-v4": 2048, # verify against the model card if this ever looks off } DEFAULT_EMBED_MODEL = get_default_embed_model() USER_DATA_DIR = str(user_data_dir()) CHROMA_PERSIST_DIR = os.path.join(USER_DATA_DIR, "chroma_db") VISUAL_INDEX_DIR = os.path.join(USER_DATA_DIR, "visual_index") # User-triggered report saves (the "💾 Save Report" buttons) write per-tab # .docx reports here — one folder per tab (general_chat, rag, deep_research, # vision, stt, data_analysis) so reports never mix. Nothing is auto-saved: # files are only written on a button click. Same user_data isolation rule # as every other generated file. REPORT_BASE_DIR = os.path.join(USER_DATA_DIR, "reports") REPORT_DIRS = { "gen": os.path.join(REPORT_BASE_DIR, "general_chat"), "rag": os.path.join(REPORT_BASE_DIR, "rag"), "dr": os.path.join(REPORT_BASE_DIR, "deep_research"), "vis": os.path.join(REPORT_BASE_DIR, "vision"), "stt": os.path.join(REPORT_BASE_DIR, "stt"), "data": os.path.join(REPORT_BASE_DIR, "data_analysis"), } CHUNK_SIZE = 1024 CHUNK_OVERLAP = 128 TOP_K = 4 # NOTE: this budget covers BOTH the model's internal ... # reasoning AND its actual answer — they share the same generation call # (see models._call_llm() / llama_backend.LlamaServerModel.generate()). # 512 was fine for small non-reasoning models, but "thinking"-tuned # models (e.g. Qwen3.x, Qwen3.6-35B-A3B) can burn the entire budget just # reasoning about a longer/multi-part prompt, leaving nothing left for # the answer itself — format_llm_response() in chat.py then has an empty # or unclosed section and the chat bubble looks blank even # though generation "succeeded". # # Raised again from 2048 -> 4096: 2048 was still getting cut off mid- # generation on longer agentic outputs — observed concretely on Deep # Research's report-writing step, where a CodeAgent step ran out of # budget in the middle of writing a Python triple-quoted report string # and got cut off before the closing `"""`, which then failed to parse # with "SyntaxError: unterminated triple-quoted string literal" — a # genuine truncation, not a real code mistake by the model. Data # Analysis's EDA reports and Deep Research's multi-section Markdown # reports are the longest single generations in this app and are the # most likely to need this room. If responses still feel truncated on a # heavy reasoning model or a long report, raise this further (it does # cost more time/VRAM per turn — the GGUF KV-cache size is governed # separately by CONTEXT_WINDOW_OPTIONS below, not by this value). MAX_NEW_TOKENS = 4096 # ────────────────────────────────────────────────────────────────── # Max New Tokens — now user-configurable from the UI (⚙️ Model Settings), # instead of only the hardcoded MAX_NEW_TOKENS constant above (kept as # the fallback default). Persisted the same way as CONTEXT_WINDOW_OPTIONS # below, so the choice survives an app restart. See models.get_llm() / # models._call_llm() for where this is actually applied — every backend # (in-process llama.cpp, llama-server, and HuggingFace/transformers) reads # get_saved_max_new_tokens() rather than the bare constant now. # # Why this matters in practice: this budget is SHARED between a model's # internal ... reasoning and its actual answer/code (see # MAX_NEW_TOKENS's own docstring above) — a heavy "thinking"-tuned model # (e.g. Qwen3.6-35B-A3B) can burn the entire budget reasoning and never # emit an actual answer or tool call, which shows up in agentic tabs as # a step that parses to an EMPTY code block ("Executing parsed code:" # with nothing between the separators, `Out: None`) — a wasted step, not # a tool-access failure. Raising this (or turning reasoning off via # REASONING_DISABLE_TAG below) is the direct fix. # ────────────────────────────────────────────────────────────────── MAX_NEW_TOKENS_OPTIONS = { "1024 (fast, short answers)": 1024, "2048": 2048, "4096 (default)": 4096, "8192 (long reasoning / reports)": 8192, "16384 (very long reasoning models, e.g. Qwen3.6-35B-A3B)": 16384, } DEFAULT_MAX_NEW_TOKENS_LABEL = "4096 (default)" DEFAULT_MAX_NEW_TOKENS = MAX_NEW_TOKENS_OPTIONS[DEFAULT_MAX_NEW_TOKENS_LABEL] def get_saved_max_new_tokens() -> int: """Read the persisted max-new-tokens budget, falling back to the 4096 default if nothing was ever saved or the saved value is corrupt — same "safe default wins" pattern as get_saved_context_window().""" try: n = int(user_config.USER_CONFIG.get("max_new_tokens", DEFAULT_MAX_NEW_TOKENS)) return n if n > 0 else DEFAULT_MAX_NEW_TOKENS except (TypeError, ValueError): return DEFAULT_MAX_NEW_TOKENS def get_saved_max_new_tokens_label() -> str: """Reverse-lookup the dropdown label matching the persisted budget, for initializing the UI dropdown's value to whatever was saved last time — mirrors get_saved_context_window_label().""" saved = get_saved_max_new_tokens() for label, value in MAX_NEW_TOKENS_OPTIONS.items(): if value == saved: return label return DEFAULT_MAX_NEW_TOKENS_LABEL def set_max_new_tokens(n: int) -> None: """Persist the chosen max-new-tokens budget so it survives an app restart — mirrors set_context_window()'s persistence pattern.""" user_config.save_user_config({"max_new_tokens": int(n)}) # ────────────────────────────────────────────────────────────────── # Quantization (bitsandbytes) — user-configurable from the UI (🗜️ # Quantization dropdown in General Chat's Generation Settings). # # Lets any HuggingFace model load in 4-bit/8-bit via bitsandbytes, # trading a little quality for roughly a quarter (4-bit) or half # (8-bit) of the full-precision memory footprint. This is how the # Gemma 4 hardware-tier table in README.md fits models like # Gemma-4-26B-A4B-it on a 24GB card, or Gemma-4-E2B-it on a modest # CPU machine — see get_recommended_quantization() below for the # per-tier default. # # NOTE: bitsandbytes 4-bit/8-bit works most reliably on CUDA GPUs. # On CPU/MPS models.get_llm() attempts it but falls back to the # unquantized load (with a warning) rather than crashing. Models # whose id contains "qat" (e.g. the Mobile QAT checkpoint) ship # pre-quantized and are never re-quantized by this control. # ────────────────────────────────────────────────────────────────── # ────────────────────────────────────────────────────────────────── # Reasoning ("thinking") on/off toggle — user-configurable from the UI. # # Qwen3/Qwen3.5/Qwen3.6's own chat template looks for the literal # substring "/no_think" (or "/think") anywhere in the LAST user turn and # toggles its ... reasoning block accordingly — this is # the model family's own documented mechanism, not something this app # invents. Prepending it to every prompt when the user has reasoning # turned off is a direct, low-risk way to stop a heavy thinking-tuned # model from spending its entire MAX_NEW_TOKENS budget on internal # reasoning and never reaching a real answer/tool call (see # MAX_NEW_TOKENS_OPTIONS's docstring above for the failure mode this # fixes). On non-Qwen3 models this is simply inert extra text most # templates ignore — harmless either way. # ────────────────────────────────────────────────────────────────── REASONING_DISABLE_TAG = "/no_think" def get_saved_reasoning_enabled() -> bool: """Whether model reasoning is currently enabled (default: True — no behaviour change unless the user explicitly turns it off).""" return bool(user_config.USER_CONFIG.get("reasoning_enabled", True)) def set_reasoning_enabled(enabled: bool) -> None: """Persist the reasoning on/off choice so it survives an app restart — mirrors set_context_window()'s persistence pattern.""" user_config.save_user_config({"reasoning_enabled": bool(enabled)}) def get_saved_flash_attn_pytorch() -> bool: """Whether PyTorch FlashAttention (SDPA) is enabled (default: True).""" return bool(user_config.USER_CONFIG.get("flash_attn_pytorch", True)) def set_flash_attn_pytorch(enabled: bool) -> None: user_config.save_user_config({"flash_attn_pytorch": bool(enabled)}) def get_saved_flash_attn_llama() -> bool: """Whether llama.cpp FlashAttention (-fa) is enabled (default: True).""" return bool(user_config.USER_CONFIG.get("flash_attn_llama", True)) def set_flash_attn_llama(enabled: bool) -> None: user_config.save_user_config({"flash_attn_llama": bool(enabled)}) def get_saved_torch_compile() -> bool: """Whether torch.compile (CUDA) is enabled for local transformers models (default: False — opt-in; first-generation compile cost can be high).""" return bool(user_config.USER_CONFIG.get("torch_compile", False)) def set_torch_compile(enabled: bool) -> None: user_config.save_user_config({"torch_compile": bool(enabled)}) # ────────────────────────────────────────────────────────────────── # Acceleration / tuning settings — llama-server CLI flags + PyTorch # torch.compile/bf16 fastpaths. Every auto/off/empty default keeps the # launch command identical to previous versions (no behaviour change # unless the user explicitly enables a toggle). # ────────────────────────────────────────────────────────────────── # KV-cache data types llama-server accepts (also used for the K AND V # cache so the two stay in lockstep): "" = auto (llama.cpp default), # plus f16 / q8_0 / q4_0 / bf16 (q4_1/iq4_nl/q5_0/q5_1 exist but are # rarely useful for KV). Only valid llama.cpp values are persisted. LLAMA_KV_CACHE_TYPES = ("", "f16", "q8_0", "q4_0", "bf16") def get_saved_llama_kv_cache_quant() -> str: """Selected KV-cache data type passed as `--cache-type-k/--cache-type-v` to llama-server ("" = Auto — no flag emitted, llama.cpp's default).""" val = str(user_config.USER_CONFIG.get("llama_kv_cache_quant", "")) return val if val in LLAMA_KV_CACHE_TYPES else "" def set_llama_kv_cache_quant(value: str) -> None: user_config.save_user_config({"llama_kv_cache_quant": str(value or "")}) def get_saved_llama_mlock() -> bool: """Whether llama-server should `--mlock` (keep the model resident in RAM rather than swapping/compressing) — default False.""" return bool(user_config.USER_CONFIG.get("llama_mlock", False)) def set_llama_mlock(enabled: bool) -> None: user_config.save_user_config({"llama_mlock": bool(enabled)}) def get_saved_llama_mmap() -> bool: """Memory-map the model file (`--mmap`, the llama.cpp default). When off, `--no-mmap` is emitted (slower load, but may reduce pageouts for machines that don't use mlock).""" return bool(user_config.USER_CONFIG.get("llama_mmap", True)) def set_llama_mmap(enabled: bool) -> None: user_config.save_user_config({"llama_mmap": bool(enabled)}) def get_saved_llama_threads() -> Optional[int]: """CPU thread count for llama-server (`--threads N`); None/0 = Auto (llama.cpp's default, no flag emitted).""" val = user_config.USER_CONFIG.get("llama_threads") if val is None: return None try: n = int(val) except (TypeError, ValueError): return None return n if n > 0 else None def set_llama_threads(value) -> None: try: n = int(value) except (TypeError, ValueError): n = 0 user_config.save_user_config({"llama_threads": n if n > 0 else 0}) def get_saved_llama_tensor_split() -> str: """Multi-GPU tensor split (`--tensor-split N0,N1,...`, proportions per GPU as a comma list e.g. '3,1'); "" = Auto (llama.cpp default).""" return str(user_config.USER_CONFIG.get("llama_tensor_split", "")).strip() def set_llama_tensor_split(value: str) -> None: user_config.save_user_config({"llama_tensor_split": str(value or "").strip()}) def get_saved_llama_draft_model() -> str: """Speculative-decoding draft model path passed as `--spec-draft-model` (needs a recent llama.cpp build and a small GGUF, e.g. a 0.5-1B model); "" = speculative decoding off.""" return str(user_config.USER_CONFIG.get("llama_draft_model", "")).strip() def set_llama_draft_model(value: str) -> None: user_config.save_user_config({"llama_draft_model": str(value or "").strip()}) def get_saved_llama_draft_max() -> int: """Maximum tokens drafted per speculative-decoding step (`--spec-draft-n-max`) — llama.cpp's default is 3.""" val = user_config.USER_CONFIG.get("llama_draft_max") if val is None: return 3 try: n = int(val) except (TypeError, ValueError): return 3 return n if n > 0 else 3 def set_llama_draft_max(value) -> None: try: n = int(value) except (TypeError, ValueError): n = 3 user_config.save_user_config({"llama_draft_max": n if n > 0 else 3}) # torch.compile modes — "" = default. "reduce-overhead" (CUDA graphs) is # the recommended opt-in (best speedup/latency balance for chat), with # max-autotune and max-autotune-no-cudagraphs as the deeper-compile tiers. TORCH_COMPILE_MODES = ("", "default", "reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs") def get_saved_torch_compile_mode() -> str: """torch.compile mode passed to `torch.compile(model, mode=...)`; "" = default (the behaviour before this setting existed).""" val = str(user_config.USER_CONFIG.get("torch_compile_mode", "")) return val if val in TORCH_COMPILE_MODES else "" def set_torch_compile_mode(value: str) -> None: user_config.save_user_config({"torch_compile_mode": str(value or "")}) def get_saved_torch_bf16() -> bool: """Whether local transformers models load in torch.bfloat16 on CUDA (Ampere+ GPUs: faster, no fp16 overflow risk) — default False.""" return bool(user_config.USER_CONFIG.get("torch_bf16", False)) def set_torch_bf16(enabled: bool) -> None: user_config.save_user_config({"torch_bf16": bool(enabled)}) def get_saved_memory_compaction_enabled() -> bool: """Whether agentic memory compaction (token-budget-aware rolling summarization — see agents/agent_memory.py) is enabled (default: True). When off, agentic tabs fall back to the fixed turn-count memory caps (cap_agent_memory) exactly as before.""" return bool(user_config.USER_CONFIG.get("memory_compaction_enabled", True)) def set_memory_compaction_enabled(enabled: bool) -> None: """Persist the memory-compaction on/off choice so it survives an app restart — mirrors set_flash_attn_llama()'s persistence pattern.""" user_config.save_user_config({"memory_compaction_enabled": bool(enabled)}) # ────────────────────────────────────────────────────────────────── # Memory Compaction tuning — how aggressively agentic memory is # compacted (see agents/agent_memory.compact_agent_memory()). # - budget ratio: the fraction of the context window the memory may # use (after subtracting the generation reserve) before compaction # fires. Lower = compact earlier (safer, more frequent summaries); # higher = compact later (fewer summary calls, more context used). # - keep recent turns: how many of the most recent user turns stay # verbatim after a compaction. Exposed as ONE global control with an # "Auto" default that preserves each tab's original per-tab value # (General/RAG = 2, Deep Research/Data = 1) until the user explicitly # picks a number, which then applies to every agentic tab. # ────────────────────────────────────────────────────────────────── MEMORY_COMPACTION_RATIO_OPTIONS = { "50% (compact early, less context used)": 0.50, "65%": 0.65, "75% (default)": 0.75, "85%": 0.85, "90% (compact late, more context used)": 0.90, } DEFAULT_MEMORY_COMPACTION_RATIO_LABEL = "75% (default)" DEFAULT_MEMORY_COMPACTION_RATIO = MEMORY_COMPACTION_RATIO_OPTIONS[DEFAULT_MEMORY_COMPACTION_RATIO_LABEL] def get_saved_memory_compaction_ratio() -> float: """Read the persisted compaction budget ratio (fraction of the context window the memory may use before compaction fires), falling back to the 0.75 default if nothing was ever saved or the saved value is out of range — same "safe default wins" pattern as get_saved_context_window().""" try: r = float(user_config.USER_CONFIG.get( "memory_compaction_ratio", DEFAULT_MEMORY_COMPACTION_RATIO)) return r if 0.1 <= r <= 0.98 else DEFAULT_MEMORY_COMPACTION_RATIO except (TypeError, ValueError): return DEFAULT_MEMORY_COMPACTION_RATIO def get_saved_memory_compaction_ratio_label() -> str: """Reverse-lookup the dropdown label matching the persisted ratio, for initializing the UI dropdown — mirrors get_saved_context_window_label().""" saved = get_saved_memory_compaction_ratio() for label, val in MEMORY_COMPACTION_RATIO_OPTIONS.items(): if abs(val - saved) < 0.001: return label return DEFAULT_MEMORY_COMPACTION_RATIO_LABEL def set_memory_compaction_ratio(ratio: float) -> None: """Persist the chosen compaction budget ratio so it survives an app restart — mirrors set_memory_compaction_enabled()'s pattern.""" try: r = float(ratio) except (TypeError, ValueError): print(f"[Config] Ignoring unparseable memory_compaction_ratio value: {ratio!r}") return user_config.save_user_config({"memory_compaction_ratio": r}) # Original per-tab keep-recent-turns values (see the module note above) — # used only while the global control is on "Auto". _MEMORY_KEEP_RECENT_DEFAULTS = {"gen": 2, "rag": 2, "dr": 1, "data": 1} def get_saved_memory_keep_recent(tab_key: str) -> int: """How many of the most recent user turns stay verbatim after a compaction for `tab_key` ('gen'/'rag'/'dr'/'data'): the explicitly saved GLOBAL value if the user has chosen one, otherwise that tab's original default (General/RAG = 2, Deep Research/Data = 1).""" saved = user_config.USER_CONFIG.get("memory_keep_recent") if saved is not None: try: n = int(saved) if n > 0: return n except (TypeError, ValueError): pass return _MEMORY_KEEP_RECENT_DEFAULTS.get(tab_key, 2) def get_saved_memory_keep_recent_value() -> Optional[int]: """The raw saved keep-recent value — an int, or None when 'Auto' (per-tab defaults) is selected. For initializing the UI dropdown.""" saved = user_config.USER_CONFIG.get("memory_keep_recent") if saved is None: return None try: return int(saved) except (TypeError, ValueError): return None def set_memory_keep_recent(value) -> None: """Persist the global keep-recent-turns override; None / 'auto' (or the dropdown's 'Auto (per-tab defaults)' label, in case a Gradio version ever delivers the label instead of the value) clears it back to per-tab defaults. Any unparseable value is logged, not silently dropped, so a stale UI selection stays diagnosable.""" if value is None or str(value).strip().lower() in ("auto", "auto (per-tab defaults)"): user_config.save_user_config({"memory_keep_recent": None}) return try: n = int(value) except (TypeError, ValueError): print(f"[Config] Ignoring unparseable memory_keep_recent value: {value!r}") return user_config.save_user_config({"memory_keep_recent": n if n > 0 else None}) def apply_reasoning_toggle(text: str) -> str: """Prepend REASONING_DISABLE_TAG to `text` when the user has disabled reasoning via the UI checkbox; a no-op passthrough otherwise. Callers (chat.py / data_analysis.py) apply this to every prompt/task string right before it reaches the model, on every tab (direct and agentic). """ if get_saved_reasoning_enabled(): return text return f"{REASONING_DISABLE_TAG}\n{text}" DATA_ANALYSIS_DIR = os.path.join(USER_DATA_DIR, "data_analysis") DATA_UPLOAD_DIR = os.path.join(DATA_ANALYSIS_DIR, "uploads") DATA_OUTPUT_DIR = os.path.join(DATA_ANALYSIS_DIR, "outputs") DATA_AGENT_MAX_STEPS = 20 # ────────────────────────────────────────────────────────────────── # Context window (n_ctx) — how many tokens of prompt+history+generation # the LLM can hold at once. Mainly meaningful for the GGUF/llama.cpp # backend (llama_backend.LlamaCppModel), where it's a fixed size set at # load time — HF/transformers models size their own context from the # checkpoint's trained max_position_embeddings and aren't affected by # this setting. # # Bumping this fixes errors like: # "Requested tokens (16461) exceed context window of 16384" # which happens once an agentic conversation's accumulated prompt + # memory + tool-call history grows past whatever n_ctx the model was # loaded with (16384 tokens, previously hardcoded in models.py). A # larger window uses more VRAM/RAM (roughly linearly with n_ctx), so # this is exposed as a user choice rather than just maxed out by default. # # Persisted the same way as llama_backend's GGUF folder (see # user_config.py) so the choice survives an app restart. # ────────────────────────────────────────────────────────────────── CONTEXT_WINDOW_OPTIONS = { "4K (4,096 tokens — lowest memory)": 4096, "8K (8,192 tokens)": 8192, "16K (16,384 tokens — default)": 16384, "32K (32,768 tokens)": 32768, "64K (65,536 tokens — needs more VRAM/RAM)": 65536, "128K (131,072 tokens — needs a lot of VRAM/RAM)": 131072, } DEFAULT_CONTEXT_WINDOW_LABEL = "16K (16,384 tokens — default)" DEFAULT_CONTEXT_WINDOW = CONTEXT_WINDOW_OPTIONS[DEFAULT_CONTEXT_WINDOW_LABEL] # Per-tab context window persistence keys. Each tab that runs an LLM/VLM # (General/RAG/Data-Analysis/Deep-Research/Vision) keeps its own n_ctx # choice, mirroring _PROVIDER_KEYS. A tab with no per-tab value yet falls # back to the legacy global "context_window" key, so existing single-value # installs keep their setting everywhere until a tab is changed individually. _CONTEXT_WINDOW_KEYS = { "gen": "context_window_gen", "rag": "context_window_rag", "data": "context_window_data", "dr": "context_window_dr", "vlm": "context_window_vlm", } _GLOBAL_CONTEXT_WINDOW_KEY = "context_window" def get_saved_context_window(tab_key: Optional[str] = None) -> int: """Read the persisted context window (n_ctx) for *tab_key* — or the global value when *tab_key* is None — falling back to the default if nothing was ever saved (fresh install) or the saved value is corrupt. Per-tab values (e.g. 'context_window_rag') are seeded from the global 'context_window' key, so existing installs keep their single setting everywhere until a tab is changed individually.""" per_tab_key = _CONTEXT_WINDOW_KEYS.get(tab_key) if tab_key else None if per_tab_key: try: n = int(user_config.USER_CONFIG.get(per_tab_key, 0)) if n > 0: return n except (TypeError, ValueError): pass try: n = int(user_config.USER_CONFIG.get(_GLOBAL_CONTEXT_WINDOW_KEY, DEFAULT_CONTEXT_WINDOW)) return n if n > 0 else DEFAULT_CONTEXT_WINDOW except (TypeError, ValueError): return DEFAULT_CONTEXT_WINDOW def get_saved_context_window_label(tab_key: Optional[str] = None) -> str: """Reverse-lookup the dropdown label matching the persisted n_ctx for *tab_key*, for initializing the UI dropdown's value to whatever was saved last time.""" saved = get_saved_context_window(tab_key) for label, value in CONTEXT_WINDOW_OPTIONS.items(): if value == saved: return label return DEFAULT_CONTEXT_WINDOW_LABEL def set_context_window(n_ctx: int, tab_key: Optional[str] = None) -> None: """Persist the chosen context window so it survives an app restart. When *tab_key* is given the value is stored per-tab (the global key is left untouched so other tabs keep their own choices); otherwise the global key is written. Mirrors llama_backend.set_model_dir()'s persistence pattern.""" cfg_key = _CONTEXT_WINDOW_KEYS.get(tab_key, _GLOBAL_CONTEXT_WINDOW_KEY) if tab_key else _GLOBAL_CONTEXT_WINDOW_KEY user_config.save_user_config({cfg_key: int(n_ctx)}) # ────────────────────────────────────────────────────────────────── # Per-tab agentic step budgets — how many steps the manager agent (and, # where applicable, its search sub-agent) may take before giving up. The # web UI's per-tab step controls (Max Steps / Search steps) persist here so # the user's budgets survive an app restart, mirroring # _CONTEXT_WINDOW_KEYS / _PROVIDER_KEYS. # # None (nothing saved, or saved value cleared) means AUTO: each agent falls # back to its model-scaled default budget (see get_max_steps_for_model / # the agents' *_DEFAULT_MAX_STEPS), which caps large/slow local GGUFs to # fail fast. An explicit int is the user's own budget, used verbatim. # ────────────────────────────────────────────────────────────────── _AGENT_STEPS_KEYS = { "gen": "agent_max_steps_gen", "rag": "agent_max_steps_rag", "dr": "agent_max_steps_dr", "data": "agent_max_steps_data", # Data Analysis's manager } _SUB_AGENT_STEPS_KEYS = { "rag": "searcher_max_steps_rag", # RAG's knowledge_searcher sub-agent "dr": "search_max_steps_dr", # Deep Research's web-search sub-agent "data": "worker_max_steps_data", # Data Analysis's data_worker sub-agent } def _coerce_step_budget(value) -> Optional[int]: """None / '' / garbage -> None (auto); a positive int is kept as-is. A value of 0 or negative is treated as auto too — a step budget of zero would make the agent give up before its first step.""" if value is None or value == "": return None try: n = int(value) except (TypeError, ValueError): return None return n if n > 0 else None def get_saved_agent_steps(tab_key: str) -> Optional[int]: """The persisted explicit manager/agent step budget for *tab_key* ('gen'/'rag'/'dr'), or None when nothing was saved (= AUTO — the model-scaled default applies). Never raises on a corrupt value.""" key = _AGENT_STEPS_KEYS.get(tab_key) if not key: return None return _coerce_step_budget(user_config.USER_CONFIG.get(key)) def set_agent_steps(tab_key: str, value) -> None: """Persist the manager/agent step budget for *tab_key*; None clears it back to AUTO. Unknown tabs are ignored (never stored).""" key = _AGENT_STEPS_KEYS.get(tab_key) if key: user_config.save_user_config({key: _coerce_step_budget(value)}) def get_saved_sub_agent_steps(tab_key: str) -> Optional[int]: """The persisted explicit SEARCH sub-agent step budget for *tab_key* ('rag'/'dr'), or None when nothing was saved (= AUTO).""" key = _SUB_AGENT_STEPS_KEYS.get(tab_key) if not key: return None return _coerce_step_budget(user_config.USER_CONFIG.get(key)) def set_sub_agent_steps(tab_key: str, value) -> None: """Persist the search sub-agent step budget for *tab_key*; None clears it back to AUTO. Unknown tabs are ignored.""" key = _SUB_AGENT_STEPS_KEYS.get(tab_key) if key: user_config.save_user_config({key: _coerce_step_budget(value)}) # ────────────────────────────────────────────────────────────────── # Alt+Delete clear-confirmation threshold — the number of history messages # a chat must reach before the web UI's Alt+Delete shortcut asks for # confirmation (a fat-fingered shortcut on a long conversation is # irreversible; short exchanges clear instantly). App-wide: every chat tab # and the Data tab share the same shortcut. None / cleared = the default. # ────────────────────────────────────────────────────────────────── CLEAR_CONFIRM_MIN_KEY = "clear_confirm_min" CLEAR_CONFIRM_MIN_DEFAULT = 8 def _coerce_clear_confirm_min(value) -> Optional[int]: """None / '' / garbage / <1 -> None (the default applies); a positive int is kept as-is.""" if value is None or value == "": return None try: n = int(value) except (TypeError, ValueError): return None return n if n >= 1 else None def get_saved_clear_confirm_min() -> Optional[int]: """The persisted clear-confirmation threshold (messages), or None when nothing was saved (= the default). Never raises on a corrupt value.""" return _coerce_clear_confirm_min(user_config.USER_CONFIG.get(CLEAR_CONFIRM_MIN_KEY)) def set_clear_confirm_min(value) -> None: """Persist the clear-confirmation threshold; None/'' clears it back to the default.""" user_config.save_user_config({CLEAR_CONFIRM_MIN_KEY: _coerce_clear_confirm_min(value)}) # ────────────────────────────────────────────────────────────────── # STT noise-reduction STRENGTH — the 🎧 Reduce Noise preset (gentle / # medium / aggressive) the STT tab's strength picker uses. Persisted so # the tab reopens on the user's last pick. None / cleared = the default # ('aggressive'). The valid preset names come from audio_denoise's own # map (the single source of truth); the import is module-level safe # because audio_denoise pulls numpy/scipy/soundfile in lazily inside its # functions. # ────────────────────────────────────────────────────────────────── DENOISE_STRENGTH_KEY = "denoise_strength" def _denoise_presets(): """The STT noise-reduction preset map — imported lazily so the heavy numpy/scipy stack stays out of app startup (audio_denoise pulls it in only inside its own functions).""" from backend.audio_denoise import DENOISE_STRENGTH_PRESETS return DENOISE_STRENGTH_PRESETS def _denoise_default() -> str: """The default preset when nothing was saved — audio_denoise's own constant is the single source of truth (aggressive).""" from backend.audio_denoise import DEFAULT_DENOISE_STRENGTH return DEFAULT_DENOISE_STRENGTH def _coerce_denoise_strength(value) -> Optional[str]: """A preset name (gentle / medium / aggressive, case-insensitive) is normalized and kept; None / '' / garbage falls back to the default. Never raises on a corrupt value.""" if isinstance(value, str) and value.strip().lower() in _denoise_presets(): return value.strip().lower() return None def get_saved_denoise_strength() -> str: """The persisted STT noise-reduction preset, or the default when nothing was saved / the stored value is garbage.""" return _coerce_denoise_strength(user_config.USER_CONFIG.get(DENOISE_STRENGTH_KEY)) \ or _denoise_default() def set_denoise_strength(value) -> None: """Persist the STT noise-reduction preset; garbage / None clears it back to the default.""" user_config.save_user_config({DENOISE_STRENGTH_KEY: _coerce_denoise_strength(value)}) # ────────────────────────────────────────────────────────────────── # STT transcription LANGUAGE — the STT tab's language dropdown (auto / # english / khmer / french / chinese / japanese) sent to the transcribe # backend. Persisted so the tab reopens on the user's last pick, exactly # like the denoise strength above. None / cleared = 'auto' (auto-detect). # The valid values are kept here as the single source of truth, and # /api/meta's sttLanguages option list is built from the same contract. # ────────────────────────────────────────────────────────────────── STT_LANG_KEY = "stt_lang" STT_LANG_DEFAULT = "auto" STT_LANG_OPTIONS = ("auto", "english", "khmer", "french", "chinese", "japanese") def _coerce_stt_lang(value) -> Optional[str]: """A valid STT language value (case-insensitive) is normalized and kept; None / '' / garbage falls back to the default. Never raises.""" if isinstance(value, str) and value.strip().lower() in STT_LANG_OPTIONS: return value.strip().lower() return None def get_saved_stt_lang() -> str: """The persisted STT transcription language, or 'auto' when nothing was saved / the stored value is garbage.""" return _coerce_stt_lang(user_config.USER_CONFIG.get(STT_LANG_KEY)) or STT_LANG_DEFAULT def set_stt_lang(value) -> None: """Persist the STT transcription language; garbage / None clears it back to the default ('auto').""" user_config.save_user_config({STT_LANG_KEY: _coerce_stt_lang(value)}) # ────────────────────────────────────────────────────────────────── # STT microphone device id — the mic selector dropdown in the STT tab. # Persisted so the user's mic pick survives a page reload. The browser # assigns its own device ids (opaque strings), so we just store/return # the raw string; an id that no longer matches any device is silently # cleared by the frontend. # ────────────────────────────────────────────────────────────────── STT_MIC_KEY = "stt_mic_device" def get_saved_stt_mic() -> str: """The persisted mic device id, or '' (system default) when nothing was saved.""" val = user_config.USER_CONFIG.get(STT_MIC_KEY) return val if isinstance(val, str) and val.strip() else "" def set_stt_mic(value) -> None: """Persist the mic device id; garbage / None clears back to default.""" user_config.save_user_config({STT_MIC_KEY: (value or "").strip()}) # ────────────────────────────────────────────────────────────────── # Per-tab agentic EXECUTION timeout — the per-step Python code-executor # timeout in seconds (agent_factory.build_smol_agent's # executor_kwargs.timeout_seconds). Persisted the same way as the step # budgets above so the web UI's "Exec timeout" controls survive an app # restart. Exposed on every agentic chat tab (General / RAG / Deep # Research / Data) — the per-step timeout only bites on the CodeAgent # path (tool calling unchecked), where it caps a single executed Python # block. # # None (nothing saved, or saved value cleared) means AUTO: the agent keeps # its factory default. An explicit positive int is the user's own per-step # timeout, used verbatim. # ────────────────────────────────────────────────────────────────── _AGENT_EXEC_TIMEOUT_KEYS = { "gen": "agent_exec_timeout_gen", "rag": "agent_exec_timeout_rag", "dr": "agent_exec_timeout_dr", "data": "agent_exec_timeout_data", } def get_saved_execution_timeout(tab_key: str) -> Optional[int]: """The persisted explicit execution timeout (seconds) for *tab_key*, or None when nothing was saved (= AUTO — the agent factory's default applies). Never raises on a corrupt value.""" key = _AGENT_EXEC_TIMEOUT_KEYS.get(tab_key) if not key: return None return _coerce_step_budget(user_config.USER_CONFIG.get(key)) def set_execution_timeout(tab_key: str, value) -> None: """Persist the execution timeout for *tab_key*; None clears it back to AUTO. Unknown tabs are ignored (never stored).""" key = _AGENT_EXEC_TIMEOUT_KEYS.get(tab_key) if key: user_config.save_user_config({key: _coerce_step_budget(value)}) # ────────────────────────────────────────────────────────────────── # Per-tab generation RUN timeout — the wall-clock budget for a whole # chat run (General / RAG / Deep Research / Vision), in seconds (each # chat tab's Generation Settings "Timeout" control; Deep Research was the # first tab to expose it, default 300). DISTINCT from the per-step # EXECUTION timeout above: that one caps a single Python-executor step on # a CodeAgent; this one caps the whole run. Persisted the same way as the # step budgets so the web UI's controls survive an app restart. # # None (nothing saved, or saved value cleared) means NO explicit deadline: # the run goes on until it naturally finishes (the DR path still falls # back to the agent's own per-step timeout). An explicit positive int is # the user's own run timeout, used verbatim. # ────────────────────────────────────────────────────────────────── _AGENT_RUN_TIMEOUT_KEYS = { "gen": "agent_run_timeout_gen", # General Chat "rag": "agent_run_timeout_rag", # RAG Chat "vlm": "agent_run_timeout_vision", # Vision (backend tab key is 'vlm', like _PROVIDER_KEYS) "dr": "agent_run_timeout_dr", # Deep Research "data": "agent_run_timeout_data", # Data Analysis (now a chat tab) } def get_saved_agent_run_timeout(tab_key: str) -> Optional[int]: """The persisted explicit generation run timeout (seconds) for *tab_key* ('gen'/'rag'/'vlm'/'dr'), or None when nothing was saved (= no explicit deadline — the run finishes naturally). Never raises on a corrupt value.""" key = _AGENT_RUN_TIMEOUT_KEYS.get(tab_key) if not key: return None return _coerce_step_budget(user_config.USER_CONFIG.get(key)) def set_agent_run_timeout(tab_key: str, value) -> None: """Persist the generation run timeout for *tab_key*; None clears it back to no explicit deadline. Unknown tabs are ignored (never stored).""" key = _AGENT_RUN_TIMEOUT_KEYS.get(tab_key) if key: user_config.save_user_config({key: _coerce_step_budget(value)}) # ────────────────────────────────────────────────────────────────── # RAG visual retrieval toggle — whether the RAG tab runs the # resource-intensive visual path: the agentic `visual_retriever` page-image # tool (agentic mode) and the VLM grounding pass (direct + agentic modes). # DEFAULT OFF: visual retrieval can pull in the 2-8 GB retriever model and # a VLM, so it is opt-in per user. When off, RAG is a pure text-retrieval # + text-LLM pipeline (the SAME LLM the user already runs — no VLM, no # retriever-model load). # ────────────────────────────────────────────────────────────────── def get_rag_visual_retrieval() -> bool: """Whether the RAG tab's visual retriever + VLM path is enabled. Defaults to False (OFF) — the resource-light choice.""" try: return bool(user_config.USER_CONFIG.get("rag_visual_retrieval", False)) except Exception: return False def set_rag_visual_retrieval(enabled) -> None: """Persist the RAG visual-retrieval toggle. Any truthy value enables; anything else disables (default OFF).""" user_config.save_user_config({"rag_visual_retrieval": bool(enabled)}) # ────────────────────────────────────────────────────────────────── # LLM backend mode for GGUF models — how a selected .gguf file is # actually RUN, independent of which .gguf file/folder it comes from: # # "inprocess" — llama-cpp-python, loaded directly inside this Python # process (llama_backend.LlamaCppModel). The original, # default behaviour. # "server" — spawns/reuses an external `llama-server` executable # as a subprocess and talks to it over its OpenAI- # compatible HTTP API instead # (llama_backend.get_or_start_llama_server() / # LlamaServerModel). Needs a llama-server(.exe) binary # configured — see llama_backend.LLAMA_SERVER_EXE_PATH / # set_llama_server_exe_path(). # # Only meaningful for .gguf models — HuggingFace/transformers models # always run in-process regardless of this setting. Persisted the same # way as the context window above, so the choice survives an app # restart; models.get_llm() reads this to decide which backend class to # build for a given GGUF model_id. # ────────────────────────────────────────────────────────────────── LLM_BACKEND_MODE_OPTIONS = { "🧩 llama-cpp-python (in-process — default)": "inprocess", "🖥️ llama-server (external process, OpenAI-compatible API)": "server", } DEFAULT_LLM_BACKEND_LABEL = "🧩 llama-cpp-python (in-process — default)" def get_saved_llm_backend_mode() -> str: """Read the persisted GGUF backend mode ('inprocess' or 'server'), falling back to 'inprocess' if nothing was ever saved or the saved value isn't recognized — same "safe default wins" pattern as get_saved_context_window().""" saved = str(user_config.USER_CONFIG.get("llm_backend_mode", "inprocess")) if saved not in LLM_BACKEND_MODE_OPTIONS.values(): saved = "inprocess" if saved == "inprocess": try: from backend import llama_health health = llama_health.get_llama_cpp_health() if health.get("status") == "broken" and llama_backend.LLAMA_SERVER_EXE_PATH: return "server" except Exception: pass # Prefer the external llama-server whenever the INSTALLED in-process # wheel cannot offload GGUF to the GPU (not just when it is missing or # broken). This is the machine-independent rule: a CPU-only wheel # (forced by the AVX-512 crash guard, a missing CUDA runtime DLL, an # unverifiable compute capability, or an AMD/Intel GPU with no Vulkan # wheel) silently runs GGUF on the CPU in-process while a GPU-capable # llama-server sits right there. The server manages its own GPU # offloading independently, so prefer it whenever the wheel can't. if not llama_backend.LLAMA_CPP_GPU_AVAILABLE and llama_backend.LLAMA_SERVER_EXE_PATH: return "server" return saved def get_saved_llm_backend_label() -> str: """Reverse-lookup the dropdown label matching the persisted backend mode, for initializing the UI dropdown's value to whatever was saved last time — mirrors get_saved_context_window_label().""" saved = get_saved_llm_backend_mode() for label, mode in LLM_BACKEND_MODE_OPTIONS.items(): if mode == saved: return label return DEFAULT_LLM_BACKEND_LABEL def set_llm_backend_mode(mode: str) -> None: """Persist the chosen GGUF backend mode so it survives an app restart — mirrors set_context_window()'s persistence pattern. Callers (see ui.py) are responsible for resetting any cached agents/LLM instance and stopping a running llama-server process afterward, since a backend switch can't be hot-applied to an already-loaded model the way most other settings can.""" mode = mode if mode in LLM_BACKEND_MODE_OPTIONS.values() else "inprocess" user_config.save_user_config({"llm_backend_mode": mode}) # ────────────────────────────────────────────────────────────────── # llama-server (external process) backend — PER-REQUEST HTTP timeout. # # LlamaServerModel.generate() (llama_backend.py) posts to llama-server's # /v1/chat/completions endpoint with a fixed request timeout. Previously # this was hardcoded at 300s in LlamaServerModel's own default and never # overridden by models.get_llm() — which is fine for small/fast models, # but a large local GGUF model (e.g. a 30B+ MoE checkpoint) combined with # a long accumulated agentic prompt (Deep Research's manager+sub-agent # history, MAX_NEW_TOKENS=4096) can easily need more than 300s for a # single generation. When that happens, LlamaServerModel.generate() # doesn't crash — it catches the timeout and returns a fake assistant # ChatMessage containing a "⚠️ llama-server request failed... Read timed # out" warning (see that method's docstring/comment) — which smolagents' # CodeAgent then tries to regex-parse as a ```python code block, fails, # and reports a confusing "Error in code parsing" instead of the real # "this just needs more time" issue. # # Exposed as a persisted user setting (same pattern as # get_saved_context_window() above) instead of just raising the # hardcoded default, since the right value genuinely depends on the # user's model size/hardware — a small model on a fast GPU doesn't need # 20 minutes per request, but a large CPU-bound MoE model might. # ────────────────────────────────────────────────────────────────── LLAMA_SERVER_TIMEOUT_OPTIONS = { "60s (fast small models)": 60, "120s": 120, "300s (default)": 300, "600s (10 min — large/CPU-bound models)": 600, "1200s (20 min — very large MoE models on CPU)": 1200, "1800s (30 min — maximum patience)": 1800, } DEFAULT_LLAMA_SERVER_TIMEOUT_LABEL = "300s (default)" DEFAULT_LLAMA_SERVER_TIMEOUT = LLAMA_SERVER_TIMEOUT_OPTIONS[DEFAULT_LLAMA_SERVER_TIMEOUT_LABEL] def get_saved_llm_server_timeout() -> int: """Read the persisted llama-server per-request HTTP timeout (seconds), falling back to the 300s default if nothing was ever saved or the saved value is corrupt — same "safe default wins" pattern as get_saved_context_window().""" try: n = int(user_config.USER_CONFIG.get("llama_server_timeout", DEFAULT_LLAMA_SERVER_TIMEOUT)) return n if n > 0 else DEFAULT_LLAMA_SERVER_TIMEOUT except (TypeError, ValueError): return DEFAULT_LLAMA_SERVER_TIMEOUT def get_saved_llm_server_timeout_label() -> str: """Reverse-lookup the dropdown label matching the persisted timeout, for initializing the UI dropdown's value to whatever was saved last time — mirrors get_saved_context_window_label().""" saved = get_saved_llm_server_timeout() for label, value in LLAMA_SERVER_TIMEOUT_OPTIONS.items(): if value == saved: return label return DEFAULT_LLAMA_SERVER_TIMEOUT_LABEL def set_llm_server_timeout(seconds: int) -> None: """Persist the chosen llama-server per-request timeout so it survives an app restart — mirrors set_context_window()'s persistence pattern. Takes effect the next time a request is made (LlamaServerModel is lightweight to reconstruct — no subprocess restart needed, unlike a context-window or backend-mode change, since this only affects the Python-side `requests.post(..., timeout=...)` call, not llama-server itself).""" user_config.save_user_config({"llama_server_timeout": int(seconds)}) # ────────────────────────────────────────────────────────────────── # Agentic CodeAgent step budget — scaled down for larger/slower local # models. A broken step-parsing loop (e.g. a model that writes plain # prose instead of a ```python fenced block) costs roughly the same # wall-clock time PER STEP regardless of model size, but a 14B+ GGUF # model can take 30-250+ seconds per step where a small HF model takes # a few seconds — so the same default max_steps that's a harmless safety # net on a small model turns into a 4-20+ minute stall on a large one # before the agent finally gives up. See general_agent.py / rag_agent.py # for where this is applied. # ────────────────────────────────────────────────────────────────── _PARAM_SIZE_RE = re.compile(r'(\d+(?:\.\d+)?)\s*[bB](?![a-zA-Z])') def estimate_model_param_billions(model_id: str) -> Optional[float]: """Best-effort parse of a model's parameter count (in billions) from its id/filename, e.g.: 'Qwen3.6-14B-A3B-FableVibes-Q8_0.gguf' -> 14.0 'qwen3-coder-30b-a3b-compacted-19b-256k...' -> 30.0 (first match wins) 'Qwen/Qwen3-0.6B' -> 0.6 Returns None if no confident 'B' pattern is found (e.g. an unusually-named checkpoint) — callers should treat that as "unknown size", not "small", since guessing wrong in the small direction would silently remove the safety margin this exists to add. """ if not model_id: return None m = _PARAM_SIZE_RE.search(str(model_id)) if not m: return None try: return float(m.group(1)) except ValueError: return None def get_max_steps_for_model(model_id: str, default_max_steps: int) -> int: """Scale an agentic CodeAgent's max_steps down for models estimated to be 10B+ parameters, so a broken parsing/tool-calling loop on a large, slow local GGUF model fails fast instead of grinding through the full default step budget (each failed step can take a minute or more on these models — see the module docstring above). Leaves `default_max_steps` untouched if the model's size can't be confidently parsed from its id/filename, since an unrecognized name is more often a normal HuggingFace repo id (usually small/fast) than a huge unnamed checkpoint, and it's safer to keep the normal budget than cut off a model that turns out to be small. """ size_b = estimate_model_param_billions(model_id) if size_b is None: return default_max_steps if size_b >= 20: return min(default_max_steps, 4) if size_b >= 10: return min(default_max_steps, 5) return default_max_steps # ────────────────────────────────────────────────────────────────── # Per-model agentic planning override # ────────────────────────────────────────────────────────────────── # smolagents' `planning_interval` re-plan steps are a known failure mode # for some models: they latch onto the re-plan prompt text ("I still need # to solve the task I was given: …") and echo-loop instead of continuing # toward a final answer. Verified end-to-end on Muse Glimmer (RAG manager, # Deep Research manager and the Data Analysis manager, Aug 2026): with # planning_interval=3 the run loops and never delivers; with planning # disabled (None) it completes cleanly. `planning_interval_for_model()` # returns None for these models so every agentic tab skips the re-plan # steps automatically — matched against the resolved model id (repo id, # GGUF path or filename), case- and separator-insensitively. PLANNING_DISABLED_MODEL_MARKERS = ("muse-glimmer",) def _norm_model_marker(s) -> str: return str(s or "").casefold().replace("-", "").replace("_", "").replace("/", " ") def planning_interval_for_model(model_id, default_interval) -> Optional[int]: """The smolagents `planning_interval` to use for `model_id`: None (planning off) when the model is flagged in PLANNING_DISABLED_MODEL_MARKERS, else `default_interval` unchanged. The flag is the app-side cure for the Muse Glimmer planning echo-loop (see PLANNING_DISABLED_MODEL_MARKERS) and applies to EVERY agentic tab's manager, not just one.""" low = _norm_model_marker(model_id) for marker in PLANNING_DISABLED_MODEL_MARKERS: if _norm_model_marker(marker) in low: return None return default_interval # ────────────────────────────────────────────────────────────────── # Data-tab verified-ladder exclusion # ────────────────────────────────────────────────────────────────── # The Data tab's verified-ladder rule (AGENTS.md): a GGUF is offered there # only after an end-to-end Data harness pass. Muse Glimmer's Data leg # FAILS (3/6 — the manager doesn't reliably delegate to `data_worker`), so # it is registered for the LLM chat tabs (General / RAG / Deep Research) # but excluded from the Data tab's model dropdown. The `udiq2xxs` / # `udtq10` markers cover the unsloth `-UD-` dynamic-quant family (e.g. # Qwen3.8-27B UD-IQ2_XXS, GLM-4.7-Flash UD-TQ1_0) — per the verified- # ladder rule `-UD-` conversions FAIL on the CodeAgent (native tool-call # envelopes it can't parse), so they are chat-tab-only until an end-to-end # Data pass proves otherwise. The markers match the CSV repo id AND # locally-discovered GGUF paths, so the exclusion holds whether or not the # file lives in the catalog. DATA_TAB_EXCLUDED_MODEL_MARKERS = ("muse-glimmer", "udiq2xxs", "udtq10") def is_data_tab_excluded_model(model_id) -> bool: """True when `model_id` (repo id, GGUF path or label) is flagged for the Data-tab verified-ladder exclusion — the web UI's Data tab model dropdown filters these out (see web_api meta `dataModels`).""" low = _norm_model_marker(model_id) return any(_norm_model_marker(m) in low for m in DATA_TAB_EXCLUDED_MODEL_MARKERS) QWEN3_IDS = {"Qwen/Qwen3-0.6B", "Qwen/Qwen3-1.7B", "Qwen/Qwen3-4B", "Qwen/Qwen3-8B", "Qwen/Qwen3-14B", "Qwen/Qwen3-32B"} # Qwen3.6 (April 2026) — hybrid linear-/full-attention MoE ("qwen3_5_moe") # and dense architectures, superseding Qwen3.5. Only ships in 27B (dense) # and 35B-A3B (MoE, ~3B active params/token) sizes — there is no small # (<20B) Qwen3.6 checkpoint, so BASE_MODEL_OPTIONS below still uses plain # Qwen3 for the 0.6B/1.7B/4B/8B/14B tiers, and only swaps in Qwen3.6 at # the top end (replacing the older Qwen3-32B). QWEN36_IDS = {"Qwen/Qwen3.6-27B", "Qwen/Qwen3.6-35B-A3B"} ALL_QWEN_IDS = QWEN3_IDS | QWEN36_IDS QWEN_VL_IDS = {"Qwen/Qwen2.5-VL-3B-Instruct", "Qwen/Qwen2.5-VL-7B-Instruct"} # Qwen3-VL (dense 2B/4B/8B, Oct 2025) — the current-gen Qwen vision family, # listed in the Vision tab's Local HuggingFace dropdown (hf_models.csv, vlm # category) and loaded via Qwen3VLForConditionalGeneration in models.get_vlm(). # Requires transformers >= 5.0 (the Qwen3VL classes don't exist in 4.x) — see # models._MIN_TRANSFORMERS_VERSION["qwen3vl"]. QWEN3_VL_IDS = {"Qwen/Qwen3-VL-2B-Instruct", "Qwen/Qwen3-VL-4B-Instruct", "Qwen/Qwen3-VL-8B-Instruct"} SMOL_VLM_IDS = {"HuggingFaceTB/SmolVLM-256M-Instruct", "HuggingFaceTB/SmolVLM-500M-Instruct", "HuggingFaceTB/SmolVLM2-2.2B-Instruct"} ORNITH_IDS = { "deepreinforce-ai/Ornith-1.0-9B", } # Gemma 4 (all sizes) needs transformers >= 5.10.1 — see # models._MIN_TRANSFORMERS_VERSION["gemma4"] for the guard that checks # this before load. Every entry in BASE_MODEL_OPTIONS is a Gemma 4 model # (the app's base LLM family), so this guard applies to the whole default # lineup — google/gemma-4-E2B-it (the app's default LLM), E4B, the Mobile # QAT edge checkpoint, and the 12B/26B-A4B/31B ladder. # ────────────────────────────────────────────────────────────────── # Hugging Face Inference API — persisted settings. The sentinel # constant HF_INFERENCE_API_SENTINEL is defined near the top of this # file alongside the other provider constants. # ────────────────────────────────────────────────────────────────── def _update_env_file(key: str, val: str) -> None: try: from backend.paths import user_data_dir u_dir = user_data_dir() u_dir.mkdir(parents=True, exist_ok=True) env_path = u_dir / ".env" lines = [] if env_path.exists(): with open(env_path, "r", encoding="utf-8") as f: lines = f.readlines() new_lines = [] found = False for line in lines: if line.strip().startswith(f"{key}=") or line.strip().startswith(f"{key} ="): new_lines.append(f"{key}={val}\n") found = True else: new_lines.append(line) if not found: if new_lines and not new_lines[-1].endswith("\n"): new_lines.append("\n") new_lines.append(f"{key}={val}\n") with open(env_path, "w", encoding="utf-8") as f: f.writelines(new_lines) except Exception: pass _LAST_SYNCED_HF_TOKEN: Optional[str] = None def _sync_hf_token(token: str) -> None: global _LAST_SYNCED_HF_TOKEN t = str(token or "").strip() if not t or t == "hf_abc123" or _LAST_SYNCED_HF_TOKEN == t: return _LAST_SYNCED_HF_TOKEN = t os.environ["HF_TOKEN"] = t os.environ["HUGGING_FACE_HUB_TOKEN"] = t os.environ["HUGGINGFACEHUB_API_TOKEN"] = t _update_env_file("HF_TOKEN", t) def get_saved_hf_token() -> str: val = str(user_config.USER_CONFIG.get("hf_token", "")).strip() if val and val != "hf_abc123": _sync_hf_token(val) return val env_val = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN", "") or os.environ.get("HUGGING_FACE_HUB_TOKEN", "") if env_val: _sync_hf_token(env_val) return env_val def set_hf_token(token: str) -> None: user_config.save_user_config({"hf_token": token}) _sync_hf_token(token) # Synchronize HF token to os.environ and .env on startup _initial_hf_token = get_saved_hf_token() if _initial_hf_token: _sync_hf_token(_initial_hf_token) def get_saved_hf_model_id() -> str: """The last-saved Settings HF model id, or '' when nothing was ever saved. NOTE: the Settings '🤗 HF Model ID' field is gone (the per-tab curated pickers are the only HF API model selector), so this only feeds the legacy sentinel path / _hf_api_default_label — callers pick their own default via get_hf_api_model_id_for() / the curated headline.""" return str(user_config.USER_CONFIG.get("hf_model_id", "")).strip() def get_hf_api_model_id_for(model_type: str) -> str: """The remote model id the HF Inference API sentinel path should use for *model_type* ('llm' / 'vlm' / 'stt' / 'embed'): the last-saved Settings id when one exists (legacy installs), else the fixed per-type default (whisper-small for STT, bge-m3 for embedding, headline chat/VLM models for llm/vlm). The curated per-tab pickers send their own id directly and never hit this.""" saved = str(user_config.USER_CONFIG.get("hf_model_id", "")).strip() if saved: return saved return { "llm": HF_API_DEFAULT_LLM_ID, "vlm": HF_API_DEFAULT_VLM_ID, "stt": HF_API_DEFAULT_STT_ID, "embed": HF_API_DEFAULT_EMBED_ID, }.get(model_type, HF_API_DEFAULT_LLM_ID) def set_hf_model_id(model_id: str) -> None: user_config.save_user_config({"hf_model_id": model_id}) def get_saved_hf_provider() -> str: return str(user_config.USER_CONFIG.get("hf_provider", "")) def set_hf_provider(provider: str) -> None: user_config.save_user_config({"hf_provider": provider}) # ────────────────────────────────────────────────────────────────── # LiteLLM — persisted settings (model id, API key, API base). # ────────────────────────────────────────────────────────────────── def get_saved_litellm_model_id() -> str: return str(user_config.USER_CONFIG.get("litellm_model_id", "")) def set_litellm_model_id(model_id: str) -> None: user_config.save_user_config({"litellm_model_id": model_id}) def get_saved_litellm_api_key() -> str: return str(user_config.USER_CONFIG.get("litellm_api_key", "")) def set_litellm_api_key(key: str) -> None: user_config.save_user_config({"litellm_api_key": key}) def get_saved_litellm_api_base() -> str: return str(user_config.USER_CONFIG.get("litellm_api_base", "")) def set_litellm_api_base(base: str) -> None: user_config.save_user_config({"litellm_api_base": base}) # MODEL_OPTIONS starts as a copy of the base HuggingFace models loaded from models.csv. Any local # .gguf models found under llama_backend.LLAMA_CPP_MODEL_DIR are merged in # on top of it so they appear in the same dropdowns. MODEL_OPTIONS = dict(BASE_MODEL_OPTIONS) MODEL_OPTIONS.update(llama_backend.discover_gguf_models()) MODEL_OPTIONS.update(PRESET_GGUF_MODELS) def resolve_model_id(label_or_id: str, provider: Optional[str] = None, model_type: str = "llm") -> str: """Resolve a model dropdown label OR model_id string to a concrete model_id.""" if not label_or_id: return DEFAULT_VLM_MODEL if model_type == "vlm" else DEFAULT_LLM_MODEL s = str(label_or_id).strip() # If provider specified, check provider-filtered map first if provider: opts = get_model_options_for_provider(provider, model_type) if s in opts: return opts[s] if s in opts.values(): return s # Fallback: if the label is in the full HF API catalog but was # filtered out of the VLM dropdown (non-VLM model), still resolve # it — the Vision tab's dropdown filters for VLM-only, but the # resolved id must still work for any valid label. if provider == PROVIDER_HF_API and model_type == "vlm": if s in HF_API_MODEL_OPTIONS: return HF_API_MODEL_OPTIONS[s] if s in HF_API_MODEL_OPTIONS.values(): return s # Direct match in registry dicts if model_type == "vlm": if s in VLM_OPTIONS: return VLM_OPTIONS[s] if s in BASE_VLM_OPTIONS: return BASE_VLM_OPTIONS[s] else: if s in MODEL_OPTIONS: return MODEL_OPTIONS[s] if s in PRESET_GGUF_MODELS: return PRESET_GGUF_MODELS[s] if s in BASE_MODEL_OPTIONS: return BASE_MODEL_OPTIONS[s] return s def is_multimodal_model(model_id, provider: Optional[str] = None) -> bool: """Cheap, no-load check that a model id can actually SEE images — the single source of truth behind the app-wide "same-model" rule (RAG visual grounding, Deep Research's image visualizer): the grounding pass runs on the chat's OWN model, so it must never load a second model (or trigger a retriever load) just to discover the model can't see images. True for GGUF VLMs (a discovered mmproj pair, a gguf_models.csv `vlm` / `both` row, or a pinned `repo#main.gguf#mmproj.gguf` id), the registered transformers multimodal families (Gemma-4 / Qwen2.5-VL / Qwen3-VL / SmolVLM), and — for the remote HF Inference API provider — only the same model the Vision tab defaults to (a text-only remote id would just burn an API call).""" s = str(model_id or "") if not s: return False if s in GGUF_VLM_MMPROJ_MAP: return True if s in PRESET_GGUF_VLM_MODELS.values(): return True if s.count("#") >= 2: # `repo#main.gguf#mmproj.gguf` — a pinned VLM pair (see AGENTS.md). return True if s in GEMMA4_IDS or s in QWEN_VL_IDS or s in QWEN3_VL_IDS or s in SMOL_VLM_IDS: return True if provider == PROVIDER_HF_API: return s == HF_API_DEFAULT_VLM_ID return False # ────────────────────────────────────────────────────────────────── # LLM default selection — dynamic per detected hardware tier, following # README.md's Gemma 4 "Recommended Model / Quantization" ladder: # CPU-only / <8GB -> Gemma-4-E2B (4-bit or Mobile QAT) 1.5-3 GB # 8-12GB GPU -> Gemma-4-E4B (4-bit) 3-5 GB # 16GB GPU -> Gemma-4-26B-A4B (MoE, 4-bit) 8-14 GB # 24GB GPU -> Gemma-4-26B-A4B (MoE, 8-bit) 14-28 GB # 24GB+ (max quality) -> Gemma-4-31B (Dense, 4-bit) 18-20 GB # The max VRAM the ladder targets is 24GB (realistic ceiling) — the # 48GB+ hardware tier is treated as the "24GB max quality" pick. # The ladder's quantization column is mirrored by # get_recommended_quantization(). A saved user override # (default_llm_label in user_config.json, set via set_default_llm()) # always wins, same persisted-choice pattern as DEFAULT_VLM_LABEL. # ────────────────────────────────────────────────────────────────── _LLM_LABEL_BY_TIER = { HardwareManager.TIER_CPU_ONLY: "google/gemma-4-E2B-it", HardwareManager.TIER_8GB_VRAM: "google/gemma-4-E4B-it", HardwareManager.TIER_16GB_VRAM: "google/gemma-4-26B-A4B-it", HardwareManager.TIER_24GB_VRAM: "google/gemma-4-26B-A4B-it", HardwareManager.TIER_48GB_VRAM: "google/gemma-4-31B-it", HardwareManager.TIER_UNKNOWN: "google/gemma-4-E2B-it", } # Absolute fallback — the smallest Gemma 4, guaranteed present in every install. _LLM_FALLBACK_MODEL_ID = "google/gemma-4-E2B-it" def _label_for_model_id(model_id: str, options: dict) -> Optional[str]: """Reverse-lookup a dropdown label for a model id, or None.""" for label, val in options.items(): if val == model_id: return label return None def get_recommended_llm_label() -> str: """The LLM label recommended for THIS machine. Uses CSV default if set.""" if CSV_DEFAULT_LLM_LABEL and CSV_DEFAULT_LLM_LABEL in MODEL_OPTIONS: return CSV_DEFAULT_LLM_LABEL tier = HardwareManager.detect_hardware_tier() model_id = _LLM_LABEL_BY_TIER.get(tier, _LLM_FALLBACK_MODEL_ID) lbl = _label_for_model_id(model_id, MODEL_OPTIONS) if lbl: return lbl fallback_lbl = _label_for_model_id(_LLM_FALLBACK_MODEL_ID, MODEL_OPTIONS) if fallback_lbl: return fallback_lbl return next(iter(MODEL_OPTIONS.keys())) if MODEL_OPTIONS else "" def get_default_llm_label() -> str: """The LLM label actually selected by default in the UI, unless the user has a saved override in user_config.json — mirrors get_default_vlm_label()'s persisted-choice-wins pattern.""" saved = user_config.USER_CONFIG.get("default_llm_label") if saved and saved in MODEL_OPTIONS: return saved rec = get_recommended_llm_label() if rec and rec in MODEL_OPTIONS: return rec return next(iter(MODEL_OPTIONS.keys())) if MODEL_OPTIONS else "" def set_default_llm(label: str) -> None: """Persist an explicit default-LLM choice — same pattern as set_default_vlm().""" user_config.save_user_config({"default_llm_label": label}) DEFAULT_LLM_LABEL = get_default_llm_label() DEFAULT_LLM_MODEL = MODEL_OPTIONS.get(DEFAULT_LLM_LABEL, next(iter(MODEL_OPTIONS.values())) if MODEL_OPTIONS else "") def rescan_gguf_models(folder_path: Optional[str], lang_key: str = "kh"): """Set (or change) the GGUF model folder at runtime and rebuild MODEL_OPTIONS (text LLMs) and VLM_OPTIONS (vision-model pairs), without needing to edit code or restart the app. Returns (status_message, dropdown_defaults) where dropdown_defaults is a dict {tab_key: (choices, selected)} covering the General/RAG/ Data-Analysis LLM pickers plus the Vision LLM picker — the plain data shape the API layer turns into dropdown updates. """ l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) folder_path = (folder_path or "").strip() # Persists to user_config.json and updates llama_backend.LLAMA_CPP_MODEL_DIR llama_backend.set_model_dir(folder_path) whisper_cpp_backend.set_whisper_model_dir(folder_path) MODEL_OPTIONS.clear() MODEL_OPTIONS.update(BASE_MODEL_OPTIONS) MODEL_OPTIONS.update(PRESET_GGUF_MODELS) if not folder_path: msg = l["gguf_scan_disabled"] else: found = llama_backend.discover_gguf_models(folder_path) MODEL_OPTIONS.update(found) vlm_found_count = len(llama_backend.discover_gguf_vlm_models(folder_path)) if found or vlm_found_count: msg = l["gguf_scan_found"].format(n=len(found), dir=folder_path) if vlm_found_count: msg += f" (+ {vlm_found_count} vision model pair(s) found for the 🎨 Vision LLM dropdown)" else: msg = l["gguf_scan_empty"].format(dir=folder_path) if not llama_backend.LLAMA_CPP_AVAILABLE: msg += (" ⚠️ llama-cpp-python not installed — in-process loading unavailable." " Use '⚙️ LLM Backend' > 'llama-server (external process)' to run GGUF models without it.") # Vision GGUF pairs (main model + mmproj) are scanned/rebuilt # independently of the plain text-model branch above — # _rebuild_gguf_vlm_options() already no-ops safely on an # empty/invalid folder or a missing llama-cpp-python install. _rebuild_gguf_vlm_options(folder_path) # Provider-aware rebuild — each tab's dropdown must keep showing only # the models valid for its own saved provider (e.g. GGUF-only for # llama.cpp), not every model in the registry, otherwise the UI offers # HuggingFace models to the llama.cpp provider (and vice versa). dd_gen, dd_gen_v = get_model_dropdown_defaults("gen", "llm") dd_rag, dd_rag_v = get_model_dropdown_defaults("rag", "llm") dd_data, dd_data_v = get_model_dropdown_defaults("data", "llm") dd_vlm, dd_vlm_v = get_model_dropdown_defaults("vlm", "vlm") return (msg, { "gen": (dd_gen, dd_gen_v), "rag": (dd_rag, dd_rag_v), "data": (dd_data, dd_data_v), "vlm": (dd_vlm, dd_vlm_v), }) # ────────────────────────────────────────────────────────────────── # VLM_OPTIONS starts as a copy of the base HuggingFace VLMs loaded from models.csv. Any local # GGUF vision-model pairs (main .gguf + matching mmproj .gguf) found # under llama_backend.LLAMA_CPP_MODEL_DIR are merged in on top of it — # same pattern as MODEL_OPTIONS for text LLMs. VLM_OPTIONS = dict(BASE_VLM_OPTIONS) # Default VLM selection — dynamic per detected hardware tier, mirroring # Gemma 4 recommendations. A saved user override (see set_default_vlm()) # always wins, same persisted-choice pattern as DEFAULT_EMBED_MODEL above. _VLM_MODEL_BY_TIER = { HardwareManager.TIER_48GB_VRAM: "google/gemma-4-E4B-it", HardwareManager.TIER_24GB_VRAM: "google/gemma-4-E4B-it", HardwareManager.TIER_16GB_VRAM: "google/gemma-4-E4B-it", HardwareManager.TIER_8GB_VRAM: "google/gemma-4-E2B-it", HardwareManager.TIER_CPU_ONLY: "google/gemma-4-E2B-it", HardwareManager.TIER_UNKNOWN: "google/gemma-4-E2B-it", } _VLM_FALLBACK_MODEL_ID = "google/gemma-4-E2B-it" def get_recommended_vlm_label() -> str: """The Vision LLM label recommended for THIS machine. Uses CSV default if set.""" if CSV_DEFAULT_VLM_LABEL and CSV_DEFAULT_VLM_LABEL in VLM_OPTIONS: return CSV_DEFAULT_VLM_LABEL tier = HardwareManager.detect_hardware_tier() model_id = _VLM_MODEL_BY_TIER.get(tier, _VLM_FALLBACK_MODEL_ID) lbl = _label_for_model_id(model_id, VLM_OPTIONS) if lbl: return lbl return next(iter(VLM_OPTIONS.keys())) if VLM_OPTIONS else "" def get_default_vlm_label() -> str: """The VLM label actually selected by default in the UI, unless the user has a saved override in user_config.json — mirrors get_default_embed_model()'s persisted-choice-wins pattern.""" saved = user_config.USER_CONFIG.get("default_vlm_label") if saved and saved in VLM_OPTIONS: return saved return get_recommended_vlm_label() def set_default_vlm(label: str) -> None: """Persist an explicit default-VLM choice — same pattern as set_embed_model().""" user_config.save_user_config({"default_vlm_label": label}) DEFAULT_VLM_LABEL = get_default_vlm_label() DEFAULT_VLM_MODEL = VLM_OPTIONS.get(DEFAULT_VLM_LABEL, next(iter(VLM_OPTIONS.values())) if VLM_OPTIONS else "") # Maps a GGUF vision model's main .gguf path -> its paired mmproj (vision # projector) .gguf path (see llama_backend.discover_gguf_vlm_models()). # models.get_vlm() looks this up by model_id, since llama.cpp needs BOTH # files' paths to actually load a GGUF vision model — unlike text-only # GGUF models, which need just the one file. GGUF_VLM_MMPROJ_MAP = {} # Maps a GGUF vision model's main .gguf path -> {label: mmproj_path} for # all compatible mmproj files in the same folder. Populated by # _rebuild_gguf_vlm_options(). Used by the mmproj dropdown in Vision Chat. VLM_MMPROJ_CANDIDATES_MAP: dict[str, dict[str, str]] = {} def get_mmproj_choices_for_vlm(model_path: str) -> dict[str, str]: """Return {label: mmproj_path} for the mmproj dropdown in Vision Chat. If explicit candidates exist for this model path, return those. Otherwise fall back to scanning the model's folder.""" cached = VLM_MMPROJ_CANDIDATES_MAP.get(model_path) if cached: return cached fresh = llama_backend.get_mmproj_candidates_for_model(model_path) if fresh: VLM_MMPROJ_CANDIDATES_MAP[model_path] = fresh return fresh def _rebuild_gguf_vlm_options(folder: Optional[str] = None): """(Re)populate VLM_OPTIONS with discovered GGUF vision-model pairs from `folder` (or the current LLAMA_CPP_MODEL_DIR) and refresh GGUF_VLM_MMPROJ_MAP and VLM_MMPROJ_CANDIDATES_MAP to match. Mutates all dicts in place (never reassigns), same pattern as MODEL_OPTIONS's text-LLM rescan.""" VLM_OPTIONS.clear() VLM_OPTIONS.update(BASE_VLM_OPTIONS) GGUF_VLM_MMPROJ_MAP.clear() VLM_MMPROJ_CANDIDATES_MAP.clear() for label, (model_path, mmproj_path) in llama_backend.discover_gguf_vlm_models(folder).items(): VLM_OPTIONS[label] = model_path GGUF_VLM_MMPROJ_MAP[model_path] = mmproj_path candidates = llama_backend.get_mmproj_candidates_for_model(model_path) if candidates: VLM_MMPROJ_CANDIDATES_MAP[model_path] = candidates _rebuild_gguf_vlm_options() # ────────────────────────────────────────────────────────────────── # Visual retriever (ColPali-style, for visual PDF RAG) options # ────────────────────────────────────────────────────────────────── VISUAL_RETRIEVER_OPTIONS = { "vidore/colpali-v1.3-hf (~2 GB | recommended)": "vidore/colpali-v1.3-hf", "vidore/colqwen2-v1.0 (~8 GB | higher accuracy)": "vidore/colqwen2-v1.0", } DEFAULT_VISUAL_RETRIEVER = "vidore/colpali-v1.3-hf" # ────────────────────────────────────────────────────────────────── # Speech-to-Text (Whisper) options # ────────────────────────────────────────────────────────────────── def get_default_stt_label() -> str: saved = user_config.USER_CONFIG.get("default_stt_label") if saved and saved in STT_OPTIONS: return saved if CSV_DEFAULT_STT_LABEL and CSV_DEFAULT_STT_LABEL in STT_OPTIONS: return CSV_DEFAULT_STT_LABEL return next(iter(STT_OPTIONS.keys())) if STT_OPTIONS else "" DEFAULT_STT_LABEL = get_default_stt_label() DEFAULT_STT_MODEL = STT_OPTIONS[DEFAULT_STT_LABEL] if DEFAULT_STT_LABEL in STT_OPTIONS else ""