Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+29
- .gitattributes+2
- DockerfileAdded+39
- README.md+14-21
- agents/__init__.pyAdded+1
- agents/agent_factory.pyAdded+391
- agents/agent_memory.pyAdded+661
- agents/agent_streaming.pyAdded
- agents/data_analysis.pyAdded
- agents/deep_research_agent.pyAdded+807
- agents/general_agent.pyAdded+896
- agents/playwright_search_tool.pyAdded+1189
- agents/rag_agent.pyAdded+823
- app.pyAdded+76
- backend/__init__.pyAdded+1
- backend/audio_denoise.pyAdded+148
- backend/chat.pyAdded+1512
- backend/component_downloader.pyAdded+891
- backend/docx_export.pyAdded+293
- backend/gguf_models.csvAdded+39
- backend/hardware.pyAdded+1794
- backend/hf_api_models.csvAdded+128
- backend/hf_models.csvAdded+32
- backend/index_docs.pyAdded+94
- backend/knowledge_base.pyAdded
- backend/live_stream.pyAdded+109
- backend/llama_backend.pyAdded
- backend/llama_health.pyAdded+356
- backend/local_server.pyAdded+184
- backend/metadata_hardening.pyAdded+176
- backend/model_registry.pyAdded
- backend/models.pyAdded
- backend/paths.pyAdded+91
- backend/report_tools.pyAdded+490
- backend/stdio_hardening.pyAdded+231
- backend/torchaudio_health.pyAdded+193
- backend/user_config.pyAdded+70
- backend/web_api.pyAdded
- backend/whisper_cpp_backend.pyAdded+261
- requirements.txtAdded+41
- ui/__init__.pyAdded+1
- ui/branding.pyAdded+229
- ui/i18n.pyAdded
- ui/image/logo.icoAdded
- ui/image/logo.jpgAdded
- ui/image/logo_round.pngAdded
- ui/web/dist/assets/index-CaFw1y7V.cssAdded+1
- ui/web/dist/assets/index-CcfSqwDm.jsAdded
- ui/web/dist/favicon.pngAdded
- ui/web/dist/index.htmlAdded+15
1234567891011121314151617181920212223242526272829.git.venv.venv-build__pycache__*.pyc*.pyo*.pyd.pytest_cache.vscode.vs.idea*.loginstallertoolstestsOutputuser_data/gguf_modelsuser_data/chroma_dbuser_data/visual_indexuser_data/msix_certificateuser_data/tutorial_*user_data/exportsuser_data/reportsuser_data/old_filesuser_data/my_hf/build_stagethird_party*.exe*.msix*.iss32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textui/image/logo.ico filter=lfs diff=lfs merge=lfs -textui/image/logo.jpg filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839FROM python:3.11-slim
# Install system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ curl \ git \ ffmpeg \ libsm6 \ libxext6 \ poppler-utils \ && rm -rf /var/lib/apt/lists/*
# Create user for Hugging Face Spaces (UID 1000)RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \ PATH=/home/user/.local/bin:$PATH \ PYTHONUNBUFFERED=1 \ MPLBACKEND=Agg \ HF_HUB_DISABLE_TELEMETRY=1 \ DO_NOT_TRACK=1
WORKDIR $HOME/app
# Install Python requirementsCOPY --chown=user:user requirements.txt $HOME/app/requirements.txtRUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r requirements.txt
# Copy application source codeCOPY --chown=user:user . $HOME/app
# Ensure user_data directory is writableRUN mkdir -p $HOME/app/user_data && chmod -R 777 $HOME/app/user_data
EXPOSE 7860
CMD ["uvicorn", "backend.web_api:app", "--host", "0.0.0.0", "--port", "7860"]2 unmodified lines3456789101112131415161718192021222324252627282930313233342 unmodified linesemoji: 🤖colorFrom: indigocolorTo: bluesdk: staticpinned: falselicense: mitshort_description: Khmer & English AI Assistant powered by LocalAiLabtags:- khmer- ai-assistant- svelte- smolagents---# 🤖 LocalAiLab Assistant (ជំនួយការ AI)An AI Assistant with full support for **Khmer (ភាសាខ្មែរ)** and **English**, featuring multi-turn conversation, document analysis, vision analysis, speech-to-text, and data exploration.---### ✨ Features / លក្ខណៈពិសេស- 💬 **General Chat (ការសន្ទនាទូទៅ)** — Multi-turn conversation with high-performance LLMs.- 📚 **RAG & Document Q&A (ការស្រាវជ្រាវឯកសារ)** — Context-grounded Q&A.- 🖼️ **Vision Chat (ការវិភាគរូបភាព)** — Multimodal reasoning and image understanding.- 🎙️ **Speech to Text (ការបំប្លែងសំឡេងជាអក្សរ)** — Speech transcription.- ⚙️ **Custom Model Selection** — Connect to Hugging Face Serverless Inference, OpenAI, Gemini, or local models.---### 🌐 Direct Anonymous AccessYou can access this application directly with zero platform chrome:👉 **[https://localailb-assistant.hf.space](https://localailb-assistant.hf.space)**2 unmodified lines34567891011121314151617181920212223242526272 unmodified linesemoji: 🤖colorFrom: indigocolorTo: bluesdk: dockerapp_port: 7860pinned: falselicense: mitshort_description: Khmer & English AI Assistant powered by smolagents & Svelte---# 🤖 LocalAiLab Assistant (ជំនួយការ AI)LocalAiLab Assistant is an AI Assistant with full support for Khmer and English languages, powered by **FastAPI**, **Svelte**, **smolagents**, and **ChromaDB**.## ✨ Features / លក្ខណៈពិសេស- 💬 **General Chat (ការសន្ទនាទូទៅ)** — Multi-turn conversation with LLMs- 📚 **RAG Chat (ការស្រាវជ្រាវឯកសារ)** — Grounded document Q&A with vector search- 🔬 **Deep Research (ការស្រាវជ្រាវស៊ីជម្រៅ)** — Multi-agent iterative web research- 🖼️ **Vision Chat (ការវិភាគរូបភាព)** — Multimodal reasoning and image understanding- 🎙️ **Speech to Text (ការបំប្លែងសំឡេងជាអក្សរ)** — Speech transcription- 📊 **Data Analysis (ការវិភាគទិន្នន័យ)** — Automated data exploration, Python code execution, and charts- 📂 **Knowledge Base (មូលដ្ឋានចំណេះដឹង)** — Indexing PDFs, DOCX, and text files## 🚀 Running on Hugging Face SpacesThis space is running as a custom Docker container with FastAPI serving the Svelte frontend on port `7860`.
1# agents package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391"""agent_factory.py — Shared smolagents agent-construction helpers.
Every agentic tab in the app (General Chat, RAG Chat, Deep Research, DataAnalysis) builds its smolagents agent(s) with the same version-compatdance:
1. Pick ToolCallingAgent vs CodeAgent (either explicitly, or via a per-tab tool-calling heuristic). 2. Sniff the installed smolagents version's `__init__` parameters with `inspect.signature()` to learn which OPTIONAL kwargs it accepts (`code_block_tags`, `instructions`, `executor_kwargs`, `final_answer_checks`, ...) so a missing parameter silently no-ops instead of crashing with an unexpected-keyword error. 3. Construct the agent.
Centralizing that here means a smolagents API change is fixed in ONEplace instead of four — see also AGENTS.md's "the app must always launch,on any environment, and degrade gracefully" guidance."""
import importlib.resourcesimport inspectimport refrom typing import Optional
import yaml
from smolagents import CodeAgent, ToolCallingAgent
def reject_leaked_or_empty_final_answer(final_answer, *_, **__) -> bool: """Shared `final_answer_checks` validator attached to EVERY agent built here (merged with any per-tab checks, e.g. Deep Research's report validator). Rejects a final answer that is:
1. empty/blank — the model produced nothing usable; 2. a leaked raw ReAct 'Action: {…}' tool-call envelope (the failure mode the agent_streaming parser recovery fixes at parse time — this check catches any that slip through to the answer); 3. the repr of an internal object (ToolCall(...) / '<...>') instead of real answer text; 4. chat-template control-token garbage (e.g. Muse Glimmer's "to=user<|eot|>" channel-close fragment) — an answer that is pure template tokens, i.e. becomes empty once the known control tokens are stripped, is not an answer; 5. degenerate token repetition ("skills skills skills …" forever — the broken-generation loop observed when a text request landed on an EMBEDDING model through a shared llama-server port). An answer that IS the loop is not an answer. 6. a pure execution-planning monologue — the GLM Deep Research leak where the manager called final_answer() with its INTERNAL PLAN ("The user wants me to proceed with the plan I outlined. Let me execute the plan step by step … Let me start with searching …") instead of an actual report. A SHORT answer opening with first-person execution-planning phrasing is meta-commentary, not findings.
smolagents runs each check against the proposed final answer beforeaccepting it and feeds a rejection back to the model for one moreattempt, so this guards answer quality at the source for every agentictab. Signature matches smolagents' invocation`check_function(final_answer, memory, agent=self)`.""" text = str(final_answer or "").strip() if not text: return False if re.match(r"^\s*Action:?\s*\{", text, re.DOTALL | re.IGNORECASE): return False if (text.startswith("ToolCall(") or text == "None" or text.startswith("<smolagents") or text.startswith("<class ") or text.startswith("<built-in ")): return False # Chat-template control-token garbage (the Muse Glimmer leak observed # end-to-end: the model wrote its template's channel-close fragment # "to=user<|eot|>" as the WHOLE final-answer payload). Strip the known # tokens (agent_streaming.strip_template_tokens); an answer that # becomes EMPTY was pure template garbage and is rejected — smolagents # then feeds the rejection back for one more attempt — never shipped # as the answer bubble. try: from agents.agent_streaming import strip_template_tokens, _strip_deliberation_preamble cleaned = strip_template_tokens(text).strip() cleaned = _strip_deliberation_preamble(cleaned).strip() except Exception: cleaned = text if not cleaned: return False # The strip can also leave a bare role word ("<|im_start|>user<|im_end|>" # → "user") — still not an answer. if cleaned.lower() in ("user", "assistant", "system", "tool", "self"): return False # Degenerate token repetition (case 5): reject so smolagents feeds the # rejection back for another attempt instead of shipping thousands of # repeated tokens as the answer. try: from agents.agent_streaming import is_degenerate_repetition if is_degenerate_repetition(cleaned): return False except Exception: pass # Pure execution-planning / deliberation monologue (case 6): the GLM # ("The user wants me to proceed with the plan I outlined. Let me # execute …", or Khmer meta-plan "គោលការណ៍ដើម្បីដោះស្រាយ ... ប្រើឧបករណ៍ summarize_theme") # and Muse-Glimmer ("We need more detailed info … Let's call web_search_agent for host cities …") # leaks — the manager called final_answer() with its INTERNAL DELIBERATION # or SOLVING PLAN instead of a report. Detectors: # a) the text OPENS with first-person execution-planning phrasing; # b) the text contains explicit meta-planning headings/sections # (e.g. គោលការណ៍ដើម្បីដោះស្រាយ, ផែនការដោះស្រាយ, Facts survey:, Plan of action:); # c) the text discusses CALLING or using sub-agent/retriever tools in prose # (e.g. let's call knowledge_searcher, ប្រើឧបករណ៍ summarize_theme); # d) short unstructured text mentioning sub-agent names. if len(cleaned) < 4000: low = cleaned.lower() planning_openers = ( "the user wants", "the user is asking", "the user asked", "the user's question is", "the user asked for", "we need to", "we need more", "we need who", "we have retrieved", "we have findings", "we have some info", "we have search results", "let me execute", "let me proceed", "let me start", "let me search", "let me break down", "let's call", "lets call", "let's search", "let's list", "lets list", "i'll start by", "i will start by", "first, i need to", "first, i'll", "first i need to", "i will compile the answer", "i will write the response", "the search results provide", "the task:", "the task is", "ដំបូង ខ្ញុំត្រូវ", "ជាដំបូង ខ្ញុំត្រូវ", "ខ្ញុំនឹងចាប់ផ្តើម", "យើងត្រូវតែ", "យើងត្រូវការ", "អ្នកបានសួរថា", "សំណួររបស់អ្នកប្រើ៖", ) if any(low.startswith(op) for op in planning_openers): return False
# Meta-planning sections in Khmer or English (e.g. GLM-4.7-Flash plan leak) meta_plan_markers = ( "គោលការណ៍ដើម្បីដោះស្រាយ", "ផែនការដោះស្រាយ", "ផែនការសកម្មភាព", "ផែនការអនុវត្ត", "facts survey:", "plan of action:", "facts to look up:", "facts to derive:", "part 1 (facts survey)", "part 2 (plan)", "analyze the request:", ) if any(marker in low for marker in meta_plan_markers): return False
# Tool calling deliberation / invocation phrases in prose tool_deliberation_markers = ( "let's call knowledge_searcher", "let's call web_search_agent", "lets call knowledge_searcher", "lets call web_search_agent", "we can use knowledge_searcher", "could summarize documents or search", "better to search", "possibly search for", "we should diversify queries", "calling tools:", "calling tool:", "ប្រើឧបករណ៍ summarize_", "ប្រើឧបករណ៍ knowledge_searcher", "ប្រើឧបករណ៍ retriever", "ប្រើឧបករណ៍ list_", ) if any(marker in low for marker in tool_deliberation_markers): return False
if len(cleaned) < 2500: sub_agent_tools = ( "web_search_agent", "knowledge_searcher", "data_worker", "playwright_visualizer", ) if any(name in low for name in sub_agent_tools): if any(verb in low for verb in ("call", "calling", "invoke", "use", "task:", "agent", "ប្រើ")): if not (any(marker in cleaned for marker in ("\n#", "\n-", "\n*")) and ("### references" in low or "## references" in low or len(cleaned) > 1500)): return False return True
def supports_native_tool_calls(llm) -> bool: """Default tool-calling policy: prefer ToolCallingAgent for every model.
TransformersModel, LlamaCppModel, LiteLLMModel and InferenceClientModel all get reliable structured tool execution without code-parsing errors; CodeAgent remains the choice for Data Analysis where Python execution is required. Tabs with a stricter heuristic pass their own predicate via build_smol_agent(tool_calling_predicate=...). """ return True
# ──────────────────────────────────────────────────────────────────# Trimmed default prompt templates.## smolagents' default CodeAgent / ToolCallingAgent system prompts ship a# ~5-8K-char block of five worked examples using NOTIONAL tools# (`document_qa`, `image_generator`, `translator`, `wikipedia_search`, …)# that don't exist on any of this app's agents. For small quantized GGUF# models (e.g. Gemma-4-E2B QAT q4_0 — this app's default) run through# llama-cpp-python, that huge instruction blob — not any provider-specific# template rendering, which is byte-identical across backends (verified# against the transformers `apply_chat_template` render) — is the main# reason a weak model gets overwhelmed and starts "answering the system# prompt" instead of the user question. The strip below drops the worked# examples while keeping the essential agent grammar: the# Thought/Code/Observation cycle, the tools code-block, the rules, and the# `custom_instructions` slot (where the app's per-tab instructions land).## `prompt_templates=` REPLACES the whole default dict (smolagents asserts# all keys present), so the trim operates on a copy of the real default# YAML and returns the full dict — keeping `planning` / `managed_agent` /# `final_answer` templates intact so planning and managed-agent prompts# are untouched. The strip is defensive: if a future smolagents renames# the example markers, the unmatched text is returned unchanged (the# agent then uses the stock template rather than crashing).# ──────────────────────────────────────────────────────────────────
_EXAMPLES_HEADER = "Here are a few examples using notional tools:"# Both default YAMLs close the examples block with a line like# "Above example(s) were using notional tools ... You only have access# to these tools ..." — cut up to (not including) that line so the tools# list intro stays put._EXAMPLES_CLOSE_RE = re.compile(r"\n\s*Above examples? were using notional tools", re.IGNORECASE)
def trim_worked_examples(system_prompt: str) -> str: """Strip smolagents' default worked-examples block from a system prompt.
Keeps the header/cycle description and everything from the "Above examples were using notional tools" line onward (the tools block, the rules, and the `{{custom_instructions}}` slot). Returns the text unchanged if the example markers aren't found (future smolagents template change — degrade gracefully). """ start = system_prompt.find(_EXAMPLES_HEADER) if start == -1: return system_prompt close = _EXAMPLES_CLOSE_RE.search(system_prompt[start:]) if not close: return system_prompt end = start + close.start() return system_prompt[:start].rstrip() + "\n\n" + system_prompt[end:].lstrip()
# smolagents' code_agent.yaml is chosen by CodeAgent (unless# use_structured_outputs_internally, which this factory never sets);# toolcalling_agent.yaml by ToolCallingAgent. Mirrors the exact resource# loading in each class's `__init__`.
_TRIMMED_TEMPLATES_CACHE: dict = {}
def build_trimmed_prompt_templates(agent_class) -> Optional[dict]: """The default smolagents prompt-templates dict for `agent_class`, with the worked-examples block stripped from its system prompt.
Returns the FULL dict (system_prompt + planning + managed_agent + final_answer) so passing it as `prompt_templates=` satisfies smolagents' required-keys assertion. Cached per class — the YAML is read once. Returns None only for an unknown agent class (callers then fall back to smolagents' stock templates). """ cached = _TRIMMED_TEMPLATES_CACHE.get(agent_class) if cached is not None: return cached if issubclass(agent_class, CodeAgent): yaml_name = "code_agent.yaml" elif issubclass(agent_class, ToolCallingAgent): yaml_name = "toolcalling_agent.yaml" else: _TRIMMED_TEMPLATES_CACHE[agent_class] = None return None templates = yaml.safe_load( importlib.resources.files("smolagents.prompts") .joinpath(yaml_name) .read_text(encoding="utf-8") ) assert isinstance(templates, dict), "smolagents prompt YAML must be a dict" templates["system_prompt"] = trim_worked_examples(templates["system_prompt"]) _TRIMMED_TEMPLATES_CACHE[agent_class] = templates return templates
def init_params(agent_class) -> dict: """All `__init__` parameter names accepted by `agent_class`, INCLUDING those declared on base classes ({} if uninspectable).
smolagents subclasses (CodeAgent / ToolCallingAgent) accept inherited arguments such as `instructions` (declared on MultiStepAgent.__init__) by forwarding **kwargs to the base, so inspecting only the subclass's own `__init__` signature would MISS them — and the version-compat guard below would silently drop the system prompt. Unioning the whole MRO keeps the sniff correct across smolagents versions: a parameter declared directly on the subclass (older versions) or on a base (1.26+) is detected either way.
Also used directly by callers that build a kwargs dict themselves but still want the single shared signature-sniffing implementation (e.g. Deep Research's search sub-agent).""" if not isinstance(agent_class, type): agent_class = type(agent_class) # tolerate instances (getmro needs a class) params = {} for klass in inspect.getmro(agent_class): try: params.update(inspect.signature(klass.__init__).parameters) except (TypeError, ValueError): continue return params
def build_smol_agent(llm, *, tools=None, max_steps: int, agent_class=None, use_tool_calling: bool = True, tool_calling_predicate=supports_native_tool_calls, instructions=None, execution_timeout=None, verbosity_level: int = 1, extra_kwargs=None, optional_kwargs=None): """Build a smolagents CodeAgent or ToolCallingAgent with the shared version-compat guards.
Tool calling is the DEFAULT for every agent (ToolCallingAgent) — structured function-calling avoids the code-parsing failure modes of CodeAgent (e.g. "Code parsing failed ... invalid character '—'" on small GGUF models copying scraped prose into Python blocks).
Args: llm: the smolagents-compatible Model (from models.get_llm()). tools: iterable of tools to attach to the agent. max_steps: step budget. agent_class: force a specific class (e.g. ToolCallingAgent for the Deep Research search sub-agent); defaults to picking from use_tool_calling + tool_calling_predicate. use_tool_calling: prefer ToolCallingAgent when True (the default). Set False ONLY for tabs that require Python code execution (Data Analysis) — see data_analysis.py. tool_calling_predicate: per-tab heuristic deciding whether the model supports native tool calling. instructions: system instructions — attached ONLY when this smolagents version's __init__ exposes an `instructions=` param. execution_timeout: per-step code-executor timeout in seconds, passed as `executor_kwargs` when supported and > 0. verbosity_level: smolagents verbosity (default 1). extra_kwargs: additional kwargs merged UNCONDITIONALLY (e.g. name/description/planning_interval/managed_agents). optional_kwargs: additional kwargs merged only for keys this smolagents version actually accepts (e.g. final_answer_checks). """ if agent_class is None: use_tc = use_tool_calling and tool_calling_predicate(llm) agent_class = ToolCallingAgent if use_tc else CodeAgent
params = init_params(agent_class)
kwargs = dict( model=llm, tools=list(tools or []), max_steps=max_steps, verbosity_level=verbosity_level, ) if extra_kwargs: kwargs.update(extra_kwargs)
# Version-guarded optional kwargs: # - CodeAgent expects fenced ```python blocks by default; the # markdown-fence convention is more broadly compatible with the # outputs of GGUF / "thinking"-tuned models. # - Trimmed prompt templates: smolagents' default system prompt ships # ~5-8K chars of worked examples using NOTIONAL tools that don't # exist on this app's agents. For small quantized GGUF models the # huge instruction blob is the main cause of the model "answering # the system prompt" — strip it at construction, uniformly for every # provider/backend (llama-cpp-python, llama-server, transformers, # HF API, LiteLLM) since all agents are built through this factory. if agent_class is CodeAgent and "code_block_tags" in params: kwargs["code_block_tags"] = "markdown" if "prompt_templates" in params: trimmed = build_trimmed_prompt_templates(agent_class) if trimmed is not None: kwargs["prompt_templates"] = trimmed if instructions is not None and "instructions" in params: kwargs["instructions"] = instructions if execution_timeout is not None and execution_timeout > 0 and "executor_kwargs" in params: kwargs["executor_kwargs"] = {"timeout_seconds": execution_timeout} if optional_kwargs: for k, v in optional_kwargs.items(): if k not in params or k == "final_answer_checks": continue # final_answer_checks is merged separately below kwargs[k] = v
# Shared final-answer hygiene check on EVERY agent, merged with any # per-tab checks the caller passed (e.g. Deep Research's report # validator) so both run. smolagents feeds a rejection back to the # model for one more attempt, so a leaked/empty answer costs a step # (bounded by the fail-fast guard in agent_streaming) instead of # silently becoming the result. if "final_answer_checks" in params: checks = [reject_leaked_or_empty_final_answer] if optional_kwargs and optional_kwargs.get("final_answer_checks"): checks += list(optional_kwargs["final_answer_checks"]) kwargs["final_answer_checks"] = checks
return agent_class(**kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661"""agent_memory.py — Shared multi-turn memory helpers for every smolagentsCodeAgent in the app (General Chat agentic mode, RAG Chat agentic mode,Data Analysis), following the official smolagents memory guide exactly:https://huggingface.co/docs/smolagents/tutorials/memory
Standard smolagents memory model---------------------------------smolagents keeps an agent's own history in `agent.memory.steps` — a plainPython list of TaskStep / ActionStep / PlanningStep objects. Two rulesfrom the official tutorial cover everything this app needs:
1. `agent.run(task, reset=False)` keeps `agent.memory.steps` across calls, instead of the `reset=True` default that wipes it at the start of every single call — this is what lets a follow-up like "and what about last year?" refer back to what was already asked. Every chat handler (chat.py / data_analysis.py) already does this correctly: `agent.run(task, reset=not use_memory)`. 2. Memory can be edited directly, as a plain list. The tutorial's own "Dynamically change the agent's memory" section does exactly this (`agent.memory.steps = previous_agent.memory.steps`, or trimming via a step_callback) — cap_agent_memory() below does the same thing (trim old turns by reassigning `agent.memory.steps`), and reset_memory() below calls smolagents' own `agent.memory.reset()` for the same effect when the whole conversation should be dropped.
This module is intentionally just those two small helpers now. It usedto also serialize `agent.memory.steps` to JSON on disk so memory wouldsurvive an app restart, not just a model swap within the same run — thatwas NEVER part of smolagents' own memory model (smolagents doesn't shipsave/load for `agent.memory` at all — see the still-openhttps://github.com/huggingface/smolagents/issues/1216), and hand-rollingit was the source of several real bugs:
- Reconstructing ToolCall / ChatMessage / Timing objects from a flattened dict is version-sensitive; a smolagents upgrade can silently rename/drop a field, which needed several defensive "filter down to whatever kwargs this version's constructor accepts" layers just to avoid crashing on load — a lot of fragility for a feature smolagents itself doesn't officially support. - Memory was persisted GLOBALLY per tab (shared across every model used in that tab), so replaying a step written by one model's tool-call format into a DIFFERENT model's chat template could produce a genuinely confused answer — a real quality/correctness bug, not just a theoretical risk. - Worse, it actively defeated Data Analysis's "a new dataset was uploaded, so old memory about the previous one shouldn't carry over" logic: that code correctly detected the dataset had changed and reset the agent — but building a replacement agent right afterward then reloaded the *exact same stale, pre-reset memory straight back off disk*, silently undoing the reset it was supposed to perform.
This file now sticks to the plain, official, RAM-only workflow instead:an agent's memory lives exactly as long as its Python object does. It'sgone the moment the model is switched, "Clear" is clicked, or the apprestarts — matching smolagents' own tutorial exactly, and matching the"🧠 Conversation Memory (Experimental)" checkbox's own label: this trades"memory survives a restart / model switch" for "memory behaves correctlyand predictably", which is the right trade given the bugs above.
Compaction (the third helper, added later)-------------------------------------------`compact_agent_memory()` upgrades the plain drop-oldest cap: instead ofthrowing the oldest turns away when the conversation grows, it FIRSTmeasures the agent memory's token footprint against the model's contextwindow, and — only when it's about to overflow — asks the model itself tocondense the older turns into a short rolling summary that is prependedto the system prompt (the most recent turns stay verbatim). This is the"true" compaction approach (approach #4 in the standard context-windowplaybook, with the token-usage trigger of #3), and it deliberately keepsthe exact same RAM-only lifecycle as everything else here: the summarylives on the agent object (`agent._rolling_summary`), dies with it, andis cleared by reset_memory() together with the steps. On any failure itdegrades to dropping the oldest turns — the old behaviour — so the chatloop is never worse off than before."""
from smolagents.memory import TaskStep
# ──────────────────────────────────────────────────────────────────# Turn-count cap (approach #2 — drop oldest turns)# ────────────────────────────────────────────────────────���─────────def cap_agent_memory(agent, max_turns: int = 6) -> None: """Keep only the most recent `max_turns` conversation turns in `agent.memory.steps` — the same "edit the list directly" pattern smolagents' own tutorial uses for trimming memory, just dropping whole old turns instead of individual fields/screenshots.
Each turn starts with a `TaskStep` (the user's message, or in Data Analysis's case the full task prompt) and is followed by whatever `ActionStep`/`PlanningStep`s the agent took to answer it. This drops whole old turns rather than truncating mid-turn, so memory always stays structurally valid for smolagents to replay.
The agent's system prompt lives separately in `agent.memory.system_prompt` and is never touched by this. """ steps = agent.memory.steps task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)] if len(task_indices) > max_turns: cutoff = task_indices[-max_turns] agent.memory.steps = steps[cutoff:]
# ──────────────────────────────────────────────────────────────────# Token-budget-aware rolling compaction (approaches #3 + #4)# ──────────────────────────────────────────────────────────────────# How much of the context window the memory may use before compaction# fires, before the generation reserve is subtracted. Conservative by# design: the upcoming answer shares the window with whatever memory we# keep, and llama-server's native KV-cache shift remains the final safety# net on the server backend.COMPACTION_BUDGET_RATIO = 0.75
# Target size of the LLM-written rolling summary per compaction.COMPACTION_MAX_SUMMARY_TOKENS = 512
# Longest single step fed to the summarizer (action steps carry full# tool observations — a pasted webpage or a large DataFrame print must# not flood the summary call)._COMPACTION_STEP_TEXT_LIMIT = 2000
# Hard cap on the stored ROLLING summary (chars) — a very long# conversation must never let the summary itself re-fill the window# (which would otherwise trigger a compaction loop where the summary is# the bulk of the prompt). ~1500 tokens at the 4-chars/token heuristic._COMPACTION_ROLLING_SUMMARY_MAX_CHARS = 6000
def estimate_text_tokens(text, tokenizer=None) -> int: """Approximate token count of `text` for context-window budgeting.
Uses a real tokenizer when one is available (llama-cpp-python's `Llama.tokenize`, or a transformers tokenizer), falling back to a documented ~4-characters-per-token heuristic for every other backend (llama-server HTTP, HF Inference API, LiteLLM). Always wrapped in try/except so a tokenizer quirk can never break the chat loop — the heuristic is an estimate, and the compaction threshold has slack.""" if not text: return 0 if tokenizer is not None: try: return max(1, len(tokenizer(str(text)))) except Exception: pass return max(1, int(len(str(text)) / 4))
def _get_model_tokenizer(llm): """Best-effort tokenizer callable for a smolagents Model object, or None when none is cheaply accessible (callers fall back to the char heuristic). Version-robust: every attribute is read defensively.""" if llm is None: return None # In-process llama.cpp backend: LlamaCppModel wraps llama_cpp.Llama # as `.llm`, whose `.tokenize(text)` returns the token id list — the # most accurate count this app can get, since it is the exact same # tokenizer the KV-cache is sized against. inner = getattr(llm, "llm", None) if inner is not None and callable(getattr(inner, "tokenize", None)): return inner.tokenize # smolagents TransformersModel exposes `.tokenizer` in most versions. tok = getattr(llm, "tokenizer", None) if tok is not None: if callable(getattr(tok, "encode", None)): return lambda t: tok.encode(t, add_special_tokens=False) if callable(getattr(tok, "tokenize", None)): return tok.tokenize return None
def _effective_n_ctx(llm, fallback_n_ctx: int) -> int: """Refine the context-window budget from the live model when possible. In-process llama.cpp reports its actual KV-cache size via `n_ctx()`; HF checkpoints report their trained context length via `config.max_position_embeddings`. Falls back to the value the caller passed (models._llm_n_ctx, or the persisted context-window setting).""" if llm is None: return fallback_n_ctx inner = getattr(llm, "llm", None) if inner is not None and callable(getattr(inner, "n_ctx", None)): try: return int(inner.n_ctx()) except Exception: pass config = getattr(getattr(llm, "model", None), "config", None) mpe = getattr(config, "max_position_embeddings", None) if mpe: try: return int(mpe) except Exception: pass return fallback_n_ctx
def _step_to_text(step, limit: int = _COMPACTION_STEP_TEXT_LIMIT) -> str: """Version-robust plain-text rendition of one smolagents memory step (TaskStep / ActionStep / PlanningStep / ...). Prefers the step's own `to_string()`; falls back to repr. Truncated so a single huge observation (full webpage text, DataFrame print) can't flood the summarizer.""" try: text = step.to_string() except Exception: try: text = str(step) except Exception: return "" text = str(text or "").strip() if not text: return "" if limit is not None and len(text) > limit: text = text[:limit] + "\n…(truncated)" return text
def _memory_to_text(agent, *, truncate: bool = True) -> str: """Flatten the agent's whole memory (system prompt + every step) into one text blob, for token estimation / summarization input.
With `truncate=True` (the summarizer input) each step is capped so a single huge observation can't flood the summary call. With `truncate=False` (the token-budget estimate) the FULL step text is counted — the estimate must match what llama.cpp actually builds into the prompt, or a window overflow could slip past the budget check.""" parts = [] sp = getattr(agent.memory, "system_prompt", None) if sp is not None: parts.append(_step_to_text(sp, limit=4000 if truncate else None)) for step in list(getattr(agent.memory, "steps", []) or []): parts.append(_step_to_text(step, limit=_COMPACTION_STEP_TEXT_LIMIT if truncate else None)) return "\n\n".join(p for p in parts if p)
def _system_prompt_text(mem) -> str: """Read the agent memory's system prompt as a plain string — handles SystemPromptStep objects AND bare-string system prompts.""" sp = getattr(mem, "system_prompt", None) if sp is None: return "" if isinstance(sp, str): return sp content = getattr(sp, "content", None) if isinstance(content, str): return content try: return str(sp.to_string()) except Exception: return str(sp)
def _set_system_prompt_text(mem, text: str) -> None: """Replace the agent memory's system prompt in place. Version-robust: SystemPromptStep exposes a `.content` string in current smolagents; fall back to reassigning the slot for any older shape.""" sp = getattr(mem, "system_prompt", None) if sp is None: return if isinstance(sp, str): mem.system_prompt = text return if hasattr(sp, "content"): try: sp.content = text return except Exception: pass try: mem.system_prompt = text except Exception: pass
def _inject_rolling_summary(agent, rolling: str) -> None: """Append the rolling conversation summary to the agent's system prompt, so it is included in every future run's prompt (smolagents always renders memory.system_prompt at the top of the next prompt).
The ORIGINAL system prompt is captured on the agent object the first time, so reset_memory() can restore it (smolagents' memory.reset() clears `steps` but deliberately leaves `system_prompt` untouched).""" base = getattr(agent, "_base_system_prompt", None) if base is None: base = _system_prompt_text(agent.memory) agent._base_system_prompt = base block = ( "\n\n---\n" "ROLLING CONVERSATION SUMMARY (the older turns of this conversation " "were compacted; treat the condensed history below as fact):\n" f"{rolling}" ) _set_system_prompt_text(agent.memory, base + block)
_SUMMARY_SYSTEM = ( "You are the memory compactor of a local AI assistant. You will be " "given the OLDER turns of a conversation. Produce ONE compact rolling " "summary that preserves, in order of importance: " "(1) key facts, numbers and results, " "(2) the user's preferences, instructions and decisions, " "(3) any open questions or unfinished tasks. " "Be dense and factual — no pleasantries, no repetition, no markdown " "headers. Write in the same language as the conversation. " "Keep it under {max_tokens} tokens.")
def _strip_old_observations(agent, keep_recent_turns: int = 1) -> bool: """Strip or truncate heavy tool observations from older ActionSteps before dropping entire turns, preserving tool call reasoning while reclaiming token budget.""" changed = False try: steps = list(getattr(agent.memory, "steps", []) or []) task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)] if len(task_indices) <= keep_recent_turns: return False cutoff = task_indices[-keep_recent_turns] for step in steps[:cutoff]: if hasattr(step, "observations") and step.observations: obs = str(step.observations) if len(obs) > 200: step.observations = obs[:200] + "… (observation summarized/truncated)" changed = True except Exception: pass return changed
def _trim_memory_to_budget(agent, budget: int, tokenizer=None) -> bool: """Degraded fallback for compact_agent_memory(): when the LLM summary call fails — or when memory is already over budget before there are enough turns to summarize (a single heavy turn, e.g. a Deep Research turn whose sub-agent report lives in the manager's memory, can overflow the window on turn 2) — first strip heavy observations from older turns, then drop the OLDEST turns (never the newest) until the estimated memory size fits under `budget`, keeping at least one user turn's task + final answer. Returns True if anything was changed.""" changed = False try: # Step 1: try stripping bulky observations from older turns first if _strip_old_observations(agent): changed = True if estimate_text_tokens(_memory_to_text(agent, truncate=False), tokenizer) <= budget: return True
# Step 2: drop oldest turns as needed while True: steps = list(getattr(agent.memory, "steps", []) or []) task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)] if not steps: break if estimate_text_tokens(_memory_to_text(agent, truncate=False), tokenizer) <= budget: break if len(task_indices) >= 2: # Two or more turns — drop the oldest whole turn(s), # leaving the newest turn verbatim. agent.memory.steps = steps[task_indices[1]:] changed = True continue # Exactly one turn (a single heavy turn overflowed the window) # — keep the task and the final-answer step, dropping the # bloated middle (sub-agent reports / large tool observations) # which are the usual token hogs. if task_indices and len(steps) > 2: agent.memory.steps = [steps[task_indices[0]]] + steps[-1:] changed = True continue break # task-only memory still over budget — nothing left to drop except Exception: pass return changed
def guard_memory_within_run(agent, llm=None, n_ctx=None, budget_ratio: float = COMPACTION_BUDGET_RATIO) -> bool: """Intra-run memory guard — the missing twin of compact_agent_memory().
compact_agent_memory() only runs BETWEEN turns (before agent.run()), so a single long agentic run — a Deep Research manager that collects twelve web-search observations in ONE turn — could grow its memory far past the model's context window mid-run and die with llama-server's HTTP 400 exceed_context_size_error (observed: 62723 prompt tokens vs a 32768-token window at step ~12).
This guard is called by stream_agent_steps() after EVERY completed step: when the estimated full-memory token cost crosses `n_ctx * budget_ratio`, _trim_memory_to_budget() strips heavy older observations / drops the bloated middle so the NEXT step's prompt fits. Only fires for LOCAL-backed models whose window this app can measure (is_local_backed_model) — remote backends are left untouched. Returns True when memory was trimmed.""" try: if llm is None: llm = (getattr(agent, "llm", None) or getattr(agent, "model", None)) if not is_local_backed_model(llm): return False if n_ctx is None: try: from backend.model_registry import get_saved_context_window n_ctx = get_saved_context_window() except Exception: return False try: n_ctx = int(n_ctx) except Exception: return False if n_ctx <= 0: return False budget = int(n_ctx * budget_ratio) est = estimate_text_tokens(_memory_to_text(agent, truncate=False), _get_model_tokenizer(llm)) if est <= budget: return False print(f"[MemoryGuard] Agent memory ≈{est} tokens exceeds the " f"{budget}-token budget ({n_ctx} ctx × {budget_ratio:g}) — " f"trimming older steps …") return _trim_memory_to_budget(agent, budget, tokenizer=_get_model_tokenizer(llm)) except Exception: return False
def is_local_backed_model(llm) -> bool: """True when `llm` is backed by LOCAL weights whose context window this app can measure: an in-process llama.cpp backend (`.llm`), the external llama-server backend (a `.gguf` model_path), or an in-process transformers model (`.model`). Remote backends (HF Inference API / LiteLLM) return False — their real context is unknowable here and typically far larger than the saved GGUF-oriented context-window fallback, so trimming against a guessed budget would fire every few turns for nothing. Shared by compact_agent_memory() and the direct chat paths' token-budget memory trimming (chat.py::_recent_memory_messages).""" if llm is None: return False return (bool(getattr(llm, "llm", None)) or str(getattr(llm, "model_path", "") or "").lower().endswith(".gguf") or getattr(llm, "model", None) is not None)
def trim_messages_to_budget(messages: list, budget: int, tokenizer=None) -> list: """Keep the most recent `messages` — a list of plain {"role", "content"} dicts — whose estimated token footprint fits under `budget`, dropping whole OLD messages from the oldest end (never the newest) and always keeping at least one full exchange (two messages) when available. Same token-estimation machinery as compact_agent_memory(); used by the direct (non-agentic) chat paths' short-term memory so it is bounded by the context window instead of a fixed turn count. Returns `messages` unchanged when the budget is non-positive or an estimate hiccups.""" if budget <= 0 or not messages: return messages try: costs = [estimate_text_tokens(str(m.get("content", "") or ""), tokenizer) for m in messages] if sum(costs) <= budget: return messages n = len(messages) min_keep = min(n, 2) # never trim below one full user+assistant exchange acc = sum(costs[n - min_keep:]) best_start = n - min_keep for i in range(n - min_keep - 1, -1, -1): acc += costs[i] if acc <= budget: best_start = i else: break return messages[best_start:] except Exception: return messages
def compact_agent_memory(agent, model_id: str, n_ctx: int, keep_recent_turns: int = 2, budget_ratio: float = COMPACTION_BUDGET_RATIO, max_summary_tokens: int = COMPACTION_MAX_SUMMARY_TOKENS, lang_key: str = "kh") -> bool: """Token-budget-aware rolling compaction for an agentic CodeAgent — the meaningful upgrade over the plain turn-based cap.
When the agent's memory would push the next prompt past the context window, the model condenses the OLDER turns into a short rolling summary that is prepended to the system prompt, while the most recent `keep_recent_turns` turns stay verbatim — preserving content the fixed turn-cap throws away, at the cost of one extra generation every time the window fills. Runs BEFORE the next agent.run() so the cost is only paid when a new message actually arrives.
Returns True if memory was changed (summarized, or token-trimmed as a degraded fallback), so callers can surface a one-line status. Never raises: any failure degrades to dropping the oldest turns, and the existing post-run cap_agent_memory() call sites remain in place as the structural safety net. Returns False with zero changes when the "🧹 Memory Compaction" toggle (Settings) is off, when memory is still comfortably within budget, or when there aren't enough turns yet to make summarizing worthwhile AND memory is under budget (a single heavy turn that is already over budget — e.g. Deep Research, whose sub-agent report lives in the manager's memory — degrades to the token-budget trim instead, so the next run can't overflow). """ from backend import model_registry as mr from backend import models
if not mr.get_saved_memory_compaction_enabled(): return False
budget = 0 tokenizer = None try: steps = list(getattr(agent.memory, "steps", []) or []) task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)]
# Remote backends (HF Inference API / LiteLLM) have no in-process # tokenizer or model config, so their real context is unknowable # here — and it is typically far larger than the saved context- # window fallback (which is GGUF-oriented). Compacting those would # fire every few turns and burn unnecessary remote API calls for # nothing, so skip them; the fixed turn-caps still bound their # memory. model_obj = getattr(agent, "model", None) if not is_local_backed_model(model_obj): return False
n_ctx = _effective_n_ctx(model_obj, n_ctx) # Generation reserve: the upcoming answer shares the window with # whatever memory we keep, so the budget must leave room for it. budget = int(n_ctx * budget_ratio) - mr.get_saved_max_new_tokens() if budget <= 0: return False
tokenizer = _get_model_tokenizer(getattr(agent, "model", None)) if estimate_text_tokens(_memory_to_text(agent, truncate=False), tokenizer) <= budget: return False
# Too few turns to make summarizing worthwhile — BUT memory is # already over budget (a single heavy turn can overflow the # window, e.g. Deep Research, whose sub-agent report lives in the # manager's memory — the "Requested tokens (N) exceed context # window" failure on turn 2). Degrade to the token-budget trim so # the next run never crashes with a context overflow. if len(task_indices) <= keep_recent_turns + 1: return _trim_memory_to_budget(agent, budget, tokenizer)
# Everything before the last `keep_recent_turns` user turns is # compacted; those recent turns stay verbatim. cutoff_idx = task_indices[-keep_recent_turns] old_text = "\n\n".join( _step_to_text(s) for s in steps[:cutoff_idx] ).strip() if not old_text: return False
lang_note = "ខ្មែរ (Khmer)" if lang_key == "kh" else "English" # Cap the summary generation itself: the compaction call must NOT # inherit the model's full MAX_NEW_TOKENS budget — a slow local # model would stall behind the "Compacting…" status for minutes, # and a rambling model would permanently bloat the prompt. Passed # through _call_llm's optional max_tokens kwarg, which falls back # gracefully if a backend's Model wrapper rejects it. summary, _, _n_tok = models._call_llm( model_id, _SUMMARY_SYSTEM.format(max_tokens=max_summary_tokens) + f"\nLanguage: {lang_note}.", old_text, max_tokens=max_summary_tokens, ) summary = (summary or "").strip() if not summary or summary.startswith("❌"): # Summarizer failed (network, template, budget…) — degrade to # token-aware trimming of the oldest turns rather than the # full compaction. return _trim_memory_to_budget(agent, budget, tokenizer) # Defensive truncation: even a capped generation can exceed the # requested size — never let a single summary bloat the prompt. max_chars = max(512, max_summary_tokens * 4) if len(summary) > max_chars: summary = summary[:max_chars].rstrip() + "…"
prev = getattr(agent, "_rolling_summary", "") or "" rolling = (prev + "\n\n" + summary).strip() if prev else summary if len(rolling) > _COMPACTION_ROLLING_SUMMARY_MAX_CHARS: # Keep the NEWEST summary content and drop the oldest chunk, # so a long conversation can't let the summary itself re-fill # the window (which would trigger a compaction loop). rolling = "…" + rolling[-_COMPACTION_ROLLING_SUMMARY_MAX_CHARS:].lstrip("\n") _inject_rolling_summary(agent, rolling) agent.memory.steps = steps[cutoff_idx:] agent._rolling_summary = rolling # Counter surfaced in the chat response footer ("compacted N×") so # users can see when the rolling summary is being used. Reset # together with the rest of memory in reset_memory(). agent._compaction_count = (getattr(agent, "_compaction_count", 0) or 0) + 1 print(f"[memory] Compaction: {len(task_indices)} turns -> rolling " f"summary + {len(steps[cutoff_idx:])} steps kept verbatim.") return True except Exception: import traceback traceback.print_exc() if budget > 0: try: return _trim_memory_to_budget(agent, budget, tokenizer) except Exception: pass return False
def reset_memory(agent) -> None: """Wipe an agent's own conversation memory in place, WITHOUT rebuilding the agent object itself.
Calls smolagents' own `agent.memory.reset()` — see smolagents/memory.py: `AgentMemory.reset()` sets `self.steps = []` and explicitly leaves `self.system_prompt` (a separate `SystemPromptStep`, not part of `steps`) untouched. Using the library's own method here rather than reassigning `agent.memory.steps = []` by hand keeps this in step with whatever AgentMemory.reset() does internally in a future smolagents version, instead of this file quietly re-implementing (and potentially drifting from) that logic.
Also restores the ORIGINAL system prompt, drops any rolling compaction summary the agent carries, and zeroes the compaction counter (see compact_agent_memory()): a reset must never replay compacted history from the previous conversation, so the compacted system-prompt overlay is undone here.
Used whenever something other than an explicit model switch should invalidate memory — e.g. Data Analysis's "a new dataset was uploaded" check (see reset_if_context_changed() below). Clearing memory in place like this — rather than tearing down and rebuilding the whole CodeAgent, as an earlier version of this file did — is both cheaper (no tool re-initialization) and avoids the stale-memory-reload bug described in this module's docstring. """ agent.memory.reset() if hasattr(agent, "_base_system_prompt"): _set_system_prompt_text(agent.memory, agent._base_system_prompt) if hasattr(agent, "_rolling_summary"): agent._rolling_summary = None if hasattr(agent, "_compaction_count"): agent._compaction_count = 0
def reset_if_context_changed(agent, state: dict, new_key) -> bool: """Helper for tabs where a NEW context (e.g. a newly uploaded dataset) should invalidate old agent memory even though the underlying model/agent object hasn't changed — otherwise the agent would keep "remembering" a previous file's columns/stats while analyzing a different one.
`state` is a small mutable dict (e.g. module-level `{"key": None}`) used to remember the last context key seen. Returns True if a reset was triggered. """ if state.get("key") != new_key: reset_memory(agent) state["key"] = new_key return True return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807"""
deep_research_agent.py — Agentic "Deep Research" via a two-agent smolagents
setup, modeled on HuggingFace's own open_deep_research example:
https://github.com/huggingface/smolagents/tree/main/examples/open_deep_research
That example uses a MANAGER agent that plans out a research task and
delegates focused sub-questions to a dedicated browser/search agent
(there: a `ToolCallingAgent` wrapping `GoogleSearchTool` + page-reading
tools, requiring a paid search API key and typically a hosted model like
`o1`). This app has neither a search API key nor a hosted-model
requirement, so the same manager+search-agent shape is rebuilt here using
what's already available:
- The manager is a `ToolCallingAgent` (or CodeAgent fallback on models
without structured tool calling) with NO tools of its own except the
search sub-agent (passed via `managed_agents=`, which smolagents
exposes to the manager as a callable — `web_search_agent(task="...")`
— same as the real example's manager calling its own sub-agent). Tool
calling avoids CodeAgent code-parsing failures on research text.
- `planning_interval` makes the manager periodically stop and
re-evaluate its plan against what it's learned so far — the
characteristic "deep" part of deep research, as opposed to
general_agent.py's single-pass agentic chat.
- The search sub-agent reuses general_agent.py's own
TrackedDuckDuckGoSearchTool / TrackedVisitWebpageTool (free,
API-key-free DuckDuckGo search + page reading — already proven out
by General Chat's agentic mode) instead of GoogleSearchTool, and its
citation-tracking/verification helpers (resolve_actually_used_sources
etc.) are reused as-is from general_agent.py rather than duplicated.
Same reliability caveat as every other agentic tab in this app: this
needs a genuinely capable model to work well — small/local models can
struggle even more here than in General Chat's agentic mode, since a
manager also has to correctly invoke a SUB-AGENT (not just a tool) and
periodically re-plan. Expect this to work best on Gemma-4-E4B and above,
same guidance as the other agentic tabs.
"""
import threading
import types
from typing import Optional
from smolagents import Tool, ToolCallingAgent, WikipediaSearchTool, UserInputTool
from agents import agent_streaming
from agents import general_agent
from agents.agent_factory import build_smol_agent, init_params
from backend import model_registry as mr
from backend import models
from ui import i18n
try:
from agents import playwright_search_tool
_playwright_available = True
except ImportError:
_playwright_available = False
# smolagents' WikipediaSearchTool lazily imports `wikipediaapi` in its
# __init__ and raises ImportError when the package is missing. Whether it
# is actually usable is probed once here (same pattern as
# `_playwright_available` above) so the search agent can simply skip the
# tool instead of crashing the whole Deep Research tab on machines that
# don't have the optional package — see AGENTS.md's "the app must always
# launch" rule.
_wikipedia_tool_available = True
try:
import wikipediaapi # noqa: F401
except ImportError:
_wikipedia_tool_available = False
if _playwright_available:
class TrackedPlaywrightDuckDuckGoSearchTool(playwright_search_tool.PlaywrightDuckDuckGoSearchTool):
input_aliases = {
"query": ("q", "question", "search", "search_query", "keywords", "task", "text", "prompt"),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queries_run = []
self.result_links = []
def forward(self, query: str) -> str:
self.queries_run.append(query)
result = super().forward(query)
import re
_MARKDOWN_LINK_RE = re.compile(r'\[([^\]]+)\]\((https?://[^\s\)]+)\)')
for title, url in _MARKDOWN_LINK_RE.findall(result or ""):
pair = (title.strip(), url.strip())
if pair not in self.result_links:
self.result_links.append(pair)
return result
class TrackedPlaywrightGoogleSearchTool(playwright_search_tool.PlaywrightGoogleSearchTool):
input_aliases = {
"query": ("q", "question", "search", "search_query", "keywords", "task", "text", "prompt"),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queries_run = []
self.result_links = []
def forward(self, query: str, filter_year: str | None = None) -> str:
self.queries_run.append(query)
result = super().forward(query, filter_year)
import re
_MARKDOWN_LINK_RE = re.compile(r'\[([^\]]+)\]\((https?://[^\s\)]+)\)')
for title, url in _MARKDOWN_LINK_RE.findall(result or ""):
pair = (title.strip(), url.strip())
if pair not in self.result_links:
self.result_links.append(pair)
return result
class TrackedPlaywrightVisitPageTool(playwright_search_tool.PlaywrightVisitPageTool):
input_aliases = {
"url": ("link", "webpage", "page", "address", "site", "target"),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.urls_visited = []
def forward(self, url: str) -> str:
self.urls_visited.append(url)
return super().forward(url)
class PlaywrightTextInspectorTool(Tool):
name = "playwright_inspect_file"
description = (
"Read a file from a local path or URL and return its text content. "
"Handles .txt, .md, .html, .json, .csv, .py, and similar text formats. "
"For PDF files use playwright_read_embedded_pdf instead. "
"For images use playwright_visualizer instead."
)
inputs = {
"file_path": {
"type": "string",
"description": "The local path or URL to the file to read.",
},
}
input_aliases = {
"file_path": ("filepath", "file", "path", "filename", "doc", "document", "src", "source"),
}
output_type = "string"
def forward(self, file_path: str) -> str:
import mimetypes
import requests
file_path = file_path.strip()
if not file_path:
return "Error: empty file path."
try:
if file_path.startswith("http://") or file_path.startswith("https://"):
resp = requests.get(file_path, timeout=30)
resp.raise_for_status()
content = resp.text
else:
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
except Exception as e:
return f"Error reading file '{file_path}': {e}"
if len(content) > 50000:
content = content[:50000] + "\n...[truncated at 50000 chars]"
return f"## File: {file_path}\n\n```\n{content}\n```"
class PlaywrightVisualizerTool(Tool):
name = "playwright_visualizer"
description = (
"Answer a question about an image file. Provide the local path to the image "
"and an optional question. If no question is given, a detailed caption is returned."
)
inputs = {
"image_path": {
"type": "string",
"description": "The local path to the image file to analyze.",
},
"question": {
"type": "string",
"description": "The question about the image. Optional — if omitted, a caption is generated.",
"nullable": True,
},
}
input_aliases = {
"image_path": ("image", "file_path", "filepath", "path", "img", "photo", "pic"),
"question": ("prompt", "query", "task", "text", "q"),
}
output_type = "string"
def __init__(self, model_id: str = "", provider=None, n_ctx=None, **kwargs):
super().__init__(**kwargs)
# Same-model rule (see model_registry.is_multimodal_model): the
# image analysis runs on the ACTIVE Deep Research model — the one
# already loaded for this run — so no SECOND VLM is pulled into
# VRAM (a GGUF VLM rides the same llama-server, a transformers VLM
# reuses the loaded LLM via vlm_answer's reuse branch). When that
# model is TEXT-ONLY, a clean note is returned instead of loading
# the saved Vision-tab VLM. Empty model_id (defensive fallback)
# keeps the historical default-VLM behavior.
self._model_id = str(model_id or "")
self._provider = provider
self._n_ctx = n_ctx
def forward(self, image_path: str, question: str | None = None) -> str:
from PIL import Image
image_path = image_path.strip()
if not image_path:
return "Error: empty image path."
try:
pil_image = Image.open(image_path).convert("RGB")
except Exception as e:
return f"Error opening image '{image_path}': {e}"
q = question or "Please describe this image in detail."
if self._model_id and not mr.is_multimodal_model(self._model_id, self._provider):
# Text-only active model — do NOT load a second model just to
# look at the image; tell the agent to rely on page text.
return ("The active model is text-only and cannot analyze "
"images. Rely on the page's text content instead.")
try:
mmproj = mr.GGUF_VLM_MMPROJ_MAP.get(self._model_id) if self._model_id else None
answer = models.vlm_answer(
q, [pil_image],
model_id=self._model_id or None,
mmproj_path=mmproj,
n_ctx=self._n_ctx,
provider=self._provider,
)
except Exception as e:
answer = f"Could not process image through VLM: {e}"
if not question:
answer = f"Caption for '{image_path}':\n{answer}"
return answer
_manager_agent = None
_manager_agent_model_id = None
_manager_agent_config = {}
_manager_agent_n_ctx = None
_manager_agent_lock = threading.Lock()
# Module-level refs to the CURRENT run's tracked-tool instances (the
# search sub-agent's own tools), so chat.py can read/reset them the same
# way it does for general_agent.py's tools — see
# general_agent.TrackedDuckDuckGoSearchTool / TrackedVisitWebpageTool.
_search_tool = None
_webpage_tool = None
# The search sub-agent answers ONE focused sub-question per call and has
# no memory of its own across calls, so it needs far fewer steps than the
# manager, which is juggling the whole research task. The manager's
# budget is larger than general_agent.py's single-agent default (12 vs
# 8) since planning + delegation calls both cost steps on top of the
# actual research.
SEARCH_AGENT_DEFAULT_MAX_STEPS = 4
MANAGER_DEFAULT_MAX_STEPS = 12
# How often (in manager steps) the manager stops to re-plan — smolagents'
# own `planning_interval` mechanism. This is the main thing that makes
# this agent "deep" rather than a single-pass agentic chat: every few
# steps it re-reads what it has found so far and can revise its approach
# instead of blindly executing an initial plan to the end.
DEEP_RESEARCH_PLANNING_INTERVAL = 3
SEARCH_AGENT_DESCRIPTION = (
"Give this agent ONE focused sub-question (a plain-text string) and "
"it will search the web and read pages to answer just that "
"sub-question, returning what it found as plain text. It has NO "
"memory of any other call you make to it, so every call must be "
"fully self-contained — include whatever context it needs in the "
"sub-question itself. Call it once per sub-question; don't ask it "
"multiple unrelated things in one call.\n\n"
"Call it by passing the sub-question as the `task` argument — "
"web_search_agent(task=\"your question here\") — and it will run the "
"search itself."
)
DEEP_RESEARCH_INSTRUCTIONS = (
"You are a deep-research assistant. You have NO web-search tool of "
"your own — the ONLY way to get outside information is to delegate a "
"focused sub-question to the `web_search_agent` tool, e.g.\n"
"web_search_agent(task=\"<one focused sub-question>\")\n\n"
"THE ONLY AGENT THAT EXISTS is `web_search_agent`. There is no other "
"tool or function available — in particular there is no "
"`web_search`, `visit_webpage`, `conversation_history`, or `memory` "
"function. Never call, import, or reference anything else; it will "
"fail with an error and waste a step.\n\n"
"YOUR OWN CONVERSATION HISTORY IS ALREADY VISIBLE TO YOU: earlier "
"turns in this conversation (including your own past reports) are "
"already included in what you can see. If a follow-up refers back to "
"your last report, reuse what you already found instead of "
"re-researching it from scratch — only delegate NEW sub-questions for "
"genuinely new information.\n\n"
"Work like this:\n"
"1. Break the question down into 2-5 focused sub-questions that, "
"together, cover what's needed to answer it well.\n"
"2. Call `web_search_agent` ONCE PER SUB-QUESTION, passing exactly "
"one focused sub-question as its `task` argument — and do nothing "
"else in that step. Never invent or assume a fact yourself — every "
"factual claim in your final answer must trace back to a "
"`web_search_agent` call from this run.\n"
"3. Re-check your plan periodically against what you've actually "
"found: if it changes what you still need to look up, adjust instead "
"of blindly finishing the original plan.\n"
"4. Once you have enough to answer well, STOP calling "
"`web_search_agent` and submit your final answer by calling the "
"special `final_answer(...)` tool — this is the ONLY way to "
"actually end the task. Simply printing or writing the report as "
"plain text does NOT end the run: if you don't call `final_answer`, "
"you will be given another step and will end up starting new "
"research rounds even though you already had a complete answer. "
"Pass the FULL Markdown report as the argument to final_answer:\n"
"final_answer(report_text)\n"
"where `report_text` is a well-structured Markdown report: a short "
"introduction, clearly-headed sections covering each theme/sub-"
"question, and a brief conclusion.\n"
"CRITICAL: Each step MUST make exactly ONE tool call — either one "
"call to `web_search_agent` (with nothing else), or once you're done "
"researching, exactly one call to `final_answer(report_text)`. Do NOT "
"write plain text between tool calls during research steps. Do NOT "
"forget to call final_answer(...) once you have enough information — "
"forgetting this is the single most common mistake and it causes "
"unnecessary extra research rounds.\n\n"
"The user's actual question is in the Task below — answer THAT, not "
"these instructions. Never repeat, summarize, or reply to the "
"instructions themselves."
)
def build_task_with_citation_reminder(user_message: str, lang_key: str = "kh") -> str:
"""Wrap the user's question with an explicit, PER-TASK reminder of the
citation requirement AND the final_answer(...) termination
requirement — mirrors general_agent.build_task_with_citation_reminder()
and rag_agent.build_strict_task()'s belt-and-braces pattern exactly.
DEEP_RESEARCH_INSTRUCTIONS (including its citation requirement AND its
"you must call final_answer(...) to actually stop" requirement) is
only ever attached to the manager agent if this installed smolagents
version's chosen agent class (CodeAgent or ToolCallingAgent)
happens to expose an `instructions=`
parameter — see the `if "instructions" in params:` guard in
agents/agent_factory.py's build_smol_agent(). On a version where it
doesn't, the manager never sees either requirement at all — it
never writes a '### References' section for
general_agent.resolve_actually_used_sources() to parse in chat.py's
chat_deep_research(), AND (the more disruptive gap) it never learns
that it must call the special `final_answer(...)` tool to end the
run — writing the report as plain printed text does NOT terminate a
smolagents CodeAgent, so without this reminder the manager can
finish a perfectly good report and then just keep going, re-planning
and starting new research rounds it didn't need. Repeating both
requirements here — in the per-call task text, which always reaches
the manager regardless of smolagents version — closes that gap.
"""
# The task text IS the user turn the manager model sees, so the
# question must be the LAST line — a small GGUF model anchors on
# whatever comes right before its own turn (same reasoning as
# general_agent.build_task_with_citation_reminder).
return (
i18n._output_lang_instruction(lang_key)
+ "Answer the user's question below — it is the LAST line of this "
"Task. Do not repeat, summarize, or reply to these instructions; "
"answer only the question.\n\n"
"---\n"
"Reminder: every factual claim in your final report that came "
"from a web_search_agent call must be cited in-text with a "
"bracketed number (e.g. [1]) placed right after the claim, and "
"your final report must end with a '### References' section "
"listing each numbered source's title and URL, e.g.:\n"
"### References\n"
"[1] Page Title — https://example.com/page\n\n"
"IMPORTANT: inside the in-text brackets write ONLY the number — "
"NEVER the source URL or page title (e.g. write [1], not "
"[https://example.com/page] and not [Page Title]); URLs and page "
"titles are listed only in the References section.\n\n"
"Reminder: once your report is ready, you MUST submit it by "
"calling the final_answer(report_text) tool — this is the ONLY "
"way to end the task. Just printing or writing the report as "
"plain text does NOT stop the run; without calling "
"final_answer(...), you will be given another step and may end "
"up starting unnecessary new research rounds even though your "
"report was already complete.\n\n"
"If the system rejects your final answer for formatting, missing "
"citations, or a missing References section, do NOT start any new "
"research and do NOT call web_search_agent again. Keep the same "
"findings, rewrite only the final report so it satisfies the "
"checker, and call final_answer(report_text) again.\n\n"
+ i18n._task_conciseness_directive(lang_key)
+ "\n\n---\n"
"The user's question is:\n"
f"{user_message}"
)
# ──────────────────────────────────────────────────────────────────
# Strict grounding — layer 4: a `final_answer_checks` validator on the
# MANAGER agent. See the file's revision notes: smolagents' CodeAgent
# accepts `final_answer_checks: list[Callable]`, each run against
# whatever the model passes to `final_answer(...)` before the run is
# allowed to end. Raising an exception from a check feeds that message
# back to the model as the reason its answer was rejected, and it gets
# another step to fix it — rather than a bad/incomplete report silently
# becoming the final result.
#
# Deliberately does NOT validate citation *accuracy* (e.g. "does every
# [n] have a matching reference line") — that's handled, more leniently
# and more reliably, by general_agent.resolve_actually_used_sources()
# AFTER the run completes. It also does NOT require the report to end
# with a '### References' section of its own: chat.py's
# chat_deep_research() strips the model's section and appends a VERIFIED
# references block built from the URLs the search sub-agent really
# visited/returned this run, so demanding one from the model only burns
# steps on small models that write a complete report but forget the
# trailing section — the same reasoning that dropped the requirement
# from rag_agent._validate_final_report (see its comment there). One
# cheap, high-value check remains:
# 1. The report isn't empty/near-empty.
# ──────────────────────────────────────────────────────────────────
MIN_FINAL_REPORT_CHARS = 200
def _validate_final_report(final_answer, *_, **__) -> bool:
"""`final_answer_checks` validator for the Deep Research manager.
Raises a plain Exception with an actionable message on rejection —
smolagents surfaces that message back to the model as feedback for
its next step. Only rejects a report too short to be a real grounded
report; the model-written '### References' section is NOT required
because chat.py appends a verified references block from the run's
actually-used sources after the run completes (see the layer-4
comment above).
"""
text = str(final_answer or "").strip()
if len(text) < MIN_FINAL_REPORT_CHARS:
raise ValueError(
f"Your final answer is only {len(text)} character(s) — too "
f"short to be a real research report (need at least "
f"{MIN_FINAL_REPORT_CHARS}). Write a complete Markdown report "
"(a short introduction, a clearly-headed section per "
"sub-question you researched, and a brief conclusion), then "
"call final_answer(report_text) again with the FULL report "
"text as the argument."
)
return True
# The max-steps hand-off transcript cap for the search sub-agent — its
# findings are verbatim search results / page contents (wordier than the
# Data worker's compact tables), so it gets a larger cap than the
# worker's 8000.
_SEARCH_OBS_TRANSCRIPT_CAP = 12000
def _search_agent_max_steps_handoff(self, task):
"""The `web_search_agent`'s max-steps fallback (instance-patched onto
the agent in `_build_search_agent`): prefer the run's REAL gathered
sources — the verbatim tool observations (search results, page
contents) — over smolagents' stock last-ditch raw-text answer, so the
manager receives what the agent actually found instead of a leaked
channel marker / envelope. Thin wrapper over the shared
agent_streaming.max_steps_findings_handoff (same helper the Data
`data_worker` uses). NEVER raises."""
return agent_streaming.max_steps_findings_handoff(
self, task, cap=_SEARCH_OBS_TRANSCRIPT_CAP)
def _build_search_agent(llm, model_id: str = "", use_playwright: bool = False, headless: bool = True, max_steps: Optional[int] = None, timeout: Optional[int] = None, provider=None, n_ctx=None):
global _search_tool, _webpage_tool
tools = []
if use_playwright and _playwright_available:
_search_tool = TrackedPlaywrightDuckDuckGoSearchTool(headless=headless)
_webpage_tool = TrackedPlaywrightVisitPageTool(headless=headless)
tools = [
_search_tool,
TrackedPlaywrightGoogleSearchTool(headless=headless),
_webpage_tool,
playwright_search_tool.PlaywrightExtractLegalDocumentLinksTool(headless=headless),
playwright_search_tool.PlaywrightReadEmbeddedPdfTool(),
playwright_search_tool.PlaywrightPageDownTool(),
playwright_search_tool.PlaywrightPageUpTool(),
playwright_search_tool.PlaywrightFindOnPageTool(),
playwright_search_tool.PlaywrightFindNextTool(),
playwright_search_tool.PlaywrightArchiveSearchTool(),
# App-local transcriber (NOT smolagents' stock SpeechToTextTool —
# that one eagerly imports transformers/torch in its constructor
# and crashes agent builds on machines without torch, e.g. the
# Store/MSIX build). Same name/schema, torch-free, routes through
# the app's own configured STT pipeline.
general_agent.SpeechToTextTool(),
UserInputTool(),
PlaywrightTextInspectorTool(),
PlaywrightVisualizerTool(model_id=model_id, provider=provider, n_ctx=n_ctx),
]
if _wikipedia_tool_available:
tools.append(WikipediaSearchTool())
desc = (
"Give this agent ONE focused sub-question (a plain-text string) and "
"it will search the web using Playwright headless browser tools and read pages to answer just that "
"sub-question, returning what it found as plain text. It has NO "
"memory of any other call you make to it, so every call must be "
"fully self-contained — include whatever context it needs in the "
"sub-question itself. Call it once per sub-question; don't ask it "
"multiple unrelated things in one call."
)
else:
_search_tool = general_agent.TrackedDuckDuckGoSearchTool()
_webpage_tool = general_agent.TrackedVisitWebpageTool()
tools = [_search_tool, _webpage_tool]
desc = SEARCH_AGENT_DESCRIPTION
final_max_steps = max_steps if max_steps is not None else mr.get_max_steps_for_model(model_id, SEARCH_AGENT_DEFAULT_MAX_STEPS)
kwargs = dict(
model=llm,
tools=tools,
max_steps=final_max_steps,
verbosity_level=1,
name="web_search_agent",
description=desc,
planning_interval=4,
provide_run_summary=True,
)
params = init_params(ToolCallingAgent)
if "instructions" in params:
if use_playwright and _playwright_available:
kwargs["instructions"] = (
"You are a focused web search agent using real browser "
"(Playwright) tools — none of these tools use a paid API or "
"require an API key. Your tools are:\n\n"
"=== Search & Browse ===\n"
" - `playwright_duckduckgo_search(query=\"...\")` — your PRIMARY "
"search tool. Use this first for almost every search.\n"
" - `playwright_google_search(query=\"...\", filter_year=\"...\")` "
"— the FALLBACK search tool (queries Google via a real browser). "
"filter_year is optional. Use this only if "
"`playwright_duckduckgo_search` comes back empty, or the topic "
"needs Google's broader index.\n"
" - `playwright_visit_page(url=\"...\")` — opens a URL and returns "
"its visible text plus every link found on it (note: it is named "
"`playwright_visit_page`, NOT `visit_webpage` — that name does not "
"exist in this mode).\n"
" - `playwright_extract_legal_document_links(url=\"...\", "
"topic_keywords=\"...\")` — opens a listing/index page and returns "
"its links ranked by relevance to topic_keywords. Use this BEFORE "
"opening individual candidate pages one by one.\n"
" - `playwright_read_embedded_pdf(url=\"...\")` — opens a page, "
"finds any embedded/linked PDF, and extracts its text.\n"
" - `playwright_find_archived_url(url=\"...\", date=\"...\")` — "
"searches the Wayback Machine for an archived snapshot of a URL "
"near a given date. Use when a page is dead or has changed.\n\n"
"=== Page Navigation ===\n"
" - `playwright_page_down()` — scroll the viewport DOWN one page.\n"
" - `playwright_page_up()` — scroll the viewport UP one page.\n"
" - `playwright_find_on_page(search_string=\"...\")` — Ctrl+F "
"search on the currently visited page.\n"
" - `playwright_find_next()` — jump to the next match of the "
"last find_on_page search.\n\n"
"=== Utilities ===\n"
" - `transcriber(audio_url=\"...\")` — transcribes an audio file/URL "
"to text.\n"
+ (
" - `wikipedia_search(query=\"...\")` — search Wikipedia for a "
"given query and return a summary.\n"
if _wikipedia_tool_available
else ""
)
+ " - `ask_user(question=\"...\")` — ask the user for clarification "
"or additional input.\n"
" - `playwright_inspect_file(file_path=\"...\")` — read a local "
"or remote text file and return its contents.\n"
" - `playwright_visualizer(image_path=\"...\", question=\"...\")` "
"— answer a question about an image file.\n\n"
"There is no `web_search`, `visit_webpage`, or `web_search_agent` "
"function available to you (that last name is only how something "
"ELSE calls you from outside; it does not exist inside your own "
"code).\n\n"
"You do NOT need to write code or use fenced code blocks. Simply "
"call the tools by their name — this system understands structured "
"tool calls natively, without any Python scaffolding.\n\n"
"Work like this:\n"
"1. Search with `playwright_duckduckgo_search` first.\n"
"2. Open promising results with `playwright_visit_page` to read "
"their content.\n"
"3. If you find a PDF you need text from, use "
"`playwright_read_embedded_pdf` to extract it.\n"
"4. Once you have enough information, just respond with your "
"answer as plain text — that naturally ends the task. You can "
"also use the `final_answer` tool to explicitly finish with your "
"findings.\n\n"
"If after searching you find that you need more information to "
"answer the question, you can use `final_answer` with your "
"request for clarification as argument to request for more "
"information from the user."
)
else:
kwargs["instructions"] = (
"You are a focused web search agent. Your ONLY job is to answer "
"the sub-question you are given by searching the web and reading "
"pages. You have NO other tools besides `web_search` and "
"`visit_webpage` — there is no `web_search_agent` function "
"available to you (that name is only how something ELSE calls "
"you from outside; it does not exist inside your own code).\n\n"
"You do NOT need to write code or use fenced code blocks. Simply "
"call the tools by their name — this system understands structured "
"tool calls natively, without any Python scaffolding.\n\n"
"Work like this:\n"
"1. Search with `web_search` to find relevant pages.\n"
"2. Open promising results with `visit_webpage` to read their "
"content.\n"
"3. Once you have enough information, just respond with your "
"answer as plain text — that naturally ends the task. You can "
"also use the `final_answer` tool to explicitly finish with "
"your findings.\n\n"
"If after searching you find that you need more information to "
"answer the question, you can use `final_answer` with your "
"request for clarification as argument to request for more "
"information from the user."
)
if "executor_kwargs" in params and timeout is not None:
kwargs["executor_kwargs"] = {"timeout_seconds": timeout}
agent = ToolCallingAgent(**kwargs)
# Max-steps hand-off (see agent_streaming.max_steps_findings_handoff):
# when the search agent burns its whole step budget without emitting a
# real final answer (the Muse Glimmer DR runs shipped a bare
# `to=user<|eot|>` channel marker as its "final answer"), the manager
# would receive that garbage — losing the gathered sources. Deliver
# the run's verbatim tool observations (search results / page
# contents) instead. Same instance-level patch as the Data
# `data_worker`; the Deep Research MANAGER keeps the stock behavior.
try:
agent._orig_handle_max_steps_reached = agent._handle_max_steps_reached
agent._handle_max_steps_reached = types.MethodType(
_search_agent_max_steps_handoff, agent
)
except Exception:
pass
# Append managed-agent task prompt so the search agent knows how to
# handle .txt, .pdf, YouTube, and how to request clarification —
# mirrors the canonical open_deep_research pattern exactly:
# https://github.com/huggingface/smolagents/blob/main/examples/open_deep_research/run.py
agent.prompt_templates["managed_agent"]["task"] += (
"\nYou can navigate to .txt online files. "
"If a non-html page is in another format, especially .pdf or a Youtube "
"video, use a tool like 'inspect_file_as_text' or "
"'playwright_read_embedded_pdf' to inspect it. "
"Additionally, if after some searching you find out that you need more "
"information to answer the question, you can use `final_answer` with "
"your request for clarification as argument to request for more information."
)
return agent
def _supports_native_tool_calls(llm) -> bool:
"""Tool-calling policy for the Deep Research MANAGER.
Returns True for EVERY model — native tool calling is the app-wide
default (see agent_factory.build_smol_agent's default). Earlier
versions restricted ToolCallingAgent to LiteLLM / HF-Inference API
models that advertise function-calling; but llama-cpp-python's
ToolCallingAgent path handles small local GGUF models well (the
structured tool calls route through the app's smart
parse_json_blob/ReAct-envelope recovery in agent_streaming, and the
live Gemma-4-E2B verification ran web_search + final_answer natively
with zero code-parsing errors), so the restriction was lifted — the
checkbox on the Deep Research tab now genuinely controls the class,
and CodeAgent is only used when the user unchecks it.
"""
return True
def _build_manager_agent(llm, search_agent, model_id: str = "", max_steps: Optional[int] = None, timeout: Optional[int] = None, use_playwright: bool = False, headless: bool = True, use_tool_calling: bool = True, provider=None, n_ctx=None):
final_max_steps = max_steps if max_steps is not None else mr.get_max_steps_for_model(model_id, MANAGER_DEFAULT_MAX_STEPS)
tools = []
if use_playwright and _playwright_available:
tools = [
PlaywrightTextInspectorTool(),
PlaywrightVisualizerTool(model_id=model_id, provider=provider, n_ctx=n_ctx),
]
instructions = DEEP_RESEARCH_INSTRUCTIONS
if use_playwright and _playwright_available:
instructions = DEEP_RESEARCH_INSTRUCTIONS + (
"You also have direct access to these utility tools:\n"
" - `playwright_inspect_file(file_path=\"...\")` — read a local "
"or remote text file and return its contents. Use this to inspect "
"downloaded or referenced files without needing to delegate to the "
"web_search_agent.\n"
" - `playwright_visualizer(image_path=\"...\", question=\"...\")` — "
"answer a question about an image file. Use this when you need to "
"analyze an image the user provided or that was found during research.\n\n"
)
agent = build_smol_agent(
llm,
tools=tools,
max_steps=final_max_steps,
use_tool_calling=use_tool_calling,
tool_calling_predicate=_supports_native_tool_calls,
instructions=instructions,
execution_timeout=timeout,
extra_kwargs={
"managed_agents": [search_agent],
# Per-model override: models flagged planning-incompatible
# (Muse Glimmer — it echo-loops the re-plan prompt) get None
# (planning off), everyone else keeps the default interval.
"planning_interval": mr.planning_interval_for_model(model_id, DEEP_RESEARCH_PLANNING_INTERVAL),
},
optional_kwargs={"final_answer_checks": [_validate_final_report]},
)
print(f"[DeepResearch] Building manager {type(agent).__name__} on '{model_id or '(shared)'}' …")
return agent
def reset_tool_usage() -> None:
"""Call right before agent.run() so this run's tracked queries/URLs
start from zero — mirrors general_agent.reset_tool_usage()."""
if _search_tool is not None:
_search_tool.queries_run = []
_search_tool.result_links = []
if _webpage_tool is not None:
_webpage_tool.urls_visited = []
def get_tool_usage() -> tuple:
"""Call right after agent.run() returns. Returns (queries_run,
urls_visited, result_links) from the search sub-agent's own tools —
see general_agent.get_tool_usage() for the equivalent on that tab.
Passed to general_agent.resolve_actually_used_sources() so chat.py
can print a guaranteed-accurate References list for this report."""
queries = list(_search_tool.queries_run) if _search_tool is not None else []
urls = list(_webpage_tool.urls_visited) if _webpage_tool is not None else []
links = list(_search_tool.result_links) if _search_tool is not None else []
return queries, urls, links
def get_deep_research_agent(model_id: Optional[str] = None, use_playwright: bool = False, headless: bool = True, manager_max_steps: Optional[int] = None, search_max_steps: Optional[int] = None, execution_timeout: Optional[int] = None, use_tool_calling: bool = True, provider: Optional[str] = None, n_ctx: Optional[int] = None):
"""Lazily build (or rebuild, if the model changed) the manager agent
and its search sub-agent.
`execution_timeout` is the per-step Python code-executor timeout in
seconds (the DrControls "Exec timeout" field in agentic mode) — threaded
to both the manager and the web_search_agent sub-agent builders' own
`timeout` (their per-step executor cap). None = AUTO (the factory
default). This is DISTINCT from the tab's whole-run generation timeout,
which is enforced at the WS stream layer (web_api._run_stream) and
never reaches this builder — a wall-clock run budget must not double as
a per-step executor cap."""
global _manager_agent, _manager_agent_model_id, _manager_agent_config, _manager_agent_n_ctx
target = model_id or models._llm_model_id
current_config = {
"use_playwright": use_playwright,
"headless": headless,
"manager_max_steps": manager_max_steps,
"search_max_steps": search_max_steps,
"execution_timeout": execution_timeout,
"n_ctx": n_ctx,
}
if _manager_agent is not None and target == _manager_agent_model_id and current_config == _manager_agent_config:
return _manager_agent
with _manager_agent_lock:
if _manager_agent is not None and target == _manager_agent_model_id and current_config == _manager_agent_config:
return _manager_agent
print(f"[DeepResearch] Building manager + web_search_agent on '{target}' (Playwright: {use_playwright}, Headless: {headless}) …")
llm = models.get_llm(target, provider=provider, n_ctx=n_ctx)
search_agent = _build_search_agent(llm, target, use_playwright, headless, search_max_steps, execution_timeout,
provider=provider, n_ctx=n_ctx)
_manager_agent = _build_manager_agent(llm, search_agent, target, manager_max_steps, execution_timeout, use_playwright, headless, use_tool_calling=use_tool_calling,
provider=provider, n_ctx=n_ctx)
_manager_agent_model_id = target
_manager_agent_config = current_config
_manager_agent_n_ctx = n_ctx
# Standard smolagents behaviour: a freshly-built agent starts with
# empty memory (see agent_memory.py's module docstring for why
# this app doesn't try to restore memory from a previous
# model/session here either).
return _manager_agent
def reset_agent():
"""Drop the cached manager (and its search sub-agent). Does NOT unload
the underlying LLM itself — that's shared/managed by models.get_llm().
Call this whenever the Deep Research tab's model changes or the LLM
is force-reloaded/unloaded elsewhere — mirrors general_agent.reset_agent().
"""
global _manager_agent, _manager_agent_model_id, _manager_agent_config, _manager_agent_n_ctx, _search_tool, _webpage_tool
_manager_agent = None
_manager_agent_model_id = None
_manager_agent_config = {}
_manager_agent_n_ctx = None
_search_tool = None
_webpage_tool = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896"""
general_agent.py — Agentic General Chat via a smolagents agent
(CodeAgent or ToolCallingAgent — see agents/agent_factory.py for the
choice), using
smolagents' own built-in tools (see:
https://huggingface.co/docs/smolagents/tutorials/tools) instead of any
app-specific tool like RAG Chat's RetrieverTool (knowledge_base.py) or
Data Analysis's install_package (data_analysis.py).
Tools used here:
- DuckDuckGoSearchTool — live web search
- VisitWebpageTool — fetch + read a page's full text when a search
snippet isn't enough
- SpeechToTextTool — transcribes an audio file/URL to text (see
https://huggingface.co/docs/smolagents/en/reference/default_tools#smolagents.SpeechToTextTool).
Useful if the user's message references a local
audio file path or URL they want transcribed.
NOTE: this is a separate, simpler code path from
the app's own dedicated 🎙️ Speech to Text tab
(models.py's transcribe_audio()) — it downloads
and lazily loads its own fixed Whisper checkpoint
(openai/whisper-large-v3-turbo) the first time
the agent actually calls it, is not configurable
from the model dropdowns, and doesn't chunk long
(>30s) audio or force a language the way
models.py's pipeline does. For serious/long
transcription work, point the user at the
dedicated STT tab instead; this tool is meant
for the agent to handle short ad-hoc audio
incidentally mentioned mid-conversation.
PythonInterpreterTool is deliberately NOT added: it's only meaningful for
ToolCallingAgent (JSON-style tool calls). CodeAgent already writes and
executes its own Python for every step, so adding PythonInterpreterTool
as a *tool* on top of that would just be a redundant, confusing entry in
the agent's toolbox.
Same caveat as rag_agent.py / data_analysis.py: tool-calling reliability
depends heavily on the underlying model. Gemma-4-E2B (this app's default)
may never call a tool at all, or call it malformed, and just hallucinate
an answer from its own knowledge instead. If the agent seems to ignore
the web tools, switch to a larger model (Gemma-4-E4B+, or any capable
GGUF model) in the LLM dropdown first.
"""
import os
import re
import threading
import time
from pathlib import Path
from typing import Optional
from smolagents import DuckDuckGoSearchTool, Tool, VisitWebpageTool
from agents.agent_factory import build_smol_agent
from backend import model_registry as mr
from backend import models
from ui import i18n
_general_agent = None
_general_agent_model_id = None
_general_agent_max_steps = None
_general_agent_execution_timeout = None
_general_agent_lang_key = None
_general_agent_n_ctx = None
_general_agent_lock = threading.Lock()
# ──────────────────────────────────────────────────────────────────
# Citation tracking — DuckDuckGoSearchTool / VisitWebpageTool are
# smolagents' own built-in tools, not app-specific ones we can add
# call-count/found-count bookkeeping to by editing their source. Instead,
# thin subclasses record every query run / URL actually opened, mirroring
# knowledge_base.RetrieverTool's self-tracked call_count/found_count
# pattern (see rag_agent.py's strict-grounding verification for why: it's
# more reliable than trying to introspect the agent's internal
# step/memory structure, which varies across smolagents versions).
#
# This lets chat.py append a guaranteed-accurate "sources consulted this
# turn" list after every agentic run, independent of whether the model
# actually remembered to write its own in-text citations/References
# section (which — like RAG's strict grounding — depends on the
# underlying model's instruction-following and can't be fully trusted).
# ──────────────────────────────────────────────────────────────────
# smolagents' DuckDuckGoSearchTool formats each hit as a markdown link
# followed by its snippet, e.g. "[Page Title](https://example.com/page)\n
# some snippet text…", under a "## Search Results" header. This pulls the
# real (title, url) pairs straight out of that text so chat.py can cite an
# actual clickable source instead of just repeating the query string (a
# query the model typed is not itself a source — see the "did not provide
# the actual link" issue this fixes).
_MARKDOWN_LINK_RE = re.compile(r'\[([^\]]+)\]\((https?://[^\s\)]+)\)')
# Matches the "### References" (or similar) heading GENERAL_AGENT_INSTRUCTIONS
# asks the model to end its answer with, so the section body can be pulled
# out and parsed for the URLs the model actually claims it used.
_REFERENCES_HEADER_RE = re.compile(r'#{1,6}\s*references?\b', re.IGNORECASE)
_BARE_URL_RE = re.compile(r'https?://\S+')
def extract_model_cited_urls(answer: str) -> list:
"""Pull (num_str, title, url) tuples out of the model's own '### References'
section at the end of its answer.
Tolerates both formats the model might use:
- '[1] Page Title — https://example.com/page'
- '[Page Title](https://example.com/page)' or '[1] [Page Title](https://example.com/page)'
Returns a list of (num_str, title, url) tuples, where num_str is the
citation index tag (e.g. "1", "7") if present, or None if omitted.
"""
if not answer:
return []
header_match = _REFERENCES_HEADER_RE.search(answer)
if not header_match:
return []
section = answer[header_match.end():]
items = []
seen_urls = set()
for line in section.splitlines():
line = line.strip()
if not line:
continue
url_match = _BARE_URL_RE.search(line)
if not url_match:
# Check for pure markdown link format [Title](https://...)
md_match = _MARKDOWN_LINK_RE.search(line)
if md_match:
title, url = md_match.group(1), md_match.group(2)
url = url.strip().rstrip(').,;')
if url not in seen_urls:
prefix = line[:md_match.start()].strip()
num_m = re.match(r'^\[?(\d+)\]?[.\-:)]*\s*', prefix)
num_str = num_m.group(1) if num_m else None
items.append((num_str, title.strip(), url))
seen_urls.add(url)
continue
url = url_match.group(0).rstrip(').,;')
if url in seen_urls:
continue
prefix = line[:url_match.start()].strip()
num_m = re.match(r'^\[?(\d+)\]?[.\-:)]*\s*', prefix)
num_str = num_m.group(1) if num_m else None
title = re.sub(r'^\[?\d+\]?[.\-:)]*\s*', '', prefix).strip(' -—:')
items.append((num_str, title or url, url))
seen_urls.add(url)
return items
def resolve_actually_used_sources(answer: str, urls_visited: list, result_links: list) -> list:
"""Return the (num_str, title, url) tuples that should be shown as this
turn's actually-used references — the INTERSECTION of what the model claims
it cited (its own '### References' section) and what was REALLY
searched/visited this run.
"""
known_title_by_url = {}
for u in urls_visited:
known_title_by_url.setdefault(u, u)
for title, u in result_links:
known_title_by_url.setdefault(u, title)
cited = extract_model_cited_urls(answer)
used, seen = [], set()
fallback_idx = 1
for num, title, url in cited:
real_url = url if url in known_title_by_url else next(
(k for k in known_title_by_url if k.rstrip('/') == url.rstrip('/')), None
)
if real_url and real_url not in seen:
item_num = num if num else str(fallback_idx)
used.append((item_num, title or known_title_by_url[real_url], real_url))
seen.add(real_url)
fallback_idx += 1
if used:
return used
if urls_visited:
return [(str(i + 1), u, u) for i, u in enumerate(urls_visited) if u not in seen]
return [(str(i + 1), title, url) for i, (title, url) in enumerate(result_links)]
def strip_trailing_references_section(answer: str) -> str:
"""Cut off the model's own '### References' section (if present) from
the end of its answer, so chat.py can replace it with the verified
list from resolve_actually_used_sources() instead of showing both the
model's (unverified, possibly incomplete/hallucinated) version and a
second, accurate one back to back.
"""
if not answer:
return answer
header_match = _REFERENCES_HEADER_RE.search(answer)
if not header_match:
return answer
return answer[:header_match.start()].rstrip()
def renumber_citations(answer: str, used_sources: list) -> tuple:
"""Remap citation numbers in `answer` (e.g. [2, 3, 7] -> [1, 2, 3]) and in `used_sources`
so that citations start sequentially from 1 to N without gaps.
Prevents citation hallucinations:
- If `used_sources` is empty (no tools called or all model-cited URLs were hallucinated),
any stray bracketed citation tags like [1], [2] are stripped from the answer text.
- Any in-text citation tag referencing an unverified source index (not present in `used_sources`)
is removed from the answer text.
Returns (renumbered_answer, renumbered_sources).
"""
if not answer:
return answer, used_sources
if not used_sources:
# No verified sources exist for this run — strip any stray/hallucinated [n] tags from text
cleaned_answer = re.sub(r'\s*\[\d+(?:\s*,\s*\d+)*\]', '', answer)
return cleaned_answer, []
num_map = {}
renumbered_sources = []
for new_idx, item in enumerate(used_sources, 1):
if len(item) == 3:
old_num, title, url = item
else:
old_num, title, url = str(new_idx), item[0], item[1]
new_num_str = str(new_idx)
if old_num:
num_map[str(old_num)] = new_num_str
renumbered_sources.append((new_num_str, title, url))
def replace_bracket(match):
content = match.group(1)
parts = [p.strip() for p in content.split(',')]
if all(p.isdigit() for p in parts if p):
# Only keep numbers that mapped to a verified source in num_map!
valid_parts = [num_map[p] for p in parts if p in num_map]
if not valid_parts:
return "" # Remove the bracket entirely if all numbers inside were hallucinated
seen = set()
dedup = []
for np in valid_parts:
if np not in seen:
dedup.append(np)
seen.add(np)
return "[" + ", ".join(dedup) + "]"
return match.group(0)
renumbered_answer = re.sub(r'\[(\d+(?:\s*,\s*\d+)*)\]', replace_bracket, answer)
# Clean up double spaces created by removed brackets
renumbered_answer = re.sub(r' +', ' ', renumbered_answer)
return renumbered_answer, renumbered_sources
class TrackedDuckDuckGoSearchTool(DuckDuckGoSearchTool):
input_aliases = {
"query": ("q", "question", "search", "search_query", "keywords", "task", "text", "prompt"),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queries_run = []
# Real (title, url) pairs actually surfaced by a search this run —
# see _MARKDOWN_LINK_RE above. Deduplicated in insertion order.
self.result_links = []
self._last_call_time = 0.0
def forward(self, query: str) -> str:
# Guard against a model looping on the EXACT same query — seen in
# practice with some larger local GGUF models, which will re-run
# an identical search 5-6+ times in a row instead of noticing it
# already has the results (each call still costs a real network
# round-trip). Case/whitespace-insensitive match; a genuinely
# different/refined query is still allowed through normally.
normalized = query.strip().lower()
if normalized and any(normalized == q.strip().lower() for q in self.queries_run):
return (
f"You already searched for '{query}' earlier in this run and "
"got results — running the exact same query again will only "
"return the same thing. Stop searching and write your final "
"answer using what you already found, or search for something "
"MEANINGFULLY DIFFERENT if you still need more information."
)
# Inter-search pacing: delay at least 1.2s between rapid searches
# to prevent DuckDuckGo rate-limiting.
now = time.time()
elapsed = now - self._last_call_time
if elapsed < 1.2 and self._last_call_time > 0:
time.sleep(1.2 - elapsed)
self.queries_run.append(query)
result = None
try:
result = super().forward(query)
except Exception as e:
err_str = str(e).lower()
if "ratelimit" in err_str or "202" in err_str or "too many requests" in err_str:
# Retry once after 2.0s backoff
time.sleep(2.0)
try:
result = super().forward(query)
except Exception as retry_e:
return f"DuckDuckGo search rate-limited: {retry_e}. Use existing information or try again later."
else:
return f"DuckDuckGo search error: {e}"
finally:
self._last_call_time = time.time()
for title, url in _MARKDOWN_LINK_RE.findall(result or ""):
pair = (title.strip(), url.strip())
if pair not in self.result_links:
self.result_links.append(pair)
return result
_IMAGE_EXFILTRATION_RE = re.compile(r"!\[(.*?)\]\((https?://[^\s)]+)\)")
def sanitize_scraped_markdown(text: str) -> str:
"""Sanitize scraped web markdown to neutralize remote markdown image tags,
which can be exploited in indirect prompt injection attacks for data exfiltration."""
if not text:
return ""
return _IMAGE_EXFILTRATION_RE.sub(r"[image: \1]", text)
class TrackedVisitWebpageTool(VisitWebpageTool):
input_aliases = {
"url": ("link", "webpage", "page", "address", "site", "target"),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.urls_visited = []
def forward(self, url: str) -> str:
self.urls_visited.append(url)
content = super().forward(url)
return sanitize_scraped_markdown(content)
# ──────────────────────────────────────────────────────────────────
# File I/O tools — ReadFileTool and WriteFileTool give the agent the
# ability to read from and write to files on disk within the app's
# workspace root. Paths outside the workspace root are rejected.
# ──────────────────────────────────────────────────────────────────
_FILE_TOOL_ROOT: Path = Path(
os.environ.get("FILE_TOOL_ROOT", str(Path(__file__).parent.parent))
).resolve()
_MAX_READ_BYTES = 1_000_000 # 1 MB safety cap for read_file
_PROTECTED_READ_FILENAMES = {".env", "user_config.json"}
_BLOCKED_WRITE_EXTENSIONS = {
".py", ".pyw", ".pyc", ".pyd",
".exe", ".bat", ".cmd", ".ps1", ".psm1", ".vbs", ".vbe", ".wsf", ".wsh",
".dll", ".sys", ".so", ".dylib",
".sh", ".bash",
}
_PROTECTED_WRITE_DIRS = {"backend", "agents", "ui", "installer", "tools", ".git", ".venv", ".venv-build"}
def _safe_resolve(raw_path: str, for_write: bool = False) -> Path:
"""Resolve `raw_path` under _FILE_TOOL_ROOT; raises ValueError if the
resolved path escapes the root (path traversal protection) or touches
protected sensitive system files or source directories."""
cleaned = (raw_path or "").strip().strip('"').strip("'")
if not cleaned:
raise ValueError("Empty file path provided.")
p = (_FILE_TOOL_ROOT / cleaned).resolve()
try:
rel = p.relative_to(_FILE_TOOL_ROOT)
except ValueError:
raise ValueError(
f"Path '{raw_path}' resolves to '{p}', which is outside the "
f"allowed workspace root '{_FILE_TOOL_ROOT}'. "
"Only paths within the workspace root are permitted."
)
parts = rel.parts
filename = p.name.lower()
ext = p.suffix.lower()
if not for_write:
if filename in _PROTECTED_READ_FILENAMES or filename.endswith(".env"):
raise ValueError(f"Access denied: reading secret or credential file '{filename}' is restricted.")
if any(part in (".git", ".venv", ".venv-build") for part in parts):
raise ValueError(f"Access denied: reading internal directory '{parts[0]}' is restricted.")
if for_write:
if filename in _PROTECTED_READ_FILENAMES or filename.endswith(".env"):
raise ValueError(f"Access denied: writing to secret or credential file '{filename}' is prohibited.")
if ext in _BLOCKED_WRITE_EXTENSIONS:
raise ValueError(f"Access denied: writing executable/script file type '{ext}' is prohibited.")
if any(part in _PROTECTED_WRITE_DIRS for part in parts):
raise ValueError(f"Access denied: writing to application source directory '{parts[0]}' is prohibited.")
return p
class SpeechToTextTool(Tool):
"""App-local transcriber tool that NEVER imports torch at construction
time. smolagents' stock SpeechToTextTool eagerly imports
`transformers.models.whisper` in its `__new__` — that transitively pulls
in accelerate, which then fails with "No package metadata was found for
torch" on machines where torch is not installed. The Store/MSIX build
deliberately ships WITHOUT torch (CPU/GPU PyTorch is installed on-demand
via Settings), so constructing the stock tool crashed EVERY agentic
General/Deep-Research run on that build. A missing torch must degrade,
never crash agent construction.
Two further fixes over the stock tool, both preserved here:
1. The input schema uses a JSON-Schema-valid `string` type — the stock
tool declares `{"audio": {"type": "audio"}}`, and `"audio"` is NOT
a valid JSON-Schema type for OpenAI-compatible function calling, so
strict HF Inference API providers (DeepInfra, Novita, …) reject the
ENTIRE request.
2. Transcription runs through the app's OWN configured STT pipeline
(backend.models.transcribe_audio — whisper.cpp server / in-process
whisper-cpp / HF Inference API / local HF). That is torch-free on
the server and remote providers, already respects the user's
Settings STT configuration, and degrades to a clear error message
when nothing is configured.
"""
name = "transcriber"
description = (
"This is a tool that transcribes an audio file into text. "
"It returns the transcribed text."
)
inputs = {
"audio": {
"type": "string",
"description": "Path or URL of the audio file to transcribe.",
}
}
output_type = "string"
@staticmethod
def _resolve_audio_path(audio) -> Optional[str]:
"""Resolve the tool input to a local audio file: an existing local
path (surrounding quotes stripped) or an http(s) URL downloaded to a
temp file. Returns None when the input cannot become a readable file
— the caller turns that into a clear error, never a crash."""
if not audio:
return None
raw = str(audio).strip().strip('"').strip("'")
if not raw:
return None
if raw.lower().startswith(("http://", "https://")):
try:
import tempfile
import urllib.request
from urllib.parse import urlparse
suffix = Path(urlparse(raw).path).suffix or ".wav"
tmp = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
tmp.close()
urllib.request.urlretrieve(raw, tmp.name)
return tmp.name
except Exception:
return None
p = Path(raw).expanduser()
return str(p) if p.exists() else None
def forward(self, audio: str) -> str:
path = self._resolve_audio_path(audio)
if path is None:
return (
"[transcriber ERROR] Could not read the audio input — pass a "
"local audio file path or an http(s) URL to an audio file."
)
from backend import models
try:
text = models.transcribe_audio(path, language="auto")
except Exception as exc: # pragma: no cover — defensive
return f"[transcriber ERROR] {exc}"
text = (text or "").strip()
if text.startswith("❌"):
# transcribe_audio embeds a full traceback in the failure yield;
# surface only the actionable first line (e.g. "No whisper-server
# executable is configured…").
first = text.splitlines()[0] if text.splitlines() else text
return f"[transcriber ERROR] {first[:200]}"
return text if text else "(No speech detected)"
class ReadFileTool(Tool):
"""Reads the text content of a file on disk within the workspace."""
name = "read_file"
description = (
"Read the text content of a file on disk. "
"Pass the file path relative to the workspace root "
"(e.g. '.agents/skills/my_skill/SKILL.md') or an absolute path "
"that sits inside the workspace root. "
"Returns the full file content as a string. "
"Returns an error string if the file does not exist, is binary, "
"or exceeds 1 MB. Do NOT use this for audio/image/binary files."
)
inputs = {
"path": {
"type": "string",
"description": "Relative or absolute path to the file to read.",
}
}
input_aliases = {
"path": ("file_path", "filepath", "file", "filename", "doc", "src"),
}
output_type = "string"
def forward(self, path: str) -> str:
try:
resolved = _safe_resolve(path, for_write=False)
except ValueError as e:
return f"[read_file ERROR] {e}"
if not resolved.exists():
return f"[read_file ERROR] File not found: '{resolved}'"
if not resolved.is_file():
return f"[read_file ERROR] '{resolved}' is not a regular file."
size = resolved.stat().st_size
if size > _MAX_READ_BYTES:
return (
f"[read_file ERROR] File is {size:,} bytes — exceeds the "
f"{_MAX_READ_BYTES:,}-byte read limit. Summarize or split it."
)
try:
return resolved.read_text(encoding="utf-8", errors="replace")
except Exception as exc:
return f"[read_file ERROR] Could not read '{resolved}': {exc}"
class WriteFileTool(Tool):
"""Writes (or overwrites) a file on disk within the workspace."""
name = "write_file"
description = (
"Write text content to a file on disk within the workspace root. "
"Creates the file (and any missing parent directories) if it does "
"not exist; OVERWRITES it if it already exists. "
"Pass the file path relative to the workspace root "
"(e.g. '.agents/skills/my_skill/SKILL.md') and the full text "
"content to write. Returns a confirmation message with the "
"absolute path of the written file, or an error string on failure."
)
inputs = {
"path": {
"type": "string",
"description": "Relative or absolute path of the file to write.",
},
"content": {
"type": "string",
"description": "The full text content to write to the file.",
},
}
input_aliases = {
"path": ("file_path", "filepath", "file", "filename", "target"),
"content": ("text", "data", "body"),
}
output_type = "string"
def forward(self, path: str, content: str) -> str:
try:
resolved = _safe_resolve(path, for_write=True)
except ValueError as e:
return f"[write_file ERROR] {e}"
try:
resolved.parent.mkdir(parents=True, exist_ok=True)
resolved.write_text(content, encoding="utf-8")
return f"[write_file OK] Written {len(content):,} chars to '{resolved}'"
except Exception as exc:
return f"[write_file ERROR] Could not write '{resolved}': {exc}"
class DraftCodexSkillTool(Tool):
"""Drafts a Codex-style SKILL.md from a concise user idea."""
name = "draft_codex_skill"
description = (
"Draft a Codex SKILL.md from a user request. Use this when the user "
"asks to create, update, or design a reusable Codex skill. This tool "
"does not write files; use write_file afterward only if the user wants "
"the skill saved."
)
inputs = {
"idea": {
"type": "string",
"description": "The user's skill idea or requested workflow.",
},
"skill_name": {
"type": "string",
"description": "Optional short kebab-case skill name.",
"default": "",
"nullable": True,
},
}
output_type = "string"
@staticmethod
def _slug(text: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")
return slug[:48].strip("-") or "custom-skill"
def forward(self, idea: str, skill_name: str = "") -> str:
idea = (idea or "").strip()
if not idea:
return "[draft_codex_skill ERROR] Provide a skill idea."
name = self._slug(skill_name or idea)
description = (
f"Use when the user wants help with {idea}. "
"Follow the workflow and constraints in this skill."
)
body = (
"---\n"
f"name: {name}\n"
f"description: {description}\n"
"---\n\n"
f"# {name.replace('-', ' ').title()}\n\n"
"## Workflow\n\n"
"1. Identify the user's exact goal and scope.\n"
"2. Gather only the context needed for the task.\n"
"3. Choose the narrowest reliable action path.\n"
"4. Produce the requested artifact or answer.\n"
"5. Validate the result before finishing.\n\n"
"## Rules\n\n"
"- Keep the workflow focused and repeatable.\n"
"- Prefer existing project conventions and tools.\n"
"- Ask for clarification only when a safe assumption is not possible.\n"
"- Do not add unrelated files or broad background prose.\n\n"
"## Output\n\n"
"- State what scope was used.\n"
"- Provide the finished result or exact next action.\n"
"- Mention any validation performed or remaining limitation.\n"
)
return (
f"Suggested path: .agents/skills/{name}/SKILL.md\n\n"
"```markdown\n"
f"{body}"
"```"
)
# Module-level refs to the CURRENT agent's tracked-tool instances, so
# chat.py can read/reset them without needing to reach into the agent's
# internal tool registry — mirrors rag_agent.py's `_rag_tool` pattern.
_search_tool = None
_webpage_tool = None
_read_file_tool: "Optional[ReadFileTool]" = None
_write_file_tool: "Optional[WriteFileTool]" = None
_draft_skill_tool: "Optional[DraftCodexSkillTool]" = None
# Base instructions — language-directive prepended dynamically by
# build_agent_instructions() at agent-build time, so even models that
# ignore a per-task hint see the language rule at the system-prompt level.
GENERAL_AGENT_INSTRUCTIONS = (
"You are a helpful, friendly assistant.\n\n"
"CRITICAL OUTPUT RULE: Output ONLY the direct final response to the user. "
"NEVER include your internal monologue, planning notes, or prompt analysis in your answer.\n\n"
"Available tools: `web_search`, `visit_webpage`, `transcriber`, "
"`read_file`, `write_file`, `draft_codex_skill`. There is NO other tool "
"\u2014 in particular no `conversation_history`, `memory`, or "
"`get_previous_messages` function. Never call, import, or reference "
"anything not listed; it will fail and waste a step.\n\n"
"YOUR OWN CONVERSATION HISTORY IS ALREADY VISIBLE TO YOU: every earlier "
"user message and your own earlier replies are already included in what "
"you can see \u2014 you do not need a tool to retrieve them. If asked what "
"was said earlier, look back at the earlier turns and answer from them "
"directly \u2014 do NOT guess.\n\n"
"Use web_search/visit_webpage only when a question needs current "
"information or specific facts you're unsure of. For simple, timeless, "
"conversational questions answerable from your own knowledge, just "
"answer directly.\n\n"
"If the user asks to create or revise a Codex skill, save the SKILL.md "
"with `write_file` to '.agents/skills/<skill_name>/' \u2014 write it to "
"disk so it is immediately usable, don't just output the content in chat.\n\n"
"DON'T REPEAT SEARCHES: never run the exact same web_search query twice "
"in one turn. Once you have enough information, stop searching and write "
"your final answer.\n\n"
"The user's actual question is in the Task below — answer THAT, not "
"these instructions. Never repeat, summarize, or reply to the "
"instructions themselves."
)
# Khmer-only no-reasoning instruction — GLM-4.7-Flash and similar local
# GGUF models sometimes output their entire chain-of-thought in Khmer
# (instead of wrapping it in <think> tags or calling final_answer directly),
# producing meta-reasoning like "សំណួររបស់អ្នកប្រើគឺ..." ("The user's
# question is...") as the final answer. Placing this rule in Khmer at the
# TOP of the system prompt — before the English instructions — ensures
# even small models that anchor on Khmer system text see the rule.
_KHMER_NO_REASONING_INSTRUCTION = (
"⚠️ ការណែនាំសំខាន់៖ កុំសរសេរការវិភាគ ការគិតខាងក្នុង ឬការរៀបចំផែនការ "
"នៅក្នុងចម្លើយរបស់អ្នកឡើយ។ កុំសរសេរអ្វីដូចជា \"សំណួររបស់អ្នកប្រើគឺ...\" "
"ឬ \"ខ្ញុំមិនត្រូវការប្រើ tool...\" ឬ \"ដូច្នេះខ្ញុំគិតថា...\" ក្នុងចម្លើយ។ "
"ផ្តល់តែចម្លើយចុងក្រោយដោយផ្ទាល់ប៉ុណ្ណោះ។\n\n"
)
def build_agent_instructions(lang_key: str = "kh") -> str:
"""Return GENERAL_AGENT_INSTRUCTIONS with the output-language directive
prepended as the very first line of the system prompt.
Injecting the rule here (system-prompt level, applied once at agent-build
time) is more reliable than the per-task-message approach alone:
small/weak GGUF models that ignore a language hint buried inside the
user-turn task text still tend to comply when they see it as a top-level
SYSTEM instruction. Both layers are kept (system + per-task) for maximum
coverage.
"""
lang_directive = i18n._output_lang_instruction(lang_key)
# For Khmer UI: prepend the Khmer no-reasoning instruction BEFORE the
# English instructions so the model sees the rule in its UI language first.
no_reasoning = _KHMER_NO_REASONING_INSTRUCTION if lang_key == "kh" else ""
return lang_directive + no_reasoning + GENERAL_AGENT_INSTRUCTIONS
def build_task_with_citation_reminder(user_message: str, lang_key: str = "kh") -> str:
"""Wrap the user's message with an explicit, PER-TASK reminder of the
citation requirement — a second layer on top of
GENERAL_AGENT_INSTRUCTIONS, mirroring rag_agent.build_strict_task()'s
"belt and braces" reasoning exactly.
Why this is needed: GENERAL_AGENT_INSTRUCTIONS (including its
citation requirement) is only ever attached to the agent if this
installed smolagents version's chosen agent class (CodeAgent or
ToolCallingAgent) happens to expose an `instructions=` parameter — see the
`if "instructions" in params: kwargs["instructions"] = ...` guard in
agents/agent_factory.py's build_smol_agent(). On a smolagents
version where that parameter doesn't exist, that assignment is
silently skipped and the
model never sees the citation requirement AT ALL — it has no way to
know it's supposed to write a '### References' section, so
chat.py's resolve_actually_used_sources() always finds nothing to
parse, even after a turn that genuinely searched the web. Repeating
the requirement here, in the per-call task text (which always
reaches the model regardless of smolagents version), closes that
gap — same reasoning rag_agent.py already applies to its own
strict-grounding instructions.
"""
# The task text IS the user turn the model sees (smolagents places it
# in the user message), so the question must be the LAST line — a small
# GGUF model anchors on whatever comes right before its own turn, and
# the "answers the system prompt" failure class fires when the
# question is buried at the start behind instruction blocks (see
# chat_general_direct's matching anchor for the direct path).
return (
i18n._output_lang_instruction(lang_key)
+ i18n._task_preamble(lang_key)
+ i18n._task_citation_reminder(lang_key)
+ i18n._task_conciseness_directive(lang_key)
+ "\n\n---\n"
+ i18n._task_question_label(lang_key)
+ f"{user_message}"
)
GENERAL_AGENT_DEFAULT_MAX_STEPS = 8
def _build_agent(llm, model_id: str = "",
max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
use_tool_calling: bool = True,
lang_key: str = "kh"):
global _search_tool, _webpage_tool, _read_file_tool, _write_file_tool, _draft_skill_tool
_search_tool = TrackedDuckDuckGoSearchTool()
_webpage_tool = TrackedVisitWebpageTool()
_read_file_tool = ReadFileTool()
_write_file_tool = WriteFileTool()
_draft_skill_tool = DraftCodexSkillTool()
if max_steps is None:
max_steps = mr.get_max_steps_for_model(model_id, GENERAL_AGENT_DEFAULT_MAX_STEPS)
agent = build_smol_agent(
llm,
tools=[_search_tool, _webpage_tool, SpeechToTextTool(),
_read_file_tool, _write_file_tool, _draft_skill_tool],
max_steps=max_steps,
use_tool_calling=use_tool_calling,
instructions=build_agent_instructions(lang_key),
execution_timeout=execution_timeout,
)
print(f"[GeneralAgent] Building {type(agent).__name__} on '{model_id or '(shared)'}' …")
return agent
def reset_tool_usage() -> None:
"""Call right before agent.run() so this run's tracked queries/URLs
start from zero — mirrors rag_agent.reset_retriever_stats()."""
if _search_tool is not None:
_search_tool.queries_run = []
_search_tool.result_links = []
if _webpage_tool is not None:
_webpage_tool.urls_visited = []
# ReadFileTool / WriteFileTool are stateless per-call; nothing to reset.
def get_tool_usage() -> tuple:
"""Call right after agent.run() returns. Returns (queries_run,
urls_visited, result_links) — the ACTUAL search queries run, pages
explicitly visited via visit_webpage, and (title, url) pairs actually
surfaced by web_search's own results this turn — tracked directly by
the tools themselves rather than trusting the model's own in-text
citations (see the TrackedDuckDuckGoSearchTool / TrackedVisitWebpageTool
docstring above for why). `result_links` is what should be used to
build a real, clickable references list — the raw query string alone
is not a citable source."""
queries = list(_search_tool.queries_run) if _search_tool is not None else []
urls = list(_webpage_tool.urls_visited) if _webpage_tool is not None else []
links = list(_search_tool.result_links) if _search_tool is not None else []
return queries, urls, links
def get_general_agent(model_id: Optional[str] = None,
max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
use_tool_calling: bool = True,
provider: Optional[str] = None,
lang_key: str = "kh",
n_ctx: Optional[int] = None):
"""Lazily build (or rebuild, if the model/settings changed) the agentic
General Chat CodeAgent or ToolCallingAgent.
`lang_key` is included in the cache key so that switching UI language
forces a rebuild with a fresh system-prompt language directive — without
this the agent built for Khmer would keep its Khmer system prompt even
after the user switches to English, and vice-versa.
`n_ctx` (optional): this tab's context window, threaded straight through
to models.get_llm() so a per-tab n_ctx change rebuilds the agent with
the freshly (re)loaded model. Included in the cache key for that reason.
"""
global _general_agent, _general_agent_model_id
global _general_agent_max_steps, _general_agent_execution_timeout
global _general_agent_lang_key, _general_agent_n_ctx
target = model_id or models._llm_model_id
if (_general_agent is not None
and target == _general_agent_model_id
and max_steps == _general_agent_max_steps
and execution_timeout == _general_agent_execution_timeout
and lang_key == _general_agent_lang_key
and n_ctx == _general_agent_n_ctx):
return _general_agent
with _general_agent_lock:
if (_general_agent is not None
and target == _general_agent_model_id
and max_steps == _general_agent_max_steps
and execution_timeout == _general_agent_execution_timeout
and lang_key == _general_agent_lang_key
and n_ctx == _general_agent_n_ctx):
return _general_agent
llm = models.get_llm(target, provider=provider, n_ctx=n_ctx)
_general_agent = _build_agent(llm, target, max_steps, execution_timeout,
use_tool_calling=use_tool_calling, lang_key=lang_key)
_general_agent_model_id = target
_general_agent_max_steps = max_steps
_general_agent_execution_timeout = execution_timeout
_general_agent_lang_key = lang_key
_general_agent_n_ctx = n_ctx
return _general_agent
def reset_agent():
"""Drop the cached CodeAgent wrapper (does NOT unload the underlying
LLM itself — that's shared/managed by models.get_llm()). Call this
whenever the General Chat model changes or the LLM is force-reloaded/
unloaded elsewhere, so this agent doesn't keep holding a stale model
reference — mirrors rag_agent.reset_agent() / data_analysis.reset_agent().
"""
global _general_agent, _general_agent_model_id, _search_tool, _webpage_tool
global _general_agent_max_steps, _general_agent_execution_timeout
global _general_agent_lang_key, _general_agent_n_ctx, _read_file_tool, _write_file_tool
_general_agent = None
_general_agent_model_id = None
_general_agent_max_steps = None
_general_agent_execution_timeout = None
_general_agent_lang_key = None
_general_agent_n_ctx = None
_search_tool = None
_webpage_tool = None
_read_file_tool = None
_write_file_tool = None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189"""playwright_search_tool.py
Playwright-driven web search tools for Open Deep Research / rdtii, used ALONGSIDE the
existing paid SerpAPI/Serper `GoogleSearchTool` and `DuckDuckGoSearchTool` (not a
replacement for either).
Two search tools are provided:
- PlaywrightDuckDuckGoSearchTool (RECOMMENDED as primary): scrapes DuckDuckGo's
server-rendered HTML results page. No JavaScript wait, no CAPTCHA/consent wall in
normal use, and stable markup -- the most scrape-friendly of the two.
- PlaywrightGoogleSearchTool (fallback): scrapes Google's JS-rendered results page.
Broader index (useful for some non-English/regional government sites DuckDuckGo
misses), but far more bot-detection friction -- occasional CAPTCHA/consent walls
and markup that shifts to resist scraping.
Why either exists at all: SerpAPI/Serper cost money per query and DuckDuckGo (via the
`ddgs` library) gets rate-limited under heavy/rapid use. These instead launch a real
(headless) Chromium browser via Playwright and scrape results directly -- no paid API,
no third-party search library, no per-query cost or account quota.
They're drop-in-shaped tools: single `query` input, and a similar "numbered list of
title/link/snippet" output shape as smolagents' GoogleSearchTool. Once wired in
alongside the other search tools, the search_agent keeps using its existing tools
(VisitTool, PageUpTool, PageDownTool, FinderTool, FindNextTool, ArchiveSearchTool,
TextInspectorTool) to open, crawl, and read whatever pages these tools find -- only the
initial "search" step differs.
Requirements (not in requirements.txt by default -- add both):
pip install playwright
playwright install chromium
Usage:
from playwright_search_tool import PlaywrightDuckDuckGoSearchTool, PlaywrightGoogleSearchTool
WEB_TOOLS = [GoogleSearchTool(...), DuckDuckGoSearchTool(), PlaywrightDuckDuckGoSearchTool(), PlaywrightGoogleSearchTool(), ...]
---------------------------------------------------------------------------
Why PlaywrightGoogleSearchTool's extraction logic is NOT based on Google's CSS class
names (div.g, div.MjjYud, etc.):
Google's result-page markup (a) changes its class names frequently and without
notice, and (b) is frequently served *differently* to traffic it suspects is
automated -- a plain, unauthenticated, headless-looking browser can get a
stripped-down or reflowed results page where those old class names simply don't
exist, even though a person opening the same query in a normal browser sees full
results. Relying on class names is why an earlier version of this tool could report
"No Google results found" for a query that clearly has results.
Instead, extraction here is structural: Google's results almost always still put each
organic result's title inside an <h3>, wrapped (directly or via an ancestor) in an
<a href="..."> to the real destination. Walking up from every <h3> to its nearest
linked ancestor is far more resistant to markup/class churn than any fixed selector
list. A handful of anti-bot-detection tweaks (a realistic user agent, a normal
viewport, hiding the `navigator.webdriver` flag, and waiting for actual content
instead of a fixed sleep) also reduce how often Google serves the stripped-down page
in the first place.
DuckDuckGo's HTML endpoint below needs none of this -- it's server-rendered with no
client-side JS to fight, which is exactly why it's the recommended primary tool.
---------------------------------------------------------------------------
"""
from __future__ import annotations
import json
import os
import tempfile
import urllib.parse
from smolagents import Tool
_USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
)
_CONSENT_BUTTON_LABELS = ("Accept all", "I agree", "Accept", "Reject all", "Alle akzeptieren")
# Hosts that are Google's own chrome (nav bars, "Sign in", "Settings", cached-page
# links, translate links, etc.) rather than an actual search result -- filtered out
# of both the h3-based pass and the broad fallback pass below.
_IGNORED_HOST_FRAGMENTS = (
"google.com/search", "google.com/preferences", "google.com/advanced_search",
"google.com/intl", "accounts.google.", "support.google.", "policies.google.",
"maps.google.", "webcache.googleusercontent.", "translate.google.",
"/url?q=/search", "consent.google.",
)
_ANTI_DETECTION_INIT_SCRIPT = """
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] });
window.chrome = window.chrome || { runtime: {} };
"""
class PlaywrightDuckDuckGoSearchTool(Tool):
"""Searches DuckDuckGo's plain HTML endpoint (html.duckduckgo.com/html/) with
Playwright. This is the PREFERRED Playwright search tool for automated use, ahead
of PlaywrightGoogleSearchTool below:
- The page is fully server-rendered HTML with no JavaScript required, so there's
no client-side rendering to wait for and no anti-bot-detection script needed.
- No CAPTCHA/consent wall in normal use (unlike Google, which frequently serves
one to automated-looking traffic).
- Stable, simple markup (a.result__a / .result__snippet) that changes far less
often than Google's, which is deliberately obfuscated/rotated against scrapers.
Trade-off: DuckDuckGo's index is thinner than Google's for some non-English or
regional government sites, which is why PlaywrightGoogleSearchTool is kept as an
explicit fallback rather than removed.
"""
name = "playwright_duckduckgo_search"
description = (
"Performs a DuckDuckGo web search for your query and returns the top results (title, "
"link, short snippet) as a numbered list. Uses a real browser (Playwright) against "
"DuckDuckGo's plain HTML results page -- no JavaScript rendering wait, no CAPTCHA/consent "
"wall in normal use, and more stable markup than Google's. Use this as your PRIMARY search "
"tool for almost every search -- call it FIRST, before any other search tool. Only fall "
"back to the 'playwright_google_search' tool if this one comes back with no results, or a "
"topic needs Google's broader index (e.g. some non-English regional government sites). "
"Keep queries short and simple -- the plain topic name plus a country/keyword or two -- "
"rather than long boolean or quoted-phrase chains."
)
inputs = {
"query": {"type": "string", "description": "The search query to perform. Keep it short and simple."},
}
output_type = "string"
def __init__(self, max_results: int = 8, headless: bool = False, timeout_ms: int = 20000):
super().__init__()
self.max_results = max_results
self.headless = headless
self.timeout_ms = timeout_ms
def forward(self, query: str) -> str:
try:
from playwright.sync_api import sync_playwright
except ImportError as e:
raise ImportError(
"PlaywrightDuckDuckGoSearchTool needs the `playwright` package and its "
"browser binaries. Install with:\n"
" pip install playwright\n"
" playwright install chromium"
) from e
query = (query or "").strip()
if not query:
return "Error: empty search query."
url = "https://html.duckduckgo.com/html/?" + urllib.parse.urlencode({"q": query})
with sync_playwright() as p:
browser = p.chromium.launch(
headless=self.headless,
args=["--disable-blink-features=AutomationControlled"],
)
try:
context = browser.new_context(
user_agent=_USER_AGENT,
locale="en-US",
viewport={"width": 1366, "height": 900},
extra_http_headers={"Accept-Language": "en-US,en;q=0.9"},
)
page = context.new_page()
# Server-rendered HTML -- domcontentloaded is enough, no networkidle wait
# needed the way the JS-heavy Google results page requires.
page.goto(url, timeout=self.timeout_ms, wait_until="domcontentloaded")
extracted = page.evaluate(
"""
() => {
const results = [];
document.querySelectorAll('.result, .web-result').forEach(block => {
const a = block.querySelector('a.result__a');
if (!a || !a.href) return;
const snippetEl = block.querySelector('.result__snippet');
results.push({
title: (a.innerText || '').trim(),
link: a.href,
snippet: snippetEl ? (snippetEl.innerText || '').trim() : '',
});
});
return { results, pageTitle: document.title };
}
"""
)
results = extracted.get("results", [])
finally:
browser.close()
if not results:
return (
f"No DuckDuckGo results found for '{query}'. Try a shorter/simpler query with "
f"playwright_duckduckgo_search again, OR call the fallback Google tool like this:\n"
f"```python\n"
f'result = playwright_google_search(query="{query}")\n'
f"print(result)\n"
f"```"
)
lines = [f"## DuckDuckGo Search Results for '{query}'\n"]
n = 0
for r in results:
link = (r.get("link") or "").strip()
if not link:
continue
n += 1
title = (r.get("title") or link).strip()
snippet = (r.get("snippet") or "").strip()
lines.append(f"{n}. [{title}]({link})\n{snippet}\n")
if n >= self.max_results:
break
return "\n".join(lines)
class PlaywrightGoogleSearchTool(Tool):
"""Searches Google by driving a real headless browser with Playwright, as an
additional, free alternative alongside the existing paid/rate-limited search
tools -- not a replacement for them.
A fresh, isolated browser is launched per call (rather than one shared browser
kept alive across calls) -- slightly slower per search, but avoids any
thread-safety concerns from Gradio potentially handling requests on different
threads, and keeps this tool's lifecycle dead simple (nothing to explicitly shut
down at app exit).
"""
name = "playwright_google_search"
description = (
"Performs a Google web search for your query and returns the top results "
"(title, link, short snippet) as a numbered list. Uses a real browser "
"(Playwright) that types the query into google.com directly -- no paid "
"search API, no API key, and no third-party search library involved. This "
"is the FALLBACK search tool -- try 'playwright_duckduckgo_search' FIRST for "
"almost every search, and only call this one if that comes back with no "
"results or the topic needs Google's broader index. Keep queries short and "
"simple -- the plain topic name plus a country/keyword or two -- rather than "
"long boolean or quoted-phrase chains."
)
inputs = {
"query": {"type": "string", "description": "The search query to perform. Keep it short and simple."},
"filter_year": {
"type": "string",
"description": "(Optional) restrict results to this year, e.g. '2023'.",
"nullable": True,
},
}
output_type = "string"
def __init__(self, max_results: int = 8, headless: bool = False, timeout_ms: int = 20000, debug: bool = False):
super().__init__()
self.max_results = max_results
self.headless = headless
self.timeout_ms = timeout_ms
self.debug = debug
def forward(self, query: str, filter_year: str | None = None) -> str:
try:
from playwright.sync_api import sync_playwright
except ImportError as e:
raise ImportError(
"PlaywrightGoogleSearchTool needs the `playwright` package and its "
"browser binaries. Install with:\n"
" pip install playwright\n"
" playwright install chromium"
) from e
query = (query or "").strip()
if not query:
return "Error: empty search query."
params = {"q": query, "num": str(max(self.max_results, 10)), "hl": "en", "gl": "us", "pws": "0"}
if filter_year:
params["tbs"] = f"cdr:1,cd_min:1/1/{filter_year},cd_max:12/31/{filter_year}"
url = "https://www.google.com/search?" + urllib.parse.urlencode(params)
page_info = ""
with sync_playwright() as p:
browser = p.chromium.launch(
headless=self.headless,
args=["--disable-blink-features=AutomationControlled"],
)
try:
context = browser.new_context(
user_agent=_USER_AGENT,
locale="en-US",
viewport={"width": 1366, "height": 900},
extra_http_headers={"Accept-Language": "en-US,en;q=0.9"},
)
context.add_init_script(_ANTI_DETECTION_INIT_SCRIPT)
page = context.new_page()
page.goto(url, timeout=self.timeout_ms, wait_until="domcontentloaded")
# Best-effort consent-dialog dismissal (Google's EU/UK cookie wall) --
# harmless no-op if no such dialog appears for this session/region.
for label in _CONSENT_BUTTON_LABELS:
try:
page.get_by_role("button", name=label).click(timeout=1200)
page.wait_for_load_state("domcontentloaded", timeout=self.timeout_ms)
break
except Exception:
continue
# Wait for actual result content rather than a fixed sleep -- far more
# reliable across Google's varying render times. If nothing shows up
# in time, keep going anyway and let the extraction below report
# honestly (this also surfaces a captcha/consent page as "no results"
# rather than hanging).
try:
page.wait_for_selector("h3, #rso, #search", timeout=6000)
except Exception:
pass
page.wait_for_timeout(400)
extracted = page.evaluate(
"""
([ignoredFragments]) => {
const isIgnored = (href) => ignoredFragments.some(f => href.includes(f));
const results = [];
const seenLinks = new Set();
// Primary pass: every <h3> (the title Google puts on each organic
// result), walking up to its nearest linked ancestor.
document.querySelectorAll('h3').forEach(h3 => {
const a = h3.closest('a[href]') || h3.parentElement?.querySelector('a[href]');
if (!a || !a.href || !a.href.startsWith('http')) return;
if (isIgnored(a.href) || seenLinks.has(a.href)) return;
// Snippet: look at the result's outer block (a few levels up
// from the link) and take its text, minus the title itself.
let block = a.closest('div[data-hveid], div.g, div') || a.parentElement;
let text = block ? block.innerText : '';
const title = h3.innerText || '';
if (title && text.startsWith(title)) text = text.slice(title.length);
text = text.split('\\n').map(s => s.trim()).filter(Boolean).slice(0, 2).join(' ');
seenLinks.add(a.href);
results.push({ title: title || a.href, link: a.href, snippet: text });
});
// Fallback pass: if the h3-based pass found nothing (e.g. an
// unusual layout variant), broadly scan external links with
// non-trivial link text instead.
if (results.length === 0) {
document.querySelectorAll('a[href^="http"]').forEach(a => {
const href = a.href;
if (isIgnored(href) || seenLinks.has(href)) return;
const text = (a.innerText || '').trim();
if (text.length < 8) return;
seenLinks.add(href);
results.push({ title: text, link: href, snippet: '' });
});
}
return {
results: results.slice(0, 30),
pageTitle: document.title,
bodyLen: document.body ? document.body.innerText.length : 0,
};
}
""",
[_IGNORED_HOST_FRAGMENTS],
)
results = extracted.get("results", [])
if self.debug:
page_info = (
f" [debug: page title='{extracted.get('pageTitle')}', "
f"body chars={extracted.get('bodyLen')}]"
)
finally:
browser.close()
if not results:
year_note = f" (filtered to {filter_year})" if filter_year else ""
return (
f"No Google results found for '{query}'{year_note}.{page_info} This can happen if Google "
"served a consent/CAPTCHA page instead of results. Try playwright_duckduckgo_search "
"instead, like this:\n"
f"```python\n"
f'result = playwright_duckduckgo_search(query="{query}")\n'
f"print(result)\n"
f"```"
)
lines = [f"## Search Results for '{query}'{page_info}\n"]
n = 0
for r in results:
link = (r.get("link") or "").strip()
if not link:
continue
n += 1
title = (r.get("title") or link).strip()
snippet = (r.get("snippet") or "").strip()
lines.append(f"{n}. [{title}]({link})\n{snippet}\n")
if n >= self.max_results:
break
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Extensions/keywords that make a link look like the actual downloadable document
# file rather than a landing/details page about it. Deliberately broad (covers the
# common legal-document file types plus generic "get me the file" wording) -- a
# false positive here just means the agent double-checks a link that turns out to
# be another HTML page, which playwright_visit_page reports honestly either way.
# ---------------------------------------------------------------------------
_DOWNLOAD_EXT_RE = r"\.(pdf|docx?|rtf|txt)(\?|#|$)"
_DOWNLOAD_KEYWORD_RE = r"download|full[\s_-]?text|view[\s_-]?(the[\s_-])?(authoris|full)|attachment|/file/"
class PlaywrightVisitPageTool(Tool):
"""Opens a URL with a real headless Chromium browser (Playwright) and returns its
visible text plus every link on the page, with links that look like an actual
downloadable document (by file extension or surrounding wording) flagged and
listed first. This is the "read/browse a page" half of a Playwright-only
search-and-browse loop -- paired with PlaywrightGoogleSearchTool for the
"search" half -- so neither step needs the `requests` library, a paid search
API, or the existing requests-based SimpleTextBrowser.
If the URL itself resolves directly to a non-HTML file (a PDF, DOCX, etc.),
that's reported immediately as "this URL IS the document" instead of trying to
scrape it as a web page -- the agent doesn't need to visit it a second time.
"""
name = "playwright_visit_page"
description = (
"Opens a URL with a real browser (Playwright) and returns the page's visible text plus "
"every link found on it, with links that look like an actual downloadable document file "
"(PDF/DOC/DOCX/TXT, or wording like 'Download'/'Full text'/'View authorised version') "
"flagged with a leading '⬇️ DOWNLOAD?' marker and listed first. Use this to read a search "
"result page, then call it again on any flagged link found on that page to go one level "
"deeper (e.g. from a government 'Details' page to the actual PDF it links to). If the URL "
"you pass in is itself already a direct file (not an HTML page), this tool reports that "
"immediately instead of trying to scrape it as a web page."
)
inputs = {
"url": {"type": "string", "description": "The exact URL to open (from a search result or a link found on a previously visited page)."},
}
output_type = "string"
def __init__(
self,
headless: bool = False,
timeout_ms: int = 20000,
max_text_chars: int = 5000,
max_links: int = 40,
):
super().__init__()
self.headless = headless
self.timeout_ms = timeout_ms
self.max_text_chars = max_text_chars
self.max_links = max_links
def forward(self, url: str) -> str:
try:
from playwright.sync_api import sync_playwright
except ImportError as e:
raise ImportError(
"PlaywrightVisitPageTool needs the `playwright` package and its browser "
"binaries. Install with:\n"
" pip install playwright\n"
" playwright install chromium"
) from e
url = (url or "").strip()
if not url:
return "Error: empty URL."
if not (url.startswith("http://") or url.startswith("https://")):
return f"Error: '{url}' is not an http(s) URL."
with sync_playwright() as p:
browser = p.chromium.launch(
headless=self.headless,
args=["--disable-blink-features=AutomationControlled"],
)
try:
context = browser.new_context(
user_agent=_USER_AGENT,
locale="en-US",
viewport={"width": 1366, "height": 900},
extra_http_headers={"Accept-Language": "en-US,en;q=0.9"},
accept_downloads=True,
)
context.add_init_script(_ANTI_DETECTION_INIT_SCRIPT)
page = context.new_page()
try:
response = page.goto(url, timeout=self.timeout_ms, wait_until="domcontentloaded")
except Exception as e:
# A direct file link (e.g. a PDF) sometimes triggers Playwright's own
# download handling rather than a normal navigation, which surfaces as
# an exception here rather than a response -- treat that as a strong
# signal this URL IS a downloadable file, not a real navigation failure.
if "Download is starting" in str(e):
return (
f"'{url}' triggered a file download when opened -- this URL IS the "
"document itself (not an HTML landing page). Use it directly as the "
"document's URL; no further browsing of this link is needed."
)
return f"Error: could not load '{url}': {e}"
status = response.status if response else None
if status and status >= 400:
return f"Error: '{url}' returned HTTP {status}."
content_type = (response.headers.get("content-type", "") if response else "").lower()
if content_type and "html" not in content_type and "text/plain" not in content_type:
cl = response.headers.get("content-length") if response else None
size_note = f", {cl} bytes" if cl and cl.isdigit() else ""
return (
f"'{url}' is itself a direct downloadable file (Content-Type: "
f"{content_type}{size_note}). This URL IS the document -- no further "
"browsing of this link is needed."
)
# Best-effort settle for JS-rendered content -- keep going even if the page
# never truly goes idle (some sites keep long-poll/analytics connections open).
try:
page.wait_for_load_state("networkidle", timeout=min(self.timeout_ms, 8000))
except Exception:
pass
data = page.evaluate(
"""
([downloadExtRe, downloadKeywordRe]) => {
const extRe = new RegExp(downloadExtRe, 'i');
const kwRe = new RegExp(downloadKeywordRe, 'i');
const seen = new Set();
const links = [];
document.querySelectorAll('a[href^="http"]').forEach(a => {
const href = a.href;
if (!href || seen.has(href)) return;
const text = (a.innerText || a.textContent || '').trim().replace(/\\s+/g, ' ');
if (!text && !extRe.test(href)) return;
seen.add(href);
const likelyDownload = extRe.test(href) || kwRe.test(href) || kwRe.test(text);
links.push({ href, text: text.slice(0, 120), likelyDownload });
});
return {
title: document.title || '',
text: document.body ? document.body.innerText : '',
links,
};
}
""",
[_DOWNLOAD_EXT_RE, _DOWNLOAD_KEYWORD_RE],
)
finally:
browser.close()
title = data.get("title", "") or url
text = (data.get("text", "") or "").strip()
if len(text) > self.max_text_chars:
text = text[: self.max_text_chars] + "\n...[truncated]"
links = data.get("links", [])
flagged = [ln for ln in links if ln.get("likelyDownload")]
other = [ln for ln in links if not ln.get("likelyDownload")]
shown = (flagged + other)[: self.max_links]
lines = [f"## Page: {title}\nURL: {url}\n", "### Content\n", text or "(no visible text extracted)", ""]
lines.append(f"### Links found on this page ({len(links)} total, showing {len(shown)})")
if flagged:
lines.append(f"({len(flagged)} flagged as possible document downloads -- listed first)")
for i, ln in enumerate(shown, start=1):
marker = "⬇️ DOWNLOAD? " if ln.get("likelyDownload") else ""
label = ln.get("text") or ln.get("href")
lines.append(f"{i}. {marker}[{label}]({ln.get('href')})")
_save_page_cache(url, title, text)
return "\n".join(lines)
# ---------------------------------------------------------------------------
# PlaywrightExtractLegalDocumentLinksTool
#
# Purpose: a dedicated "extract every link, then score/rank it against my
# target topic" step -- run BEFORE opening individual candidate pages one by
# one. Many government/legal-register sites (results listings, regulator
# publication pages, gazette indexes) are JavaScript-rendered, so a plain
# `requests`-based link scrape misses most or all of the real links; this
# reuses the same Playwright browser the rest of this module already drives.
#
# Deliberately a SEPARATE tool from PlaywrightVisitPageTool rather than a mode
# flag on it: PlaywrightVisitPageTool's job is "read this one page's content +
# its links"; this tool's job is "given a page, tell me which of its links are
# actually worth opening for a SPECIFIC target topic" -- it takes a
# topic_keywords argument and returns a ranked, scored list, not raw content.
# Named specifically (not "playwright_extract_links") so it's unambiguous next
# to playwright_visit_page / playwright_duckduckgo_search / playwright_google_search
# in a tool list, and so the agent doesn't confuse it with a generic scraper.
# ---------------------------------------------------------------------------
class PlaywrightExtractLegalDocumentLinksTool(Tool):
"""Opens a URL with a real browser (Playwright -- required for JavaScript-
rendered listing/index pages a plain HTTP request can't see the links on),
extracts every link on the page, scores each one for relevance against a
target legal topic (keyword overlap with the link's visible text/URL, plus
a bonus for links that look like an actual downloadable document file or
carry download-style wording), and returns a ranked list -- most relevant
first -- instead of a flat, unordered dump of every link on the page.
Use this BEFORE opening individual candidate pages one by one: run it on a
search-result page or a regulator's publications/listing page, look at the
top-ranked links, and only then call `playwright_visit_page` on the ones
that actually look relevant. If it reports zero links at all (a page with
no outbound links, or a direct file URL), fall back to reading the page's
own content with `playwright_visit_page` instead.
"""
name = "playwright_extract_legal_document_links"
description = (
"Opens a URL with a real browser (Playwright) and extracts every link on the page, then "
"scores and ranks each link by how relevant it looks to a target legal topic you specify "
"(keyword overlap with the link's visible text/URL, plus a bonus for links that look like "
"an actual downloadable document file -- PDF/DOC/DOCX/TXT -- or carry wording like "
"'Download'/'Full text'/'View authorised version'). Returns the top-ranked links first, "
"each with its relevance score, so you can decide which ones are actually worth opening "
"before visiting them one by one -- use this BEFORE playwright_visit_page on a search-"
"result page, a regulator's publications/listing page, or any other page likely to link "
"out to several documents. Needs a real browser because many such pages are JavaScript-"
"rendered and a plain HTTP request can't see their links at all. If this reports zero "
"links (e.g. the URL is itself a direct file, or a page with no outbound links), fall "
"back to reading the page's own content with playwright_visit_page instead."
)
inputs = {
"url": {"type": "string", "description": "The exact URL of the page whose links you want to extract and rank."},
"topic_keywords": {
"type": "string",
"description": (
"Short, plain keywords describing the legal document/topic you're looking for, e.g. "
"'cross-border data policy Cambodia' or 'data protection act Philippines'. Used to "
"score each link's relevance -- keep it short, the same way you'd phrase a search query."
),
},
}
output_type = "string"
def __init__(
self,
headless: bool = False,
timeout_ms: int = 20000,
max_links_extracted: int = 200,
max_links_shown: int = 25,
):
super().__init__()
self.headless = headless
self.timeout_ms = timeout_ms
self.max_links_extracted = max_links_extracted
self.max_links_shown = max_links_shown
@staticmethod
def _score_link(text: str, href: str, keywords: list[str]) -> int:
"""Cheap, deterministic relevance score -- no LLM call. Counts keyword
hits in the link's visible text and URL (text hits weighted higher,
since a link's own wording is a stronger relevance signal than
incidental words in its URL path), plus a flat bonus for anything that
already looks like a direct document download (by extension or
surrounding wording, reusing this module's own download-detection
regexes so the signal is consistent with playwright_visit_page)."""
import re as _re
text_l = (text or "").lower()
href_l = (href or "").lower()
score = 0
for kw in keywords:
kw = kw.lower().strip()
if not kw:
continue
if kw in text_l:
score += 3
if kw in href_l:
score += 1
if _re.search(_DOWNLOAD_EXT_RE, href_l):
score += 5
if _re.search(_DOWNLOAD_KEYWORD_RE, href_l) or _re.search(_DOWNLOAD_KEYWORD_RE, text_l):
score += 3
return score
def forward(self, url: str, topic_keywords: str) -> str:
try:
from playwright.sync_api import sync_playwright
except ImportError as e:
raise ImportError(
"PlaywrightExtractLegalDocumentLinksTool needs the `playwright` package and its "
"browser binaries. Install with:\n"
" pip install playwright\n"
" playwright install chromium"
) from e
url = (url or "").strip()
if not url:
return "Error: empty URL."
if not (url.startswith("http://") or url.startswith("https://")):
return f"Error: '{url}' is not an http(s) URL."
keywords = [w for w in (topic_keywords or "").replace(",", " ").split() if len(w) > 2]
with sync_playwright() as p:
browser = p.chromium.launch(
headless=self.headless,
args=["--disable-blink-features=AutomationControlled"],
)
try:
context = browser.new_context(
user_agent=_USER_AGENT,
locale="en-US",
viewport={"width": 1366, "height": 900},
extra_http_headers={"Accept-Language": "en-US,en;q=0.9"},
accept_downloads=True,
)
context.add_init_script(_ANTI_DETECTION_INIT_SCRIPT)
page = context.new_page()
try:
response = page.goto(url, timeout=self.timeout_ms, wait_until="domcontentloaded")
except Exception as e:
if "Download is starting" in str(e):
return (
f"'{url}' triggered a file download when opened -- this URL IS a document "
"itself, not a listing/index page with links to extract. Use it directly as "
"a candidate document; there are no links to rank here."
)
return f"Error: could not load '{url}': {e}"
status = response.status if response else None
if status and status >= 400:
return f"Error: '{url}' returned HTTP {status}."
content_type = (response.headers.get("content-type", "") if response else "").lower()
if content_type and "html" not in content_type and "text/plain" not in content_type:
return (
f"'{url}' is itself a direct downloadable file (Content-Type: {content_type}). "
"This URL IS a document -- there are no links to extract/rank here."
)
try:
page.wait_for_load_state("networkidle", timeout=min(self.timeout_ms, 8000))
except Exception:
pass
data = page.evaluate(
"""
() => {
const seen = new Set();
const links = [];
document.querySelectorAll('a[href^="http"]').forEach(a => {
const href = a.href;
if (!href || seen.has(href)) return;
const text = (a.innerText || a.textContent || '').trim().replace(/\\s+/g, ' ');
seen.add(href);
links.push({ href, text: text.slice(0, 160) });
});
return { title: document.title || '', links };
}
"""
)
finally:
browser.close()
title = data.get("title", "") or url
links = data.get("links", [])[: self.max_links_extracted]
if not links:
return (
f"'{url}' (page: {title}) has no outbound http(s) links to extract. Fall back to "
"reading this page's own content with playwright_visit_page instead."
)
scored = []
for ln in links:
href, text = ln.get("href", ""), ln.get("text", "")
scored.append((self._score_link(text, href, keywords), href, text))
scored.sort(key=lambda t: t[0], reverse=True)
shown = scored[: self.max_links_shown]
n_relevant = sum(1 for s, _, _ in scored if s > 0)
lines = [
f"## Links extracted from: {title}\nURL: {url}\n",
f"Keywords used for scoring: {', '.join(keywords) if keywords else '(none given)'}\n",
f"### Ranked links ({len(links)} total found, {n_relevant} scored relevant, showing top {len(shown)})\n",
"Open the highest-scoring links first with playwright_visit_page. A score of 0 means no "
"keyword or download signal matched at all -- usually site navigation/boilerplate, not a "
"candidate document.\n",
]
for i, (score, href, text) in enumerate(shown, start=1):
label = text or href
lines.append(f"{i}. [score={score}] [{label}]({href})")
if n_relevant == 0:
lines.append(
"\nNote: nothing on this page scored above 0 for the given keywords -- consider a "
"different topic_keywords phrasing, or fall back to reading the page's own content "
"with playwright_visit_page in case the relevant text (not a link) is on this page "
"itself."
)
return "\n".join(lines)
class PlaywrightReadEmbeddedPdfTool(Tool):
"""Opens a URL using Playwright, scans the page DOM to identify any embedded PDF files
(via iframe, embed, or object tags, or direct PDF download links), downloads the PDF,
and extracts its text content using pdfplumber to return to the agent.
"""
name = "playwright_read_embedded_pdf"
description = (
"Opens a webpage URL using Playwright, scans the DOM to identify any embedded PDF files "
"(in iframes, embed/object tags, or direct PDF links), downloads the PDF, and extracts "
"its text content using pdfplumber. Use this tool if you suspect a page contains an "
"embedded PDF viewer displaying document text that isn't captured by normal page reading."
)
inputs = {
"url": {"type": "string", "description": "The URL of the webpage that contains the embedded PDF."},
}
output_type = "string"
def __init__(
self,
headless: bool = False,
timeout_ms: int = 20000,
max_pdf_chars: int = 25000,
):
super().__init__()
self.headless = headless
self.timeout_ms = timeout_ms
self.max_pdf_chars = max_pdf_chars
def forward(self, url: str) -> str:
try:
from playwright.sync_api import sync_playwright
except ImportError as e:
raise ImportError(
"PlaywrightReadEmbeddedPdfTool needs the `playwright` package. Install with:\n"
" pip install playwright\n"
" playwright install chromium"
) from e
import requests
import tempfile
import os
import pdfplumber # MIT — replaced PyMuPDF (AGPL) for Store distribution
import urllib.parse
url = (url or "").strip()
if not url:
return "Error: empty URL."
# If the input URL is already a PDF, process it directly
if url.lower().endswith(".pdf"):
pdf_urls = [url]
page_title = "Direct PDF Link"
else:
if not (url.startswith("http://") or url.startswith("https://")):
return f"Error: '{url}' is not an http(s) URL."
pdf_urls = []
page_title = url
with sync_playwright() as p:
browser = p.chromium.launch(
headless=self.headless,
args=["--disable-blink-features=AutomationControlled"],
)
try:
context = browser.new_context(
user_agent=_USER_AGENT,
locale="en-US",
viewport={"width": 1366, "height": 900},
extra_http_headers={"Accept-Language": "en-US,en;q=0.9"},
accept_downloads=True,
)
context.add_init_script(_ANTI_DETECTION_INIT_SCRIPT)
page = context.new_page()
try:
response = page.goto(url, timeout=self.timeout_ms, wait_until="domcontentloaded")
page_title = page.title() or url
except Exception as e:
if "Download is starting" in str(e):
# The page URL itself triggered a direct download
pdf_urls = [url]
else:
return f"Error: could not load '{url}': {e}"
if not pdf_urls:
# Scan the DOM for embedded PDFs
detected = page.evaluate(
"""
() => {
const urls = new Set();
// Check iframes (common for PDF.js or direct PDF embed)
document.querySelectorAll('iframe').forEach(el => {
const src = el.src || '';
if (!src) return;
if (src.toLowerCase().includes('.pdf')) {
urls.add(src);
}
// Try extracting from common PDF viewer query params like viewer.html?file=URL
const fileParam = src.match(/[?&]file=([^&]+)/);
if (fileParam) {
try { urls.add(decodeURIComponent(fileParam[1])); } catch(err) {}
}
});
// Check embed tags
document.querySelectorAll('embed').forEach(el => {
const src = el.src || '';
if (src && (src.toLowerCase().includes('.pdf') || (el.type || '').toLowerCase() === 'application/pdf')) {
urls.add(src);
}
});
// Check object tags
document.querySelectorAll('object').forEach(el => {
const data = el.data || '';
if (data && (data.toLowerCase().includes('.pdf') || (el.type || '').toLowerCase() === 'application/pdf')) {
urls.add(data);
}
});
// Check links that look like PDFs
document.querySelectorAll('a[href]').forEach(el => {
const href = el.href || '';
const text = (el.innerText || el.textContent || '').trim().toLowerCase();
if (href.toLowerCase().includes('.pdf') || text.includes('view pdf') || text.includes('download pdf')) {
urls.add(href);
}
});
return Array.from(urls);
}
"""
)
# Resolve absolute URLs
for u in detected:
resolved = urllib.parse.urljoin(url, u)
if resolved not in pdf_urls:
pdf_urls.append(resolved)
finally:
browser.close()
if not pdf_urls:
return f"No embedded PDFs or direct PDF links found on webpage: '{url}'."
# Fetch and extract text from the detected PDFs (up to 3 to avoid excessive time/text limit issues)
lines = [f"## Webpage Analyzed: {page_title}", f"URL: {url}", f"Detected {len(pdf_urls)} embedded PDF(s). Processing..."]
for idx, pdf_url in enumerate(pdf_urls[:3], 1):
lines.append(f"\n--- PDF #{idx}: {pdf_url} ---")
temp_path = None
try:
headers = {"User-Agent": _USER_AGENT}
res = requests.get(pdf_url, headers=headers, timeout=20, stream=True)
if res.status_code >= 400:
lines.append(f"Error downloading PDF: HTTP Status {res.status_code}")
continue
# Write to temp file
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tf:
for chunk in res.iter_content(chunk_size=8192):
tf.write(chunk)
temp_path = tf.name
# Extract text using pdfplumber (MIT)
pdf_text_parts = []
with pdfplumber.open(temp_path) as pdf:
for page in pdf.pages:
page_text = page.extract_text() or ""
pdf_text_parts.append(page_text)
if sum(len(x) for x in pdf_text_parts) > self.max_pdf_chars:
pdf_text_parts.append("\n...[truncated due to length limit]...")
break
extracted_text = "\n".join(pdf_text_parts).strip()
if extracted_text:
lines.append(extracted_text)
else:
lines.append("(No text could be extracted from this PDF -- it might be scanned image pages)")
except Exception as pdf_err:
lines.append(f"Failed to process PDF: {pdf_err}")
finally:
if temp_path and os.path.exists(temp_path):
try:
os.remove(temp_path)
except:
pass
return "\n".join(lines)
# ── Shared page state for navigation tools ──────────────────────────
# PlaywrightVisitPageTool caches the last-visited page here so
# PageUp/PageDown/FindOnPage/FindNext can navigate within its content
# without re-launching a browser.
_page_cache = {
"url": None,
"title": None,
"full_text": "",
"viewport_pos": 0,
"viewport_size": 2000,
"find_query": None,
"find_last_viewport": None,
}
def _save_page_cache(url, title, text):
_page_cache["url"] = url
_page_cache["title"] = title
_page_cache["full_text"] = text or ""
_page_cache["viewport_pos"] = 0
_page_cache["find_query"] = None
_page_cache["find_last_viewport"] = None
def _format_viewport(cache):
total = len(cache["full_text"])
vsize = cache["viewport_size"]
pos = cache["viewport_pos"]
total_pages = max(1, (total + vsize - 1) // vsize)
current_page = pos // vsize + 1
content = cache["full_text"][pos:pos + vsize]
return (
f"Address: {cache['url']}\n"
f"Title: {cache['title']}\n"
f"Viewport position: Showing page {current_page} of {total_pages}.\n"
f"=======================\n"
f"{content}"
)
class PlaywrightPageDownTool(Tool):
name = "playwright_page_down"
description = "Scroll the viewport DOWN one page-length in the currently visited page and return the new viewport content."
inputs = {}
output_type = "string"
def forward(self) -> str:
cache = _page_cache
if not cache["url"]:
return "No page has been visited yet. Use playwright_visit_page first."
total = len(cache["full_text"])
cache["viewport_pos"] = min(cache["viewport_pos"] + cache["viewport_size"], max(0, total - 1))
return _format_viewport(cache)
class PlaywrightPageUpTool(Tool):
name = "playwright_page_up"
description = "Scroll the viewport UP one page-length in the currently visited page and return the new viewport content."
inputs = {}
output_type = "string"
def forward(self) -> str:
cache = _page_cache
if not cache["url"]:
return "No page has been visited yet. Use playwright_visit_page first."
cache["viewport_pos"] = max(cache["viewport_pos"] - cache["viewport_size"], 0)
return _format_viewport(cache)
class PlaywrightFindOnPageTool(Tool):
name = "playwright_find_on_page"
description = "Scroll the viewport to the first occurrence of the search string. This is equivalent to Ctrl+F on the currently visited page."
inputs = {
"search_string": {
"type": "string",
"description": "The string to search for on the page. Supports wildcards like '*'.",
}
}
output_type = "string"
def forward(self, search_string: str) -> str:
cache = _page_cache
if not cache["url"]:
return "No page has been visited yet. Use playwright_visit_page first."
import re
query = re.sub(r"\*", ".*", re.escape(search_string))
full = cache["full_text"]
match = re.search(query, full, re.IGNORECASE)
if not match:
cache["find_query"] = search_string
cache["find_last_viewport"] = None
return (
f"Address: {cache['url']}\n"
f"Title: {cache['title']}\n"
f"=======================\n"
f"The search string '{search_string}' was not found on this page."
)
pos = match.start()
vsize = cache["viewport_size"]
cache["viewport_pos"] = max(0, pos - vsize // 4)
cache["find_query"] = search_string
cache["find_last_viewport"] = cache["viewport_pos"]
return _format_viewport(cache)
class PlaywrightFindNextTool(Tool):
name = "playwright_find_next"
description = "Scroll the viewport to the next occurrence of the search string. Use after playwright_find_on_page."
inputs = {}
output_type = "string"
def forward(self) -> str:
cache = _page_cache
if not cache["url"]:
return "No page has been visited yet. Use playwright_visit_page first."
if not cache["find_query"]:
return "No active search. Use playwright_find_on_page first."
import re
query = re.sub(r"\*", ".*", re.escape(cache["find_query"]))
full = cache["full_text"]
start = cache["viewport_pos"] + cache["viewport_size"]
if cache["find_last_viewport"] is not None and cache["find_last_viewport"] >= start:
start = cache["find_last_viewport"] + 1
if start >= len(full):
start = 0
match = re.search(query, full[start:], re.IGNORECASE)
if not match:
cache["find_last_viewport"] = None
return (
f"Address: {cache['url']}\n"
f"Title: {cache['title']}\n"
f"=======================\n"
f"No more occurrences of '{cache['find_query']}' found."
)
pos = start + match.start()
vsize = cache["viewport_size"]
cache["viewport_pos"] = max(0, pos - vsize // 4)
cache["find_last_viewport"] = cache["viewport_pos"]
return _format_viewport(cache)
class PlaywrightArchiveSearchTool(Tool):
name = "playwright_find_archived_url"
description = "Given a url, searches the Wayback Machine and returns the archived version of the url closest to the desired date. Use this when a page is dead, blocked, or has changed since the date you care about."
inputs = {
"url": {
"type": "string",
"description": "The url you need the archive for.",
},
"date": {
"type": "string",
"description": "The date to find the archive for, in 'YYYYMMDD' format (e.g. '27 June 2008' → '20080627').",
"nullable": True,
},
}
output_type = "string"
def forward(self, url: str, date: str | None = None) -> str:
import requests
no_timestamp_url = f"https://archive.org/wayback/available?url={urllib.parse.quote(url)}"
archive_url = no_timestamp_url + (f"×tamp={date}" if date else "")
try:
response = requests.get(archive_url, timeout=30).json()
except Exception as e:
return f"Error querying Wayback Machine: {e}"
if "archived_snapshots" in response and "closest" in response["archived_snapshots"]:
closest = response["archived_snapshots"]["closest"]
else:
try:
response2 = requests.get(no_timestamp_url, timeout=30).json()
if "archived_snapshots" in response2 and "closest" in response2["archived_snapshots"]:
closest = response2["archived_snapshots"]["closest"]
else:
return f"No archive found for '{url}' on Wayback Machine."
except Exception as e:
return f"Error querying Wayback Machine: {e}"
target_url = closest["url"]
snapshot_date = closest["timestamp"][:8] if "timestamp" in closest else "unknown"
return (
f"Web archive for url {url}, snapshot taken at date {snapshot_date}:\n"
f"Archived URL: {target_url}\n\n"
f"To view this archived page, call playwright_visit_page with the archived URL above."
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823"""
rag_agent.py — Agentic RAG via a smolagents manager + search sub-agent.
Architecture (manager / sub-agent):
* MANAGER — a ToolCallingAgent that ANALYZES the user's question (intent,
meaning, keywords) instead of literally pasting it into a search, then
decomposes it into 1-3 focused search tasks and delegates each one to the
`knowledge_searcher` sub-agent. It never queries the knowledge base
directly — it only reasons and directs.
* SUB-AGENT (`knowledge_searcher`) — a ToolCallingAgent holding ONLY the
`retriever` tool. Given a focused task from the manager, it runs the
retriever SEVERAL times, deliberately rephrasing the query on every
iteration (synonyms, reordering, narrowing/broadening) so it never repeats
the same search wording, then returns a findings report with source tags.
This replaces the older single-agent design (one agent holding the retriever
tool and deciding on its own) — which tended to paste the user's whole
verbatim sentence into `retriever`, producing noisy semantic matches.
IMPORTANT CAVEAT: tool-calling reliability still depends heavily on the
underlying model. `google/gemma-4-E2B-it` (the app's default LLM) is small
enough that the manager may delegate poorly or the sub-agent may call
`retriever` in a malformed way. If agentic RAG Chat seems to ignore the
knowledge base, switch to a larger model (e.g. Gemma-4-E4B or above).
"""
import re
import threading
import types
from typing import Optional
from agents import agent_streaming
from agents.agent_factory import build_smol_agent
from backend import model_registry as mr
from backend import models
from backend.knowledge_base import (
DocumentSummaryTool,
KeyPointsTool,
ListTopicsTool,
MindMapTool,
RetrieverTool,
SubthemeSummaryTool,
ThemeSummaryTool,
VisualRetrieverTool,
reset_visual_tool_hits,
)
from ui import i18n
_rag_agent = None
_rag_agent_model_id = None
_rag_agent_theme = ""
_rag_agent_subtheme = ""
_rag_agent_sources = []
_rag_agent_max_steps = 6
_rag_agent_searcher_max_steps = None
_rag_agent_execution_timeout = None
_rag_agent_n_ctx = None
_rag_agent_visual_retrieval = False
_rag_tool = None
_rag_visual_tool = None
_rag_summary_tools = []
_rag_agent_lock = threading.Lock()
# ──────────────────────────────────────────────────────────────────
# Sub-agent identity (required by smolagents' managed_agents machinery).
# ──────────────────────────────────────────────────────────────────
SEARCHER_AGENT_NAME = "knowledge_searcher"
SEARCHER_AGENT_DESCRIPTION = (
"Runs focused semantic searches over document text in the user's indexed knowledge base "
"and returns a findings report with source tags. Call with task='search query keywords' "
"(e.g. knowledge_searcher(task='contract summary')). Describe WHAT to look for. "
"Never call for listing themes/topics — use list_knowledge_base_topics directly instead."
)
# The manager's VISUAL-INDEX RULE paragraph. It is appended to
# STRICT_SYSTEM_INSTRUCTIONS ONLY when RAG visual retrieval is enabled —
# the rule teaches the manager to delegate scanned/image-heavy docs to the
# searcher's `visual_retriever` tool, which does not exist when the toggle
# is OFF (offering a rule for a tool the agent can never call wastes steps).
RAG_MANAGER_VISUAL_RULE = (
"VISUAL-INDEX RULE (scanned / image-heavy documents):\n"
"- A summarization tool's output may mark a source as having page images in the visual index ('🖼️ Page images available in the visual index'), or the extracted text may be unreadable OCR (e.g. `(cid:123)` fragments). Both mean the document's REAL content lives in its PAGE IMAGES — the text chunks are unreliable.\n"
"- In that case DO NOT conclude the knowledge base lacks information and DO NOT answer from the garbled text alone. DELEGATE to `knowledge_searcher` with an explicit task: 'use `visual_retriever` to search the page images for <what the user wants> (e.g. the document's title, date, issuer, key clauses)' and tell it to report what the PAGE IMAGES show. The retrieved pages are then read by the multimodal grounding pass.\n"
"- For summaries of scanned documents, ALWAYS add such a `knowledge_searcher` visual task before writing the final answer — the visual pages are the authoritative source.\n\n"
)
# ──────────────────────────────────────────────────────────────────
# Strict grounding — layer 1: agent-level system instructions (applied
# once, at agent construction, if this smolagents version supports it).
# ──────────────────────────────────────────────────────────────────
STRICT_SYSTEM_INSTRUCTIONS = (
"You are a retrieval research manager. You answer the user's question "
"using ONLY the user's own indexed knowledge base — never your own "
"general knowledge or training data, even if you believe you know the "
"answer.\n\n"
"Available tools to you as the manager:\n"
"- `knowledge_searcher`: sub-agent that executes semantic searches over document text.\n"
"- `list_knowledge_base_topics`: lists all indexed themes, subthemes, and filenames directly from metadata.\n"
"- `summarize_theme`: produces a comprehensive summary of a specific theme.\n"
"- `summarize_subtheme`: produces a summary of a specific subtheme under a theme.\n"
"- `summarize_document`: produces a summary of a specific document by its source filename.\n"
"- `find_key_points`: extracts top takeaways/highlights for a theme, subtheme, or document.\n"
"- `create_mind_map`: generates a concept tree or Mermaid diagram outline of topics.\n\n"
"METADATA VS SEMANTIC SEARCH RULE:\n"
"- Themes, subthemes, and filenames are METADATA. NEVER delegate metadata queries (like 'what themes exist', 'list subthemes', or 'available files') to `knowledge_searcher` — use `list_knowledge_base_topics` directly instead.\n"
"- When the user asks for a summary, overview, or highlights of a theme, subtheme, or document, call the corresponding summarization tool (`summarize_theme`, `summarize_subtheme`, `summarize_document`, `find_key_points`) directly to obtain the full structured outline. If deeper details on specific sub-topics are needed, you may also run focused searches via `knowledge_searcher`.\n"
"- For questions about factual information, facts, or concepts inside documents, analyze the question and delegate focused keyword search tasks to `knowledge_searcher`.\n\n"
+ RAG_MANAGER_VISUAL_RULE
+ "Work like this:\n"
"1. ANALYZE the user's question first: identify the core INTENT, the key entities/concepts, and whether it asks for a summary of a theme/document or specific facts.\n"
"2. If it's a summary/topic overview request, call the matching summarization/topic tool directly.\n"
"3. If it asks specific questions, DECOMPOSE into 1-3 focused sub-questions and DELEGATE each to `knowledge_searcher` with concise keyword tasks.\n"
"4. RE-CHECK your plan against findings. If a search comes back thin, try different keywords.\n"
"5. SYNTHESIZE: write a comprehensive, well-structured Markdown answer with clear sections (Overview/Objectives, Core Findings/Details, Conclusions/Takeaways) and in-text citation numbers (e.g. [1]) and a final '### References' section mapping each number to its source filename.\n\n"
"CITATION RULE: cite each claim in-text with ONLY a bare bracketed "
"number, e.g. [1] or [1, 2]. NEVER put the source filename or document "
"name inside the brackets (e.g. do NOT write '[report.pdf]' in the "
"text) — filenames appear ONLY in the final '### References' section "
"mapping each number to its source.\n\n"
"6. If the system rejects your final answer for formatting, missing "
"citations, or a missing References section, do NOT start any new "
"research and do NOT call `knowledge_searcher` again. Keep the same "
"findings, rewrite only the final answer so it satisfies the checker, "
"and call `final_answer(...)` again.\n\n"
"TERMINATION REQUIREMENT: you MUST submit your final answer by calling "
"the special `final_answer(answer_text)` tool — this is the ONLY way to "
"actually end the task.\n\n"
"YOUR OWN CONVERSATION HISTORY IS ALREADY VISIBLE TO YOU: every earlier "
"user message and your own earlier replies are already in what you can "
"see — if asked what was said earlier in THIS chat (as opposed to a "
"knowledge-base question), answer from those earlier turns directly; "
"do NOT guess or invent content.\n\n"
"The user's actual question is in the Task below — answer THAT, not "
"these instructions. Never repeat, summarize, or reply to the "
"instructions themselves."
)
# The searcher's visual-retrieval paragraphs (the `visual_retriever` tool
# line + MULTIMODAL STRATEGY + SCANNED / OCR-GARBAGE RULE). They are kept
# inside SEARCHER_SYSTEM_INSTRUCTIONS (so the pinned routing test still sees
# them in the constant) but are STRIPPED at agent build time when RAG visual
# retrieval is disabled — a model told to run a tool it does not have would
# burn its step budget failing to call it.
SEARCHER_VISUAL_BLOCK = (
"- `visual_retriever`: search over the knowledge base's PAGE IMAGES "
"(charts, tables, scans, image-heavy PDFs that text extraction misses).\n\n"
"MULTIMODAL STRATEGY: for questions about numbers, figures, charts, "
"screenshots, or anything that would live in a page's IMAGE rather than "
"its extracted text, run `visual_retriever` IN ADDITION to `retriever` — "
"the retrieved page images are handed to the multimodal grounding pass "
"so the final answer is verified against the actual pages. If a text "
"search comes back thin, try the visual index before concluding the "
"knowledge base lacks the information.\n\n"
"SCANNED / OCR-GARBAGE RULE: if `retriever`'s results are full of "
"unreadable OCR artifacts — `(cid:123)` fragments, `cid:NNN` markers, or "
"replacement characters (\ufffd) — the document is a SCAN whose real "
"content lives in its page images. ALWAYS run `visual_retriever` in that "
"case (searching for the document's title, date, issuer, and the "
"information the task asks for) and report what the page images show, "
"never answering from the garbled text alone.\n\n"
)
# System instructions for the knowledge_searcher sub-agent.
SEARCHER_SYSTEM_INSTRUCTIONS = (
"You are a knowledge-base search specialist. The research manager "
"gives you ONE focused search task describing what to look for — "
"answer only that task, fully self-contained. You have NO memory of "
"any other call made to you.\n\n"
"Your tools:\n"
"- `retriever`: semantic search over the knowledge base's TEXT chunks.\n"
"- `visual_retriever`: search over the knowledge base's PAGE IMAGES "
"(charts, tables, scans, image-heavy PDFs that text extraction misses).\n\n"
"MULTIMODAL STRATEGY: for questions about numbers, figures, charts, "
"screenshots, or anything that would live in a page's IMAGE rather than "
"its extracted text, run `visual_retriever` IN ADDITION to `retriever` — "
"the retrieved page images are handed to the multimodal grounding pass "
"so the final answer is verified against the actual pages. If a text "
"search comes back thin, try the visual index before concluding the "
"knowledge base lacks the information.\n\n"
"SCANNED / OCR-GARBAGE RULE: if `retriever`'s results are full of "
"unreadable OCR artifacts — `(cid:123)` fragments, `cid:NNN` markers, or "
"replacement characters (\ufffd) — the document is a SCAN whose real "
"content lives in its page images. ALWAYS run `visual_retriever` in that "
"case (searching for the document's title, date, issuer, and the "
"information the task asks for) and report what the page images show, "
"never answering from the garbled text alone.\n\n"
"NEGATIVE GUARD: Themes, subthemes, and file names are metadata attributes, "
"not document body text. Never search for queries like 'available themes', "
"'list of subthemes', or 'list of documents' — search only for factual concepts "
"and information described in the documents.\n\n"
"SEARCH STRATEGY — DIVERSIFY EVERY QUERY:\n"
"1. Extract the essential keywords from the task (drop filler words).\n"
"2. Run `retriever` with a keyword-focused query FIRST.\n"
"3. Then run 1-3 MORE searches, each with a DIFFERENT formulation than "
"the previous one:\n"
" - a paraphrase using synonyms,\n"
" - the same terms in a different order,\n"
" - a narrower query focused on a single entity/aspect,\n"
" - a broader query if the narrow ones return nothing.\n"
" NEVER call `retriever` twice with the same query string.\n"
"4. Stop once you have enough evidence, or after about 4 varied "
"searches.\n\n"
"REPORT: return a concise findings report listing what you found, "
"tagging each item with its source filename (e.g. 'report.pdf'). If "
"nothing relevant was found, say so plainly — do not invent or guess."
)
# Visual-free variants of the two instruction sets — built ONCE at import
# time by stripping the visual blocks above. `_build_searcher_agent` /
# `_build_manager_agent` use these when RAG visual retrieval is DISABLED
# (the default), so the agents are never taught to use the `visual_retriever`
# tool (which they also never receive).
STRICT_SYSTEM_INSTRUCTIONS_NO_VISUAL = STRICT_SYSTEM_INSTRUCTIONS.replace(
RAG_MANAGER_VISUAL_RULE, ""
)
SEARCHER_SYSTEM_INSTRUCTIONS_NO_VISUAL = SEARCHER_SYSTEM_INSTRUCTIONS.replace(
SEARCHER_VISUAL_BLOCK, ""
)
# ──────────────────────────────────────────────────────────────────
# Strict grounding — layer 2: per-question task template (applied every
# call, in chat.py, via build_strict_task()).
# ─────────────────────────────────────��────────────────────────────
def _scope_display(value) -> str:
"""Render a metadata scope value as a readable comma-joined string.
The RAG tab sends theme/subtheme selections as ARRAYS (multi-select),
so a value arrives as either a single string (backward-compatible
callers) or a list. A list must never be stringified directly — `str()`
/ f-string interpolation would leak the Python list notation into the
agent's prompt (the old `Active Theme: '['ditctab2019d5_en']'`)."""
if value is None:
return ""
if isinstance(value, str):
vals = [value.strip()]
else:
vals = [str(v).strip() for v in value if v is not None and str(v).strip()]
return ", ".join(v for v in vals if v)
def build_strict_task(question: str, lang_key: str = "kh",
theme: str = "", subtheme: str = "",
sources: Optional[list] = None) -> str:
"""Wrap the user's question with explicit strict-grounding instructions
and the current active filter scope (theme/subtheme/sources)."""
scope_lines = []
theme_disp = _scope_display(theme)
if theme_disp:
scope_lines.append(f"Active Theme: {theme_disp}")
subtheme_disp = _scope_display(subtheme)
if subtheme_disp:
scope_lines.append(f"Active Subtheme: {subtheme_disp}")
if sources:
clean_srcs = [str(s) for s in sources if s]
if clean_srcs:
scope_lines.append(f"Active Sources: {', '.join(clean_srcs)}")
scope_block = ""
if scope_lines:
scope_block = (
"--- Filter Scope in Knowledge Base ---\n"
+ "\n".join(scope_lines)
+ "\n(If the user says 'this theme', 'this subtheme', or 'this document', refer to the active scope above)\n\n"
)
return (
i18n._output_lang_instruction(lang_key)
+ scope_block
+ "Answer the user's question using ONLY information retrieved "
"from the indexed knowledge base. Do not use your own general "
"knowledge, and do not guess.\n\n"
"1. ANALYZE the question: identify whether it asks for an overview/summary "
"of a theme/document or specific factual answers.\n"
"2. If the user asks for a summary, overview, topics, key points, or a mind map "
"of a theme/subtheme/document, call the corresponding tool directly "
"(`summarize_theme`, `summarize_subtheme`, `summarize_document`, "
"`find_key_points`, `create_mind_map`, `list_knowledge_base_topics`).\n"
"3. For factual questions, break into 1-3 sub-questions and call `knowledge_searcher` "
"with concise keyword search tasks.\n"
"4. If a search task returns thin results, try different keywords — never repeat the same task.\n"
"5. Write a comprehensive, well-structured Markdown answer with in-text citation numbers (e.g. [1], [2]) "
"and a '### References' section mapping each number to its source filename.\n"
"6. Submit your answer by calling `final_answer(answer_text)`. NEVER output your internal plan, list of tools to use, or problem analysis in final_answer — provide ONLY the factual response directly.\n"
"7. If the knowledge base has nothing relevant, state clearly that "
"the knowledge base doesn't contain this information — do not guess.\n\n"
+ i18n._task_conciseness_directive(lang_key)
+ "\n\n---\n"
"The user's question is:\n"
f"{question}"
)
# ──────────────────────────────────────────────────────────────────
# Strict grounding — layer 3: post-hoc verification. Doesn't rely on the
# model actually obeying the instructions above, NOR on introspecting
# smolagents' internal step/memory structure (which varies across
# versions and previously caused false "never searched" verdicts even
# when the retriever clearly ran and returned real results — see the
# CodeAgent transcript where `Out: Retrieved documents (sources: ...)`
# was printed but the old introspection still reported called=False).
#
# Instead, the RetrieverTool instance itself tracks how many times it
# was called and how many of those calls found something (see
# knowledge_base.RetrieverTool) — reset before each run, read after.
# ──────────────────────────────────────────────────────────────────
def never_searched_message(lang_key: str = "kh") -> str:
"""Bilingual guard message: the agent completed WITHOUT calling the
retriever (call_count == 0). Rendered in the UI language so a Khmer
UI never shows an English answer."""
return (
"⚠️ ខ���ញុំមិនបានស្វែងរកក្នុងមូលដ្ឋានចំណេះដឹងសម្រាប់សំណួរនេះ ដូច្នេះខ្ញុំមិនឆ្លើយទេ — "
"សូមព្យាយាមបកស្រាយសំណួររបស់អ្នកឡើងវិញ។"
if lang_key == "kh" else
"⚠️ I didn't search the knowledge base for this, so I'm not answering — "
"please try rephrasing your question."
)
def nothing_found_message(lang_key: str = "kh") -> str:
"""Bilingual guard message: the agent searched but found nothing
relevant (found_count == 0). Rendered in the UI language so a Khmer
UI never shows an English answer."""
return (
"⚠️ ខ្ញុំបានស្វែងរកក្នុងមូលដ្ឋានចំណេះដឹងរួចហើយ ប៉ុន្តែរកមិនឃើញអ្វីដែលពាក់ព័ន្ធនឹង "
"សំណួរនេះទេ ដូច្នេះខ្ញុំនឹងមិនទាយវិញទេ។ សូមព្យាយាមបកស្រាយសំណួរ ឬបញ្ចូលឯកសារដែល "
"គ្របដណ្តប់លើប្រធានបទនេះជាមុនសិន។"
if lang_key == "kh" else
"⚠️ I searched the indexed knowledge base but found nothing relevant to "
"this question, so I won't guess. Try rephrasing, or index a document "
"that covers this topic first."
)
def reset_retriever_stats():
"""Call right before agent.run() so this run's stats start from zero."""
if _rag_tool is not None:
_rag_tool.reset_stats()
if _rag_visual_tool is not None:
_rag_visual_tool.reset_stats()
for tool in _rag_summary_tools:
if hasattr(tool, "reset_stats"):
tool.reset_stats()
# Clear any page images a PREVIOUS run's visual_retriever tool calls
# stashed — this run's grounding pass must only see THIS run's pages.
reset_visual_tool_hits()
def get_retriever_stats() -> tuple:
"""Call right after agent.run() returns. Returns (call_count,
found_count, sources_used) across the retriever plus any RAG summary
tools used this run. `sources_used` is the ACTUAL set of source
filenames the tools returned this run, tracked directly by the tools
themselves rather than trusting the model's own in-text citations."""
tools = ([_rag_tool] if _rag_tool is not None else []) + \
([_rag_visual_tool] if _rag_visual_tool is not None else []) + \
list(_rag_summary_tools)
call_count = 0
found_count = 0
sources_used = set()
for tool in tools:
if tool is None:
continue
call_count += int(getattr(tool, "call_count", 0) or 0)
found_count += int(getattr(tool, "found_count", 0) or 0)
sources_used.update(set(getattr(tool, "sources_used", set()) or set()))
return call_count, found_count, sources_used
def get_visual_retriever_stats() -> tuple:
"""(call_count, found_count, pages_found) for JUST the visual_retriever
tool — the signal the chat footer uses to say "the agent actually pulled
page images this run", separate from get_retriever_stats()'s aggregate
(which mixes the text retriever, the visual tool, and the summary
tools). pages_found is the total number of page images actually decoded
across the run's successful calls. (0, 0, 0) when the visual tool was
never built."""
if _rag_visual_tool is None:
return 0, 0, 0
return (int(getattr(_rag_visual_tool, "call_count", 0) or 0),
int(getattr(_rag_visual_tool, "found_count", 0) or 0),
int(getattr(_rag_visual_tool, "pages_found", 0) or 0))
def normalize_in_text_citations(answer: str, refs) -> str:
"""Rewrite model-emitted in-text citations that carry the SOURCE NAME
(filename, URL, or page title) inside brackets OR parentheses (e.g.
'[CV Sample 1 - Data Scientist AI Specialist.pdf]',
'[https://en.wikipedia.org/wiki/2026_FIFA_World_Cup]', or '(CV Sample
1 - Data Scientist AI Specialist.pdf)') into the numbered form '[N]'
/ '(N)' that the verified References list uses.
Local GGUF models frequently ignore the "cite with a bracketed NUMBER"
instruction and paste the whole retrieved filename into the citation
marker instead. `renumber_citations` (general_agent.py) only remaps
[digits] brackets, so a [filename] / (filename) marker previously
leaked through into the rendered answer verbatim. chat.py runs this
AFTER renumber_citations and passes the RENUMBERED refs, so each
marker whose name matches a verified reference (case-insensitive
substring, either direction — same matching rule as
extract_verified_references) is replaced by that reference's FINAL
sequential number — keeping parenthesized markers in sync with the
renumbered References list. Markers that match NO verified source are
left untouched (they are not citations). Note: a model-written
numbered paren like `(3)` passes the digit guard below and is left
alone — renumber_citations only remaps [digits] brackets, so such a
paren is preserved verbatim rather than renumbered (a deliberate,
conservative choice: digits in parens are common in ordinary prose).
The parenthesized form is deliberately stricter than the bracketed
one: parentheses are common in ordinary prose (e.g. "(Core AI
Engineering)", "(see figure 2)"), so a parenthesized marker is only
treated as a citation when its content actually LOOKS like a filename
(carries a real file extension) AND matches a verified source — a
bare title mention like '(Sample 1)' stays prose.
`refs` is a list of (number, name) or (number, name1, name2) tuples:
the [(number, source_name)] shape from extract_verified_references()
(RAG — filename sources), or the [(number, title, url)] shape
renumber_citations returns for web sources (Deep Research / General
agentic — page-title AND URL). Every name in each tuple is matched,
so a bracket containing EITHER the page title OR the raw URL resolves
to that source's number.
"""
if not answer or not refs:
return answer
def _replace(match, open_ch, close_ch, require_ext):
inner = (match.group(1) or "").strip()
# Empty or already-numbered markers ([1], [1, 2], (1), (1, 2)) are
# left for renumber_citations to handle (or drop) — the filename
# scan below must never touch them.
if not inner or re.fullmatch(r"\d+(?:\s*,\s*\d+)*", inner):
return match.group(0)
# Only attempt a filename match on marker content that actually
# LOOKS like a filename — a bare '.pdf'-style extension or a long
# fragment. Without this guard, a source named 'report.pdf' would
# rewrite a legitimate prose '[pdf]' or '[report]' mention into a
# citation number (false positive). The model's real output always
# carries the full 'Name.pdf' form, which both gates below accept.
if require_ext:
# Parenthesized markers need a real file extension (e.g.
# '.pdf', '.docx') before they are even candidate citations —
# parens are prose-frequent, so a bare title mention like
# '(Sample 1)' must never match.
if not re.search(r"\.[A-Za-z0-9]{2,8}\b", inner):
return match.group(0)
elif "." not in inner and len(inner) < 8:
return match.group(0)
low = inner.lower()
for ref in refs:
num = ref[0]
# Match against EVERY name in the ref: (num, name) for
# filename sources, (num, title, url) for web sources — so a
# bracket containing the page title OR the raw URL both
# resolve to the same number.
for name in ref[1:]:
name_low = str(name or "").lower()
if name_low and (low in name_low or name_low in low):
return f"{open_ch}{num}{close_ch}"
return match.group(0)
# Bracketed citations: [filename] -> [N].
answer = re.sub(r"\[([^\[\]]+)\]",
lambda m: _replace(m, "[", "]", require_ext=False), answer)
# Parenthesized citations: (filename) -> (N), with the stricter
# extension guard above.
answer = re.sub(r"\(([^()]+)\)",
lambda m: _replace(m, "(", ")", require_ext=True), answer)
return answer
def extract_verified_references(answer: str, sources_used) -> list:
"""Parse the model's own numbered '### References' section (e.g.
'[1] report.pdf', '1. report.pdf') and keep only entries whose
filename was ACTUALLY retrieved this run (cross-checked against
sources_used from RetrieverTool) — so chat.py can render a numbered
References list whose [n] tags match the model's in-text citations,
without trusting the model to have invented sources.
Mirrors general_agent.resolve_actually_used_sources(): the model's
in-text numbers are preserved as written, so an answer citing '[1]'
in the body lines up with '[1] report.pdf' in the list below.
Falls back to numbering the actually-retrieved sources_used (in
sorted order) when the model wrote no parseable/valid references.
"""
if not sources_used:
return []
header_match = re.search(r"#{1,6}\s*(references?|ឯកសារយោង)\b", answer or "", re.IGNORECASE)
if header_match:
section = (answer or "")[header_match.end():]
entries = []
seen = set()
for line in section.splitlines():
line = line.strip()
m = re.match(r"^\[?(\d+)\]?[.:\-)]?\s*(.+)$", line)
if not m:
continue
num = int(m.group(1))
name = m.group(2).strip().strip("[]").strip()
if not name or name in seen:
continue
matched = next((s for s in sources_used if name.lower() in s.lower() or s.lower() in name.lower()), None)
if matched and matched not in seen:
entries.append((num, matched))
seen.add(matched)
if entries:
return sorted(entries, key=lambda e: e[0])
return [(i + 1, name) for i, name in enumerate(sorted(sources_used))]
RAG_AGENT_DEFAULT_MAX_STEPS = 6
SEARCHER_DEFAULT_MAX_STEPS = 5
# Deep-research-style re-planning: every N manager steps it stops and
# re-reads what the sub-agent has found so far, so it can revise its
# search plan instead of blindly executing the initial one (same
# mechanism deep_research_agent.py uses — this is what makes a research
# loop "deep" rather than a single-pass agentic chat).
RAG_PLANNING_INTERVAL = 3
# final_answer_checks validator thresholds:
# * reject an answer too short to be a real grounded report
# The verified References block is appended by chat.py from the actual
# tracked sources, so the validator no longer rejects missing refs.
MIN_FINAL_REPORT_CHARS = 150
_RAG_REFERENCES_RE = re.compile(r'#{1,6}\s*(references?|ឯកសារយោង)\b', re.IGNORECASE)
def _validate_final_report(final_answer, *_, **__) -> bool:
"""`final_answer_checks` validator for the RAG manager. Raises an
actionable Exception on rejection — smolagents surfaces the message
back to the model as feedback for its next step (see
deep_research_agent._validate_final_report for the same pattern)."""
text = str(final_answer or "").strip()
if len(text) < MIN_FINAL_REPORT_CHARS:
raise ValueError(
f"Your final answer is only {len(text)} character(s) — too "
f"short to be a real grounded answer (need at least "
f"{MIN_FINAL_REPORT_CHARS}). Write a complete Markdown "
"answer (a short introduction, a clearly-headed section per "
"sub-question you searched, and a brief conclusion), then "
"call final_answer(report_text) again with the FULL answer "
"text as the argument."
)
return True
def _scaled_max_steps(model_id: str, default_max_steps: int) -> int:
"""Larger/slower local GGUF models pay a much higher per-step cost when
a parsing loop goes wrong, so their step budget is scaled down to fail
fast instead of grinding through the full default (same reasoning as
model_registry.get_max_steps_for_model)."""
return mr.get_max_steps_for_model(model_id, default_max_steps)
# The max-steps hand-off transcript cap for the `knowledge_searcher`
# sub-agent — its findings are verbatim retrieval chunk texts (wordier than
# the Data worker's compact tables), so it gets the same larger cap as the
# Deep Research search agent.
_SEARCHER_OBS_TRANSCRIPT_CAP = 12000
def _searcher_max_steps_handoff(self, task):
"""The `knowledge_searcher`'s max-steps fallback (instance-patched onto
the agent in `_build_searcher_agent`): prefer the run's REAL retrieved
findings — the verbatim retriever tool observations (the chunk texts the
manager needs to ground its answer) — over smolagents' stock last-ditch
raw-text answer, so the manager receives what the agent actually found
instead of a leaked channel marker / envelope / code fence. Thin wrapper
over the shared agent_streaming.max_steps_findings_handoff (the same
helper the Data `data_worker` and Deep Research `web_search_agent`
use). NEVER raises."""
return agent_streaming.max_steps_findings_handoff(
self, task, cap=_SEARCHER_OBS_TRANSCRIPT_CAP)
def _build_searcher_agent(llm, tool: RetrieverTool, visual_tool: Optional[VisualRetrieverTool] = None,
model_id: str = "",
max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
use_tool_calling: bool = True,
n_ctx: Optional[int] = None):
"""Build the `knowledge_searcher` sub-agent: holds the TEXT retriever
tool PLUS the `visual_retriever` page-image tool (when a visual index
capability is available), and is deliberately told to diversify its
query wording on every search iteration. Registered as a managed_agents
entry on the manager, so smolagents exposes it to the manager as a
callable tool."""
if max_steps is None:
max_steps = _scaled_max_steps(model_id, SEARCHER_DEFAULT_MAX_STEPS)
instructions = (SEARCHER_SYSTEM_INSTRUCTIONS if visual_tool is not None
else SEARCHER_SYSTEM_INSTRUCTIONS_NO_VISUAL)
if n_ctx and n_ctx > 0:
instructions += (
f"\n\nCONTEXT BUDGET: Your effective context window is ~{n_ctx} tokens. "
"Keep searches concise and stop once you have sufficient evidence to answer "
"so observations do not overflow the context."
)
agent_tools = [tool]
if visual_tool is not None:
agent_tools.append(visual_tool)
agent = build_smol_agent(
llm,
tools=agent_tools,
max_steps=max_steps,
execution_timeout=execution_timeout,
use_tool_calling=use_tool_calling,
instructions=instructions,
extra_kwargs={
"name": SEARCHER_AGENT_NAME,
"description": SEARCHER_AGENT_DESCRIPTION,
"provide_run_summary": True,
},
)
# Max-steps hand-off (see agent_streaming.max_steps_findings_handoff):
# when the sub-agent burns its whole step budget without emitting a real
# final answer (the Muse Glimmer runs shipped a leaked `Calling tools:`
# envelope / code fence as its "answer"), the manager would receive that
# garbage — losing the retrieved chunks it needs to ground the reply.
# Deliver the run's verbatim retriever observations (the chunk texts)
# instead. Same instance-level patch as the Data `data_worker` and the
# Deep Research `web_search_agent`; the RAG MANAGER keeps the stock
# behavior (its observations are the managed-agent report wrapper, not
# raw findings).
try:
agent._orig_handle_max_steps_reached = agent._handle_max_steps_reached
agent._handle_max_steps_reached = types.MethodType(
_searcher_max_steps_handoff, agent
)
except Exception:
pass
print(f"[RAGAgent] Building {type(agent).__name__} sub-agent "
f"'{SEARCHER_AGENT_NAME}' on '{model_id or '(shared)'}' …")
return agent
def _build_manager_agent(llm, searcher, model_id: str = "",
summary_tools=None,
max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
use_tool_calling: bool = True,
visual_retrieval: bool = True):
"""Build the manager agent. It holds NO search tool of its own — only
the managed `knowledge_searcher` sub-agent (plus smolagents'
auto-added final_answer tool). Its whole job is to analyze the user's
question, split it into focused search tasks, delegate them, and
synthesize the grounded answer. `visual_retrieval=False` drops the
VISUAL-INDEX RULE from the instructions (the rule points at a
`visual_retriever` tool that does not exist when it is disabled)."""
if max_steps is None:
max_steps = _scaled_max_steps(model_id, RAG_AGENT_DEFAULT_MAX_STEPS)
agent = build_smol_agent(
llm,
tools=list(summary_tools or []),
max_steps=max_steps,
execution_timeout=execution_timeout,
use_tool_calling=use_tool_calling,
instructions=(STRICT_SYSTEM_INSTRUCTIONS if visual_retrieval
else STRICT_SYSTEM_INSTRUCTIONS_NO_VISUAL),
# Deep-research strategy: re-plan every few steps instead of
# blindly executing the initial search plan, and return a concise
# run summary so the manager can see what the sub-agent found.
# final_answer_checks is attached only when this smolagents
# version's __init__ accepts it (optional_kwargs guard).
extra_kwargs={
"managed_agents": [searcher],
# Per-model override: models flagged planning-incompatible
# (Muse Glimmer — it echo-loops the re-plan prompt) get None
# (planning off), everyone else keeps the default interval.
"planning_interval": mr.planning_interval_for_model(model_id, RAG_PLANNING_INTERVAL),
"provide_run_summary": True,
},
optional_kwargs={"final_answer_checks": [_validate_final_report]},
)
print(f"[RAGAgent] Building {type(agent).__name__} manager on "
f"'{model_id or '(shared)'}' …")
return agent
def get_rag_agent(model_id: Optional[str] = None, theme: str = "", subtheme: str = "",
max_steps: Optional[int] = None, searcher_max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
use_tool_calling: bool = True,
provider: Optional[str] = None, n_ctx: Optional[int] = None,
sources: Optional[list] = None,
visual_retrieval: bool = False):
"""Lazily build (or rebuild) the manager + `knowledge_searcher` sub-agent.
`use_tool_calling` requests native tool-calling (ToolCallingAgent);
auto-falls-back to CodeAgent if the loaded model doesn't support it.
`searcher_max_steps` (optional): the `knowledge_searcher` sub-agent's
own step budget (the manager's is `max_steps`) — the UI's per-tab
agentic step controls for RAG (see AgentControls.svelte). None uses the
model-scaled default (SEARCHER_DEFAULT_MAX_STEPS). Included in the
cache key, so changing it rebuilds the pair.
`execution_timeout` (optional): the per-step Python code-executor
timeout in seconds (the RAG "Exec timeout" control in agentic mode) —
threaded to build_smol_agent's executor_kwargs. None = AUTO (the
factory default). Included in the cache key, so changing it rebuilds.
`n_ctx` (optional): the RAG tab's context window, threaded to
models.get_llm() so a per-tab n_ctx change rebuilds this agent with
the freshly (re)loaded model. Included in the cache key for that reason.
`visual_retrieval` (default False): the RAG tab's "Visual Retriever +
VLM" toggle. When OFF, the `visual_retriever` page-image tool is NOT
attached to the `knowledge_searcher` sub-agent and the visual
instructions (VISUAL-INDEX RULE / SCANNED rule) are stripped from both
agents' system prompts, so the agentic RAG path never touches page
images or loads the retriever/VLM. Included in the cache key so
toggling it rebuilds the pair.
"""
global _rag_agent, _rag_agent_model_id, _rag_agent_theme, _rag_agent_subtheme
global _rag_agent_max_steps, _rag_agent_searcher_max_steps, _rag_agent_execution_timeout, _rag_tool
global _rag_summary_tools, _rag_agent_n_ctx, _rag_agent_sources, _rag_visual_tool
global _rag_agent_visual_retrieval
target = model_id or models._llm_model_id
sources = list(sources or [])
_same_run = (
target == _rag_agent_model_id and theme == _rag_agent_theme
and subtheme == _rag_agent_subtheme and max_steps == _rag_agent_max_steps
and searcher_max_steps == _rag_agent_searcher_max_steps
and execution_timeout == _rag_agent_execution_timeout
and n_ctx == _rag_agent_n_ctx and sources == _rag_agent_sources
and visual_retrieval == _rag_agent_visual_retrieval
)
if _rag_agent is not None and _same_run:
return _rag_agent
with _rag_agent_lock:
if _rag_agent is not None and _same_run:
return _rag_agent
# `provider` is threaded through (same as general_agent) so a
# non-default provider requested from the RAG tab actually takes
# effect; get_llm treats provider=None as the default.
llm = models.get_llm(target, provider=provider, n_ctx=n_ctx)
# The tool-calling decision (ToolCallingAgent vs CodeAgent fallback)
# is owned by build_smol_agent via the shared default predicate
# `supports_native_tool_calls` — same as general_agent. Passing the
# raw flag here means the factory applies the predicate itself.
_rag_tool = RetrieverTool(theme=theme, subtheme=subtheme, sources=sources)
# The visual page-image tool — the second retrieval tool the
# `knowledge_searcher` sub-agent can use (charts / scans / pages
# that text extraction misses). OFFERED ONLY when the RAG tab's
# "Visual Retriever + VLM" toggle is ON (default OFF — visual
# retrieval is resource-intensive: it can pull in the 2-8 GB
# retriever model and the VLM grounding pass). When disabled the
# tool is None, so `_build_searcher_agent` neither attaches it nor
# teaches its use, and VLM grounding is also skipped in chat.py.
_rag_visual_tool = VisualRetrieverTool() if visual_retrieval else None
# The summary/listing tools ALSO receive the RAG tab's selected
# sources — a summary, key-points, mind-map or topic listing must
# never cover documents outside the user's selected files, exactly
# like the retriever already scopes factual searches (the file
# filter is otherwise silently ignored by the summary path).
_rag_summary_tools = [
ListTopicsTool(sources=sources),
ThemeSummaryTool(sources=sources),
SubthemeSummaryTool(sources=sources),
DocumentSummaryTool(sources=sources),
KeyPointsTool(sources=sources),
MindMapTool(sources=sources),
]
_searcher = _build_searcher_agent(llm, _rag_tool, _rag_visual_tool, target, searcher_max_steps, execution_timeout, use_tool_calling=use_tool_calling, n_ctx=n_ctx)
_rag_agent = _build_manager_agent(llm, _searcher, target, _rag_summary_tools, max_steps, execution_timeout, use_tool_calling=use_tool_calling, visual_retrieval=visual_retrieval)
_rag_agent_model_id = target
_rag_agent_theme = theme
_rag_agent_subtheme = subtheme
_rag_agent_sources = sources
_rag_agent_max_steps = max_steps
_rag_agent_searcher_max_steps = searcher_max_steps
_rag_agent_execution_timeout = execution_timeout
_rag_agent_n_ctx = n_ctx
_rag_agent_visual_retrieval = visual_retrieval
# Standard smolagents behaviour: a freshly-built agent starts
# with empty memory. See agent_memory.py's module docstring for
# why this app no longer tries to restore memory from a previous
# model or app session.
tc_label = type(_rag_agent).__name__
print(f"[RAGAgent] Built {tc_label} manager + {SEARCHER_AGENT_NAME} on '{target}' …")
return _rag_agent
def reset_agent():
"""Drop the cached CodeAgent wrapper (does NOT unload the underlying LLM
itself — that's shared/managed by models.get_llm()). Call this whenever
the RAG-tab model changes or the LLM is force-reloaded/unloaded
elsewhere, so this agent doesn't keep holding a stale model reference.
"""
global _rag_agent, _rag_agent_model_id, _rag_agent_theme, _rag_agent_subtheme
global _rag_agent_max_steps, _rag_agent_searcher_max_steps, _rag_agent_execution_timeout, _rag_tool
global _rag_summary_tools, _rag_agent_n_ctx, _rag_agent_sources, _rag_visual_tool
_rag_agent = None
_rag_agent_model_id = None
_rag_agent_theme = ""
_rag_agent_subtheme = ""
_rag_agent_sources = []
_rag_agent_max_steps = 6
_rag_agent_searcher_max_steps = None
_rag_agent_execution_timeout = None
_rag_agent_n_ctx = None
_rag_tool = None
_rag_visual_tool = None
_rag_summary_tools = []12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""
LocalAiLab Assistant — by LocalAiLab
smolagents + ChromaDB + Dynamic Hardware Support + Svelte Web UI
=======================================================================
Tabs:
💬 General Chat — direct LLM conversation, no retrieval
📚 RAG Chat — retrieves from ChromaDB before answering
🔬 Deep Research — iterative multi-agent web research
🖼️ Vision Chat — image upload, answers from the image only (no KB)
🎙️ Speech to Text — transcribe audio to text using Whisper
📊 Data Analysis — AI agent explores CSV/Excel, builds charts + report
📂 Knowledge Base — index / manage documents
⚙️ Settings — system & model configuration
ℹ️ About — bilingual system info
"""
import os
import socket
import threading
import warnings
import webbrowser
from pathlib import Path
os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
os.environ.setdefault("DO_NOT_TRACK", "1")
# Force the non-GUI matplotlib backend app-wide (see run_webview.py — the
# tkinter splash must never collide with matplotlib's TkAgg auto-select in
# the Data worker thread; `Tcl_AsyncDelete` would abort the process).
os.environ.setdefault("MPLBACKEND", "Agg")
try:
from dotenv import load_dotenv
from backend.paths import user_data_dir
user_env = str(user_data_dir() / ".env")
if os.path.exists(user_env):
load_dotenv(user_env)
else:
load_dotenv()
except ImportError:
pass
from backend import web_api
APP_ICON = Path(__file__).parent / "ui" / "image" / "logo_round.png"
def _find_free_port(start=7861):
for port in range(start, start + 20):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(("127.0.0.1", port)) != 0:
return port
return start
warnings.filterwarnings("ignore", category=UserWarning, module="torch")
if __name__ == "__main__":
import multiprocessing
multiprocessing.freeze_support()
# Shared Windows stdio hardening: replaces None OR broken-handle
# streams (a GUI-launched process can have a sys.stdout whose OS handle
# is invalid — print() then raises OSError [WinError 6] and kills the
# run) and forces UTF-8 + errors=replace on the rest.
from backend.stdio_hardening import harden_stdio, harden_subprocesses
from backend.metadata_hardening import harden_metadata
harden_stdio()
harden_subprocesses()
harden_metadata()
port = _find_free_port()
# Open browser on startup
threading.Timer(0.8, lambda: webbrowser.open(f"http://127.0.0.1:{port}")).start()
web_api.run(host="127.0.0.1", port=port, log_level="info")1# backend package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""audio_denoise.py — Background-noise reduction for the STT tab.
Self-contained spectral-gate denoiser (no new dependencies: numpy + scipy,both already part of the app's stack — scipy is a hard dependency oflibrosa, pinned in requirements.txt since this module imports it directly).
Approach: estimate a stationary noise profile from the QUIETEST STFT frames(≈ speech pauses), then attenuate every frame's magnitude where it sits nearthat noise floor (spectral gating). The cleaned audio is written as 16-bitPCM WAV — the one format every STT backend (soundfile, whisper-server) reads,so the cleaned file drops straight into the existing transcribe/save/trimplumbing.
The module is total: unusable input or a missing scipy degrades to a cleanerror, never a traceback. Every import is lazy so a broken optional wheel cannever crash app startup."""
from __future__ import annotations
from pathlib import Path
# Named strength presets for the STT tab's noise-reduction picker. Each maps# to the gate's `strength` (how far the noise floor is pulled down, 0–1):# gentle (0.55) — light touch: keeps soft consonants / ambience# medium (0.75) — balanced (the previous default's neighborhood)# aggressive (0.9) — hard gate: silences pauses, may thin quiet speechDENOISE_STRENGTH_PRESETS = { "gentle": 0.55, "medium": 0.75, "aggressive": 0.9,}
DEFAULT_DENOISE_STRENGTH = DENOISE_STRENGTH_PRESETS["aggressive"]
def resolve_strength(value) -> float: """Map a preset name ('gentle' / 'medium' / 'aggressive') or a raw 0–1 number (int / float / numeric string) to a gate strength. Anything else falls back to the aggressive default — the endpoint can never crash on a bad pick, and the numeric form stays usable for advanced callers.""" if isinstance(value, str): v = value.strip().lower() if v in DENOISE_STRENGTH_PRESETS: return DENOISE_STRENGTH_PRESETS[v] try: num = float(v) except ValueError: return DEFAULT_DENOISE_STRENGTH return num if 0.0 <= num <= 1.0 else DEFAULT_DENOISE_STRENGTH # type() rather than isinstance(): bool is an int subclass, and a JSON # `true` silently meaning "max strength" is never intended — same # bool-rejection convention as the settings_save guards. if type(value) in (int, float): return value if 0.0 <= float(value) <= 1.0 else DEFAULT_DENOISE_STRENGTH return DEFAULT_DENOISE_STRENGTH
def denoise_audio(input_path, output_path, *, strength: float = DEFAULT_DENOISE_STRENGTH, n_fft: int = 1024, hop_length: int = 256, noise_quantile: float = 0.1) -> str: """Reduce stationary background noise in *input_path* and write the cleaned 16-bit mono WAV to *output_path*. Returns the output path.
`strength` — how aggressively the noise floor is pulled down (0–1). `noise_quantile` — fraction of lowest-energy frames used to estimate the noise profile (0.05–0.5). Raises RuntimeError on unusable input / a missing scipy — never a raw traceback. """ import numpy as np import soundfile as sf
try: from scipy.ndimage import median_filter from scipy.signal import istft, stft except Exception as e: # pragma: no cover — scipy is pinned, defensive raise RuntimeError(f"Noise reduction unavailable (scipy missing): {e}")
data, sr = sf.read(str(input_path), dtype="float32", always_2d=False) if data is None or len(data) == 0: raise RuntimeError("No audio samples to denoise.") if getattr(data, "ndim", 1) > 1: data = data.mean(axis=1) # mono — the STT backends transcribe mono anyway # A corrupt sample (NaN) must never flow through log10/exp/istft into the # WAV — silence it first so the module stays total. data = np.nan_to_num(np.asarray(data, dtype="float32"), nan=0.0, posinf=0.0, neginf=0.0) # Shorter than one FFT window there's nothing to gate — scipy would pad # it into near-silence instead of failing, which would be a lie. if len(data) < n_fft: raise RuntimeError("Audio too short to denoise.")
# Clamp the noise-quantile so a pathological value can't empty the profile. nq = float(min(max(noise_quantile, 0.01), 0.5)) gain_floor = max(0.0, min(float(strength), 0.98))
f, t, Zxx = stft(data, fs=sr, nperseg=n_fft, noverlap=n_fft - hop_length, window="hann", boundary="zeros") mag = np.abs(Zxx)
# Noise profile ≈ mean magnitude of the quietest frames (speech pauses). n_noise = max(1, int(round(mag.shape[1] * nq))) quiet_idx = np.argsort(np.mean(mag, axis=0))[:n_noise] noise_floor = np.mean(mag[:, quiet_idx], axis=1, keepdims=True)
# De-contaminate narrow tonal peaks: when the recording has no true pause # (a constant tone / droning fan in every frame), the quietest frames still # carry that tone, so the profile would read it as noise and the gate would # attenuate it away. The noise floor is broadband while tones/harmonics are # narrow, so replace each bin's estimate with the lower of itself and the # median of its neighbours across frequency (nearest-mode keeps the edges # honest). noise_floor = np.minimum( noise_floor, median_filter(noise_floor, size=(31, 1), mode="nearest"), )
# Spectral gate: keep signal, pull down what looks like the noise floor. # A sigmoid on the bin's dB EXCESS over the floor (a soft threshold ~10 dB # above the profile) — a linear 1 - gain*ratio gate let noise bins sitting # above the profile pass through almost untouched (~2x reduction); the # sigmoid clamps typical noise fluctuations (a few dB around the floor) # down hard while staying transparent for anything clearly above it. with np.errstate(divide="ignore", invalid="ignore", over="ignore"): excess_db = 20.0 * np.log10( np.maximum(mag, 1e-12) / np.maximum(noise_floor, 1e-12) ) # exp(+huge) for deep-sub-floor bins → inf → gate = floor. Guarded by # errstate(over="ignore") — the clip below still lands it exactly on # the floor, never amplifying. gate = 1.0 / (1.0 + np.exp(-2.0 * (excess_db - 10.0))) gate = (1.0 - gain_floor) + gain_floor * gate # strength scales the floor gate = np.clip(gate, 1.0 - gain_floor, 1.0) # never below the floor, never amplify cleaned = Zxx * gate
# boundary='zeros' on both transforms keeps the pair invertible (NOLA # satisfied); the zero-padding edges are trimmed back to the input length. _, y = istft(cleaned, fs=sr, nperseg=n_fft, noverlap=n_fft - hop_length, window="hann", boundary="zeros") y = np.asarray(y, dtype=np.float32)[: len(data)]
# Normalise to a safe peak so whisper never clips, then write 16-bit WAV. peak = float(np.max(np.abs(y))) if len(y) else 0.0 if peak > 0.999: y = y / peak * 0.95 out = Path(output_path) out.parent.mkdir(parents=True, exist_ok=True) sf.write(str(out), y, sr, subtype="PCM_16") return str(out)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512"""
chat.py — Chat-turn handlers for the General Chat, RAG Chat, and Vision
Chat tabs, plus the <think>-tag reasoning/answer formatter shared by the
text tabs.
"""
import re
import time
from typing import Optional
from PIL import Image
from ui import i18n
from ui.i18n import LANGUAGES
from backend import knowledge_base as kb
from backend import model_registry as mr
from backend import models
from backend.live_stream import get_bus
from agents import general_agent
from agents import rag_agent
from agents import deep_research_agent
from agents import agent_memory
from agents import agent_streaming
from backend.hardware import DEVICE
# NOTE: agentic memory (agent.memory.steps) lives only in RAM, for as long
# as the cached CodeAgent object for that tab stays alive — see
# agent_memory.py's module docstring for why this app deliberately does
# NOT persist it to disk. The "🧠 Conversation Memory" checkbox is marked
# experimental in the UI for the same reason: it resets on a model
# switch, "Clear", or an app restart, and — especially with small/local
# models — can occasionally produce a confused reply if a step written by
# one model gets replayed against a different one after a mid-conversation
# model switch.
# How many prior user+assistant exchanges to feed back into the *direct*
# (non-agentic) chat paths as short-term conversation memory. Agentic
# paths don't use this — they get real memory from smolagents' own
# agent.memory (see general_agent.py / rag_agent.py / agent_memory.py).
#
# This is now the FALLBACK ceiling, used only when the token budget can't
# be determined (see _recent_memory_messages()): when the '🧹 Memory
# Compaction' toggle (Settings) is on and the model's context window is
# known, the direct paths keep as many of the most recent turns as FIT
# the window's token budget instead of always slicing at this fixed count.
DIRECT_CHAT_MEMORY_TURNS = 6
# How many turns of memory an agentic CodeAgent is allowed to keep before
# older turns get dropped (see agent_memory.cap_agent_memory()).
AGENTIC_MEMORY_TURNS = 6
# Deep Research reports are much longer per turn than a normal chat
# answer (and each turn can also include several delegated sub-agent
# calls), so its memory budget is kept smaller than the other agentic
# tabs' default — same reasoning as data_analysis.DATA_AGENT_MEMORY_TURNS.
DEEP_RESEARCH_MEMORY_TURNS = 4
def _agent_mechanism_txt(use_tool_calling: bool) -> str:
"""Footer label for the ACTUAL agent mechanism on every agentic tab:
'tool calling' when the tab runs the default ToolCallingAgent
(structured tool calls only — no Python execution; see
general_agent.py's note on PythonInterpreterTool), and 'code' when
'Use native tool calling' is unchecked and the tab runs a CodeAgent
(every step writes and executes Python). Shared by the General / RAG /
Deep Research footers so the label stays consistent across tabs."""
return "tool calling" if use_tool_calling else "code"
# Shared with the Data Analysis footer too (agents/agent_streaming.py
# owns the single implementation — see _agent_steps_budget_txt there).
_agent_steps_budget_txt = agent_streaming._agent_steps_budget_txt
def _compaction_status_msg(lang_key: str = "kh") -> str:
"""One-line bilingual status shown when agentic memory compaction fires
(see agent_memory.compact_agent_memory())."""
return ("🧹 កំពុងបង្រួមអង្គចងចាំសន្ទនា…" if lang_key == "kh"
else "🧹 Compacting conversation memory…")
def _agent_failure_hint(lang_key: str = "kh",
diagnostics: Optional[dict] = None) -> str:
"""Soft guidance footer appended when an agentic run COMPLETED but the
model still stumbled on repeated errored steps (see agent_streaming's
fail-fast guard). `diagnostics` is the run's diagnostics snapshot
carried on the stream's FINAL yield ({total_steps,
max_consecutive_errors, aborted}) — the stream contract now delivers
it, so this no longer reads back `get_last_run()` after the loop.
Returns an empty string for clean runs and for runs the fail-fast
guard ABORTED (the abort message itself already carries the "try a
larger model" guidance, so this would just duplicate it)."""
d = diagnostics or {}
n = d.get("max_consecutive_errors", 0) or 0
if d.get("aborted") or n < agent_streaming._STUMBLE_HINT_THRESHOLD:
return ""
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
hint = l.get("agent_stumble_hint", "")
if not hint:
return ""
return "\n\n" + hint.format(n=n)
def _maybe_compact_agent_memory(agent, model_id: str, lang_key: str,
tab_key: str = "gen") -> bool:
"""Run the token-budget-aware rolling compaction on an agentic
CodeAgent before its next run (see agent_memory.compact_agent_memory()).
Reads the persisted compaction tuning from model_registry: the global
budget ratio (Settings > Memory Compaction Threshold), and the
'keep recent turns' setting for `tab_key` ('gen'/'rag'/'dr'/'data') —
the global override, or the per-tab default (General/RAG = 2,
Deep Research/Data = 1) while the control is on 'Auto'.
Returns True if memory was compacted — callers show a one-line status
(see _compaction_status_msg()). No-op when conversation memory is off
or the '🧹 Memory Compaction' toggle (Settings) is disabled."""
if agent is None:
return False
return agent_memory.compact_agent_memory(
agent,
model_id=model_id,
n_ctx=models._llm_n_ctx or mr.get_saved_context_window(),
keep_recent_turns=mr.get_saved_memory_keep_recent(tab_key),
budget_ratio=mr.get_saved_memory_compaction_ratio(),
lang_key=lang_key,
)
def _speed_seg(elapsed: float, n_tokens: int) -> str:
"""Token-rate segment for the response footer — e.g. '· 40 tok/s'.
Returns an empty string when token count is 0 (the agentic paths can
estimate but never guarantee an exact count)."""
if not n_tokens:
return ""
tok_per_sec = n_tokens / elapsed if elapsed else 0
return f" · {tok_per_sec:.1f} tok/s"
# Reusable HTML templates for format_llm_response() — extracted to
# module-level constants so the same HTML strings aren't built from scratch
# on every single chat turn (see the three branches in
# format_llm_response() below, which each use some combination of these).
_THINK_TPL = (
'<details class="think-block" {open}>\n'
'<summary class="think-summary">\n'
'<span class="think-badge">{summary}</span>\n'
'<span class="think-hint">(click to toggle)</span>\n'
'</summary>\n'
'<div class="think-body">\n{body}\n</div>\n'
'</details>\n'
)
_ANSWER_TPL = (
'<div class="final-answer-block">\n'
'<div class="answer-header-badge">{title}</div>\n'
'<div class="answer-body">\n{body}\n</div>\n'
'</div>'
)
def format_llm_response(text: str, lang_key: str = "kh") -> str:
if not text or not isinstance(text, str):
return text or ""
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
reasoning_title = l.get("err_reasoning", "🧠 ដំណើរការគិត / Reasoning Process")
answer_title = l.get("err_answer", "✨ ចម្លើយចុងក្រោយ / Final Answer")
no_reasoning = l.get("no_reasoning_text", "គ្មានព័ត៌មានគិត")
truncated_notice = l.get("truncated_notice", "⚠️ ការគិតត្រូវបានកាត់ផ្តាច់ (Truncated)")
thinking = None
answer = None
# 1. Match <think>...</think> or <reasoning>...</reasoning> or <thought>...</thought>
m_tag = re.search(r"<(think|reasoning|thought)>(.*?)</\1>(.*)", text, re.DOTALL | re.IGNORECASE)
if m_tag:
thinking = m_tag.group(2).strip()
answer = m_tag.group(3).strip()
else:
# 1b. Match Gemma 4 channel tags: <|channel>thought\n...<channel|>[answer]
m_gemma = re.search(r"<\|?channel\|?>thought\s*(.*?)(?:<\|?channel\|?>|\Z)(.*)", text, re.DOTALL | re.IGNORECASE)
if m_gemma and m_gemma.group(1).strip():
thinking = m_gemma.group(1).strip()
answer = m_gemma.group(2).strip()
else:
# 2. Match " thinking... response..."
m_resp = re.search(r" thinking(.*?) response(.*)", text, re.DOTALL)
if m_resp:
thinking = m_resp.group(1).strip()
answer = m_resp.group(2).strip()
else:
# 3. Unclosed <think> or " thinking"
m_unclosed = re.search(r"<(think|reasoning|thought)>(.*)", text, re.DOTALL | re.IGNORECASE)
if m_unclosed:
thinking = m_unclosed.group(2).strip()
answer = ""
elif " thinking" in text and " response" not in text:
thinking = text.split(" thinking", 1)[1].strip()
answer = ""
if thinking is not None:
think_html = _THINK_TPL.format(
open="",
summary=reasoning_title,
body=thinking if thinking else no_reasoning,
)
if answer:
answer = agent_streaming._strip_deliberation_preamble(answer)
ans_html = _ANSWER_TPL.format(
title=answer_title,
body=answer,
)
return think_html + ans_html
else:
ans_html = _ANSWER_TPL.format(
title=answer_title,
body=truncated_notice,
)
return think_html + ans_html
return agent_streaming._strip_deliberation_preamble(text)
def _strip_html_tags(text: str) -> str:
"""Remove HTML tags from text, keeping the inner content.
The single source of truth for tag-stripping, shared by
_strip_response_html() (recovering plain text for conversation
memory) and _export_markdown() (cleaning answers for .docx export) —
one regex, one place. Markdown syntax (**bold**, # headings, | tables |)
is not HTML and is left untouched.
The regex only strips TAG-SHAPED markup (`<` followed by a letter or
`/`), so bare comparison operators and math in answers survive: "x < 5"
and "a < b > c" are never eaten, while `<div class="…">`, `<table>`,
`<br>`, `</p>` etc. all still match."""
return re.sub(r"<[a-zA-Z/][^>]*>", "", text)
def _strip_response_html(text: str) -> str:
"""Recover the plain-text answer from a previously HTML-formatted assistant reply."""
if not text:
return text
text = re.sub(r"<details.*?</details>", "", text, flags=re.DOTALL)
text = re.sub(r"<div class=\"final-answer-block\".*?<div class=\"answer-body\">(.*?)</div>\s*</div>", r"\1", text, flags=re.DOTALL)
text = re.sub(r"<hr>.*$", "", text, flags=re.DOTALL)
text = re.sub(r"<b>\U0001F4AC[^<]*</b>\s*", "", text)
text = _strip_html_tags(text)
return text.strip()
def _recent_memory_messages(history: list, max_turns: int = DIRECT_CHAT_MEMORY_TURNS,
model_id: Optional[str] = None,
provider: Optional[str] = None,
n_ctx: Optional[int] = None,
model_obj=None, reserve_tokens: int = 0) -> list:
"""Build a clean list of prior {"role", "content"} turns from the
Gradio chatbot history, to hand to models._call_llm() as short-term
conversation memory for the *direct* (non-agentic) chat paths.
Strips HTML formatting from assistant replies (see
_strip_response_html()) so old markup/timing footers don't
pollute the prompt.
Keeps the most recent turns that FIT the model's context-window
token budget (see agent_memory.trim_messages_to_budget()) instead
of always slicing at a fixed turn count — the direct-chat analog
of the agentic paths' token-budget compaction. `model_id` /
`provider` / `n_ctx` identify the model the request will actually
run on (the same values passed to models._call_llm()); `model_obj`
is the alternative for paths (like Vision) whose model is resolved
through a different loader. `reserve_tokens` holds room in the
budget for prompt content added separately from memory (e.g. RAG
retrieved context). When the budget can't be determined —
remote backend, the '🧹 Memory Compaction' toggle (Settings) off,
or a window too small to leave generation room — this falls back
to the plain last-`max_turns` slice, exactly as before this change.
"""
if not history:
return []
cleaned = []
for turn in history:
role, content = turn.get("role"), turn.get("content")
if not isinstance(content, str) or not content.strip():
continue
if role == "assistant":
content = _strip_response_html(content)
if not content:
continue
elif role != "user":
continue
cleaned.append({"role": role, "content": content})
fixed = cleaned[-(max_turns * 2):]
if model_obj is None and model_id is None:
return fixed
if not mr.get_saved_memory_compaction_enabled():
return fixed
try:
if model_obj is None:
model_obj = models.get_llm(model_id, provider=provider, n_ctx=n_ctx)
if not agent_memory.is_local_backed_model(model_obj):
return fixed
window = agent_memory._effective_n_ctx(
model_obj, n_ctx or models._llm_n_ctx or mr.get_saved_context_window())
# Generation reserve: the upcoming answer shares the window with
# whatever memory we keep — same math as compact_agent_memory().
# `reserve_tokens` additionally holds room for prompt content added
# SEPARATELY from memory (e.g. the RAG path's retrieved context,
# which goes into the system prompt) so memory can't crowd it out.
budget = int(window * mr.get_saved_memory_compaction_ratio()) \
- mr.get_saved_max_new_tokens() - reserve_tokens
if budget <= 0:
return fixed
tokenizer = agent_memory._get_model_tokenizer(model_obj)
return agent_memory.trim_messages_to_budget(cleaned, budget, tokenizer)
except Exception:
# Never let a token-measurement hiccup break the chat loop —
# the fixed-turn slice is a perfectly usable fallback.
return fixed
def _lang_instruction(lang_key: str) -> str:
"""System-prompt instruction forcing the answer language to match the
UI language. Uses the strong, explicit shared instruction from
ui.i18n (a bare 'Answer in Khmer.' is routinely ignored by small
models and by RAG contexts written in English)."""
return i18n._output_lang_instruction(lang_key)
def run_timeout_message(lang_key: str) -> str:
"""Bilingual 'Generation timed out' message — the text the WS layer
emits when a chat run exceeds its per-tab Generation Settings
'Timeout'. Surfaces in the conversation as an assistant bubble."""
if lang_key == "kh":
return (
"⏰ អស់ពេលកំណត់ (timeout) — ការបង្កើតចម្លើយមិនទាន់បានបញ្ចប់ "
"ក្នុងពេលកំណត់ទេ។ សូមបង្កើន 'Timeout' នៅក្នុង Generation Settings "
"ហើយព្យាយាមម្តងទៀត។"
)
return (
"⏰ Generation timed out — the answer was not finished in time. "
"Increase the 'Timeout' in Generation Settings and try again."
)
def chat_general_direct(user_message: str, history: list, model_label: str, use_memory: bool = True, lang_key: str = "kh"):
"""A generator yielding exactly ONE (history, "") tuple — the direct
path has no intermediate agent steps to stream, but is written as a
generator (rather than a plain function) so chat_general()'s
`yield from` dispatch works uniformly regardless of which path (direct
or agentic) it delegates to. See chat_general_agentic() below for the
path that actually yields multiple times as live agent steps arrive.
"""
if not user_message.strip():
yield history, ""
return
history = history or []
history.append({"role": "user", "content": user_message})
provider = mr.get_saved_provider("gen")
model_id = mr.resolve_model_id(model_label, provider=provider)
n_ctx = mr.get_saved_context_window("gen")
ans = None # plain-markdown answer — the .docx export source (set in the success branch)
try:
# Memory: feed back the recent conversation (minus the message we
# just appended above, which is passed separately as `user`) so
# follow-ups like "and what about X?" have something to refer to.
# Skipped entirely when the "🧠 Conversation Memory" checkbox is off.
memory_messages = _recent_memory_messages(
history[:-1], model_id=model_id, provider=provider, n_ctx=n_ctx) if use_memory else []
system = _lang_instruction(lang_key) + "You are a helpful, friendly assistant."
# IMPORTANT: without this, instruct-tuned models (small ones
# especially) tend to give a trained canned disclaimer like "I
# don't have memory of past conversations" to any meta-question
# about memory ("do you remember what I said earlier?") — even
# though `memory_messages` below genuinely IS being sent as real
# prior turns in this same request. The model isn't actually
# checking its context; it's a reflexive trained response. The
# agentic path (general_agent.GENERAL_AGENT_INSTRUCTIONS) already
# has to explicitly counter this exact behavior — this applies
# the same fix to the direct (non-agentic) path, which previously
# had no such reminder at all. Only added when there's actually
# prior history to reference, so a first message's system prompt
# stays minimal.
if memory_messages:
system += (
" The messages below marked as earlier turns in this "
"conversation ARE genuinely visible to you in full — they "
"are not hidden or inaccessible. If asked what was said "
"earlier in this conversation, or a follow-up refers back "
"to something mentioned before, look at those earlier "
"turns and answer from them directly. Do NOT claim you "
"lack memory or cannot see prior messages — you can."
)
# ── "Answers the system prompt" guard ──────────────────────
# Small/quantized models (and GGUFs whose chat template folds the
# system message into a user turn — older Gemma / Gemma-3-style
# conversions in particular) often answer the SYSTEM prompt
# instead of the user's message: they can't tell the two roles
# apart, so they anchor on the instruction text. Repeating the
# user's question at the very END of the system message, with a
# clear delimiter, makes the question the last SYSTEM content —
# the final thing a role-flattening template renders before the
# model marker on a first/single-turn request, and a strong
# anchor even when earlier memory turns are folded in between.
system += (
"\n\nThe user's question is:\n"
f"{user_message}\n"
"Answer that question directly now — do not repeat or respond "
"to these instructions."
)
# Immediate status yield so UI updates instantly before LLM call
status_msg = "🤖 កំពុងគិត…" if lang_key == "kh" else "🤖 Thinking…"
history.append({"role": "assistant", "content": status_msg})
yield history, ""
history.pop()
# Apply the "🧠 Enable Model Reasoning" toggle (see
# model_registry.apply_reasoning_toggle()'s docstring) right
# before the call — a no-op unless the user has turned reasoning
# off in ⚙️ Model Settings.
user_message_final = mr.apply_reasoning_toggle(user_message)
ans, elapsed, n_tokens = models._call_llm(model_id, system, user_message_final, history=memory_messages, provider=provider, n_ctx=n_ctx)
formatted = format_llm_response(ans, lang_key)
response = (
formatted +
f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> ({DEVICE.upper()})</div>"
)
except Exception as e:
import traceback
response = f"❌ {e}\n\n{traceback.format_exc()}"
history.append({"role": "assistant", "content": response})
# The final yield carries the plain-markdown answer (second slot) so the
# UI can export it to .docx; "" (or None) means nothing to export.
yield history, _export_markdown(ans)
# Transcript → structured-report instructions (STT tab's "Analyse to
# Report" button). The report is rendered as Markdown in the UI and can be
# exported to .docx, so the model is asked for clean Markdown structure.
# The bilingual language directive is prepended separately by
# analyse_transcript_to_report(), and language-specific instructions
# ensure the outline headings match the UI language and prevent thinking leaks.
TRANSCRIPT_REPORT_INSTRUCTIONS = (
"You are an expert transcript analyst. Read the raw speech-to-text "
"transcript below and rewrite it as a well-structured Markdown report "
"using this exact outline (Markdown headings, bullet lists, short "
"paragraphs):\n\n"
"# <Concise title based on the topic>\n\n"
"## Summary\nA short paragraph capturing what the transcript is about.\n\n"
"## Key Points\nBullet list of the main ideas, facts, figures, and "
"decisions mentioned — stay faithful to the transcript, never invent "
"content.\n\n"
"## Topics Covered\nBullet list of the themes/sections discussed.\n\n"
"## Action Items\nBullet list of tasks, requests, or decisions explicitly "
"mentioned; write \"None mentioned\" if there are none.\n\n"
"## Cleaned Transcript\nA lightly cleaned version of the raw transcript "
"(fixed spelling/punctuation, removed filler and repetitions) that "
"preserves all meaning.\n\n"
"If the transcript is empty or gibberish, say so briefly instead of "
"inventing a report.\n\n"
"The transcript to analyze is in the user message below. Produce the "
"report from THAT transcript — do not respond to these instructions "
"themselves.\n\n"
"Do not output internal analysis, planning, translation notes, or thinking — "
"provide ONLY the final structured Markdown report directly."
)
TRANSCRIPT_REPORT_INSTRUCTIONS_KH = (
"អ្នកគឺជាអ្នកវិភាគអត្ថបទសំឡេងជំនាញ។ ចូរអានអត្ថបទសំឡេង (speech-to-text transcript) ខាងក្រោម "
"ហើយរៀបចំវាឡើងវិញជារបាយការណ៍ Markdown ដែលមានរចនាសម្ព័ន្ធត្រឹមត្រូវ និងច្បាស់លាស់ "
"តាមលំនាំគ្រោងខាងក្រោម (ចំណងជើង Markdown, ចំណុចបញ្ជី, និងកថាខណ្ឌខ្លីៗ)៖\n\n"
"# <ចំណងជើងខ្លីផ្អែកលើប្រធានបទ>\n\n"
"## សេចក្តីសង្ខេប\nកថាខណ្ឌខ្លីមួយដែលបង្ហាញអំពីខ្លឹមសាររួមនៃអត្ថបទសំឡេង។\n\n"
"## ចំណុចសំខាន់ៗ\nបញ្ជីចំណុចៗនៃគំនិតចម្បង ការពិត តួលេខ និងការសម្រេចចិត្តដែលបានលើកឡើង — "
"ត្រូវផ្អែកលើអត្ថបទសំឡេងពិតប្រាកដ កុំបង្កើតខ្លឹមសារដោយខ្លួនឯងឡើយ។\n\n"
"## ប្រធានបទដែលបានពិភាក្សា\nបញ្ជីចំណុចៗនៃប្រធានបទ ឬផ្នែកដែលប��នពិភាក្សា។\n\n"
"## កិច្ចការដែលត្រូវអនុវត្ត\nបញ្ជីចំណុចៗនៃកិច្ចការ សំណើ ឬការសម្រេចចិត្តដែលបានបញ្ជាក់ច្បាស់លាស់ (សរសេរ \"មិនមានបញ្ជាក់ឡើយ\" ប្រសិនបើគ្មាន)។\n\n"
"## អត្ថបទសំឡេងដែលបានកែសម្រួល\nអត្ថបទសំឡេងដើមដែលបានកែសម្រួលអក្ខរាវិរុទ្ធ សញ្ញាវណ្ណយុត្តិ និងកាត់បន្ថយពាក្យជាន់គ្នាបន្តិចបន្តួច ប៉ុន្តែរក្សាអត្ថន័យដើមទាំងស្រុង។\n\n"
"ប្រសិនបើអត្ថបទសំឡេងទទេ ឬគ្មានន័យ សូមបញ្ជាក់យ៉ាងខ្លីជាជាងការបង្កើតរបាយការណ៍ក្លែងក្លាយ។\n\n"
"អត្ថបទសំឡេងដែលត្រូវវិភាគគឺស្ថិតនៅក្នុងសាររបស់អ្នកប្រើខាងក្រោម។ "
"កុំសរសេរការវិភាគ (Analysis) ផែនការ (Planning) ឬការគិតខាងក្នុងជាភាសាអង់គ្លេសឡើយ — "
"ចូរផ្តល់តែរបាយការណ៍ Markdown សម្រេចចុងក្រោយជាភាសាខ្មែរដោយផ្ទាល់។"
)
def _transcript_report_instructions(lang_key: str) -> str:
if lang_key == "kh":
return TRANSCRIPT_REPORT_INSTRUCTIONS_KH
return TRANSCRIPT_REPORT_INSTRUCTIONS
def analyse_transcript_to_report(transcript, model_label, lang_key="kh",
provider=None):
"""Generator that turns a raw speech-to-text transcript into a
structured Markdown report using the LLM picked on the STT tab (its
own provider + model dropdown, saved under the "stt_report" tab key).
Yields (status, report) tuples: first a short bilingual "thinking"
status with report="" so the UI can show progress, then the final
report with status="". An empty/whitespace transcript yields ("", "")
immediately WITHOUT any LLM call (the UI shows its own bilingual hint
in that case). The report is plain Markdown — suitable for the STT
tab's Markdown output and for .docx export via
backend.docx_export.markdown_text_to_docx()."""
if not transcript or not transcript.strip():
yield "", ""
return
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
provider = provider or mr.get_saved_provider("stt_report")
model_id = mr.resolve_model_id(model_label, provider=provider)
n_ctx = mr.get_saved_context_window("stt_report")
try:
yield l.get("think_stt_analyse", "🤖 Thinking…"), ""
system = _lang_instruction(lang_key) + _transcript_report_instructions(lang_key)
ans, elapsed, n_tokens = models._call_llm(model_id, system, transcript,
history=[], provider=provider, n_ctx=n_ctx)
raw_report = (ans or "").strip()
from agents.agent_streaming import _unwrap_leaked_final_answer
report = _unwrap_leaked_final_answer(raw_report)
if isinstance(report, str):
report = report.strip()
else:
report = str(report or "").strip()
if not report:
report = (
"⚠️ គ្មានរបាយការណ៍ត្រឡប់មកវិញទេ — សូមព្យាយាមម្តងទៀត។"
if lang_key == "kh" else
"⚠️ The model returned an empty report. Please try again."
)
yield "", f"{report}\n\n---\n⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: `{model_id}` ({DEVICE.upper()})"
except Exception as e:
yield "", f"❌ {e}"
def chat_general_agentic(user_message: str, history: list, model_label: str,
use_memory: bool = True, lang_key: str = "kh",
max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
use_tool_calling: bool = True):
"""Agentic General Chat: a smolagents ToolCallingAgent (or CodeAgent
when 'Use native tool calling' is unchecked — see general_agent.py)
with the library's own built-in web-search/webpage tools
(DuckDuckGoSearchTool, VisitWebpageTool), deciding for itself whether
a question needs a web lookup before answering. Unlike RAG Chat's
agent, this has no knowledge-base grounding requirement — it's meant
for open-ended questions, not strictly-cited document Q&A.
A GENERATOR: yields (history, "") once per live agent step as it
happens (see agent_streaming.stream_agent_steps()), then one final
time with the polished final answer appended — instead of blocking
silently until the whole run finishes. Mirrors smolagents' own
GradioUI streaming behaviour, adapted to this app's chat history
shape/styling (see agent_streaming.py's module docstring).
"""
if not user_message.strip():
yield history, ""
return
history = history or []
history.append({"role": "user", "content": user_message})
# Immediate status yield so UI updates instantly before agent construction / model loading
status_msg = "🌐🤖 កំពុងរៀបចំភ្នាក់ងារ AI…" if lang_key == "kh" else "🌐🤖 Initializing AI agent…"
history.append({"role": "assistant", "content": status_msg})
yield history, ""
history.pop()
provider = mr.get_saved_provider("gen")
model_id = mr.resolve_model_id(model_label, provider=provider)
n_ctx = mr.get_saved_context_window("gen")
# Persisted step budget (the per-tab "Max Steps" control): the WS
# payload's explicit value wins; None falls back to the saved budget,
# else AUTO (model-scaled default inside get_general_agent).
max_steps = max_steps if max_steps is not None else mr.get_saved_agent_steps("gen")
# Same auto pattern for the per-step execution timeout (the per-tab
# "Exec timeout" control): explicit payload wins, else the saved
# value, else AUTO (the agent factory's default timeout).
execution_timeout = execution_timeout if execution_timeout is not None else mr.get_saved_execution_timeout("gen")
export_text = None # plain-markdown answer for .docx export (set when the run produced one)
try:
agent = general_agent.get_general_agent(model_id, max_steps=max_steps, execution_timeout=execution_timeout, use_tool_calling=use_tool_calling, provider=provider, lang_key=lang_key, n_ctx=n_ctx)
general_agent.reset_tool_usage()
t0 = time.time()
# reset=False keeps this CodeAgent's own memory (agent.memory.steps)
# across turns instead of wiping it every message — see
# https://huggingface.co/docs/smolagents/tutorials/memory. Capped
# right after so a long conversation doesn't grow the prompt
# unboundedly turn after turn. When the "🧠 Conversation Memory"
# checkbox is off, reset=True instead, so every message starts
# from a clean slate (no memory to cap either).
#
# The message is wrapped with a per-task citation reminder (NOT
# just the raw user_message) because GENERAL_AGENT_INSTRUCTIONS'
# citation requirement only reaches the model at all if this
# installed smolagents version's CodeAgent accepts an
# `instructions=` kwarg (see agents/agent_factory.py's build_smol_agent()) —
# on a version where it doesn't, this per-call reminder is the
# ONLY place the model ever sees the requirement. Without it, the
# model never writes a '### References' section, and the
# "Sources used" block below always ends up empty even after a
# turn that genuinely searched the web.
task = general_agent.build_task_with_citation_reminder(user_message, lang_key)
# See chat_general_direct()'s matching comment — a no-op unless
# the "🧠 Enable Model Reasoning" toggle is off.
task = mr.apply_reasoning_toggle(task)
# Live step streaming — see agent_streaming.stream_agent_steps()'s
# docstring for the shared (step_msg, is_final, final_output)
# generator contract every agentic call site in this app now uses.
# Token-budget-aware memory compaction (see agent_memory.py): before
# this run, if the accumulated memory would push the next prompt past
# the context window, condense the older turns into a rolling summary
# instead of just dropping them — the fixed turn-cap below stays as
# the post-run safety net. No-op unless conversation memory is on and
# the '🧹 Memory Compaction' toggle (Settings) is enabled.
if use_memory and _maybe_compact_agent_memory(agent, model_id, lang_key, tab_key="gen"):
history.append({"role": "assistant", "content": _compaction_status_msg(lang_key)})
yield history, ""
history.pop()
result = None
diag = None # snapshot from the stream's final yield (every stream path ends with one); stays None only if the loop never ran
for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key):
if not is_final:
if step_msg is not None:
history.append(step_msg)
yield history, ""
continue
result = final_output
if use_memory:
agent_memory.cap_agent_memory(agent, max_turns=AGENTIC_MEMORY_TURNS)
elapsed = time.time() - t0
turn_count = sum(1 for s in agent.memory.steps if s.__class__.__name__ == "TaskStep")
ans = str(result)
n_tokens = models._estimate_tokens(ans)
# Only show sources the model actually appears to have USED in
# its final answer — not every link `web_search` happened to
# return this turn (most search hits are never read or relied on;
# dumping all of them produced a misleading "sources" list full
# of irrelevant results, e.g. random weather sites showing up for
# an unrelated question just because one search query returned
# them). general_agent.resolve_actually_used_sources() cross-
# checks the model's own '### References' section against what
# was really searched/visited this turn, falling back to pages
# actually opened via visit_webpage (never to the full link dump)
# if the model's citations don't check out. Its own (unverified)
# References section is then swapped out for this verified one.
queries, urls, links = general_agent.get_tool_usage()
used_sources = general_agent.resolve_actually_used_sources(ans, urls, links)
ans = general_agent.strip_trailing_references_section(ans)
if used_sources:
ans, used_sources = general_agent.renumber_citations(ans, used_sources)
# Same in-text [URL] / [page-title] -> [N] normalization as the
# RAG and Deep Research paths: small local models paste the raw
# source URL or page title into the bracket instead of the bare
# number. Refs here are renumbered (num, title, url) tuples, so
# either form resolves to the final number.
ans = rag_agent.normalize_in_text_citations(ans, used_sources)
ref_lines = ["**🔗 Sources used for this answer:**"]
for num, title, url in used_sources:
link_str = f"[{title}]({url})" if title != url else url
ref_lines.append(f"- [{num}] {link_str}")
ans += f"\n\n<div class=\"sources-block\">\n\n" + "\n".join(ref_lines) + "\n\n</div>"
formatted = format_llm_response(ans, lang_key)
# Surface compaction activity in the footer: how many times the
# rolling-summary compaction has run in this conversation (see
# agent_memory.compact_agent_memory()).
compacted_n = getattr(agent, "_compaction_count", 0) or 0
memory_txt = "off"
if use_memory:
memory_txt = f"on ({turn_count} turn(s))"
if compacted_n:
memory_txt = f"on ({turn_count} turn(s), compacted {compacted_n}×)"
# The effective step budget the agent ACTUALLY ran with (the
# model-scaled value when the Max Steps control is on auto — see
# _agent_steps_budget_txt) — so the footer shows what really ran.
steps_txt = _agent_steps_budget_txt(agent)
steps_seg = f"· {steps_txt} " if steps_txt else ""
# The effective per-step execution timeout — shown ONLY on the
# CodeAgent path, since only it has a Python executor (the helper
# gates on that; see agent_streaming._agent_exec_timeout_txt).
exec_txt = agent_streaming._agent_exec_timeout_txt(agent)
exec_seg = f"· {exec_txt} " if exec_txt else ""
response = (
formatted +
agent_streaming._agent_abort_html(lang_key, diag) +
f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
f"({DEVICE.upper()}) | agentic · web search + {_agent_mechanism_txt(use_tool_calling)} "
f"{steps_seg}{exec_seg}· memory: {memory_txt}</div>" + _agent_failure_hint(lang_key, diag)
)
export_text = _export_markdown(ans)
except Exception as e:
import traceback
response = f"❌ {e}\n\n{traceback.format_exc()}"
yield from _stream_final_text(history, response, export_text)
def chat_general(user_message: str, history: list, model_label: str,
use_agentic: bool = False, use_memory: bool = True,
lang_key: str = "kh",
max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
use_tool_calling: bool = True):
"""General Chat entry point. Dispatches to:
- use_agentic=False (default, unchanged behaviour): one direct LLM
call, no tools — see chat_general_direct().
- use_agentic=True: a ToolCallingAgent (CodeAgent when native tool
calling is unchecked) with web-search/webpage tools decides
for itself whether to look things up — see chat_general_agentic().
Same reliability caveat as agentic RAG Chat: works best with
capable models (roughly Gemma-4-E4B and above); small models may never
call a tool at all.
`use_memory` controls the "🧠 Conversation Memory" checkbox: whether
prior turns in this conversation are remembered (direct path) or kept
in the CodeAgent's own memory (agentic path). Memory is never
persisted to disk either way — see agent_memory.py.
A GENERATOR (via `yield from`): both branches are generators
themselves (chat_general_direct() yields once; chat_general_agentic()
yields once per live agent step — see agent_streaming.py), so callers
(ui.py) always iterate this the same way regardless of which mode is
selected, rather than needing to special-case "does this return a
generator or a plain tuple".
"""
if use_agentic:
yield from chat_general_agentic(user_message, history, model_label, use_memory, lang_key,
max_steps=max_steps, execution_timeout=execution_timeout,
use_tool_calling=use_tool_calling)
else:
yield from chat_general_direct(user_message, history, model_label, use_memory, lang_key)
def _stream_final_text(history: list, response: str, export_text):
"""Yield (history, second) once per chunk of the finished answer,
accumulating the text into a new assistant message as it goes.
The second tuple slot — the plain-markdown answer for .docx export — is
attached ONLY to the LAST chunk, so the "final yield carries the answer"
contract is uniform with chat_rag_direct()'s single final yield; every
intermediate chunk yields "". (The UI handler only reads the last
value, but a future consumer mid-stream must never see the answer early.)
When a WS run owns the live bus (get_bus().running), the model's tokens
were ALREADY streamed into the answer bubble live by the `live` WS
events — re-chunking the finished text here would visibly re-type the
whole answer on top of the live stream. Skip the pacing and yield the
complete answer in ONE chunk so the reveal is atomic (and the uniform
final-yield/export contract still holds)."""
history.append({"role": "assistant", "content": ""})
if get_bus().running:
history[-1]["content"] = response
yield history, export_text or ""
return
chunks = agent_streaming.chunk_final_text(response)
last_idx = len(chunks) - 1
acc = ""
for i, piece in enumerate(chunks):
acc += piece
history[-1]["content"] = acc
yield history, (export_text or "") if i == last_idx else ""
def _export_markdown(ans) -> str:
"""docx-export copy of a chat answer: strip every HTML tag (via the
shared _strip_html_tags primitive, the same one _strip_response_html
uses for conversation memory) so the exported .docx gets clean
markdown instead of divs, classes, or any other HTML a model may emit.
This covers both the app's own ``<div class="sources-block">…</div>``
references wrapper AND stray model-emitted markup (`<table>`, `<br>`,
`<span class="…">`, …). Unlike _strip_response_html, the full bubble
transforms (details/final-answer-block/<hr> truncation) are NOT
applied — the answer is raw pre-formatting markdown, so a model-emitted
`<hr>` is a legitimate separator and must not truncate the export.
Returns "" for None/empty answers (nothing worth exporting)."""
if not ans:
return ""
return _strip_html_tags(str(ans))
# ──────────────────────────────────────────────────────────────────────
# Visual grounding — the visual index (byaldi/ColPali page images) wired
# into RAG chat. When the question matches pages in the visual index, the
# answer is produced (direct path) or refined (agentic path) by the RAG
# chat's OWN model (the same model already serving the text answer — no
# second VLM loaded into VRAM) looking at BOTH the retrieved text context
# and the actual page images — grounded image answers for charts / scans /
# image-heavy PDFs that text extraction misses. Everything degrades
# gracefully: no visual index → [] (a cheap directory check — the 2-8 GB
# retriever model is only loaded when an index actually exists), the RAG
# model not being multimodal or load/generation failing → None → the
# text-only LLM path runs exactly as before.
# ──────────────────────────────────────────────────────────────────────
def _visual_grounding_images(question: str, top_k: int = 3) -> list:
"""Page images from the visual index most relevant to `question`, or
[] when the index is empty / unavailable. The cheap directory check
runs first — kb.visual_retrieve only loads the retriever model when
an index actually exists. Never raises."""
import os
if not os.path.exists(os.path.join(mr.VISUAL_INDEX_DIR, "main")):
return []
try:
return kb.visual_retrieve(question, top_k=top_k)
except Exception as e:
print(f"[RAG] visual page retrieval skipped: {e}")
return []
def _rag_model_can_see_images(model_id, provider=None) -> bool:
"""Cheap, no-load check that the RAG chat's OWN model is multimodal, so
the grounding pass never loads a second model (or triggers a retriever
load) just to discover it can't see images. The logic lives in
model_registry.is_multimodal_model — the SINGLE source of truth shared
with Deep Research's image visualizer — this wrapper keeps the chat-path
name the tests patch."""
return mr.is_multimodal_model(model_id, provider)
def _vlm_grounded_answer(question: str, images: list, context: str,
model_id, provider=None,
lang_key: str = "kh", n_ctx=None):
"""Answer `question` with the RAG chat's OWN model — the same model
already serving the text answer, so no second VLM is loaded into VRAM
(for a GGUF VLM on llama-server the grounding rides the SAME server
instance, restarted once with the mmproj; for a transformers VLM the
already-loaded LLM is reused). Grounded in the retrieved text `context`
AND the retrieved page `images`. Returns None when no images, the RAG
model isn't multimodal, or load/generation fails — the caller falls
back to the text-only LLM. Never raises."""
if not images:
return None
if not _rag_model_can_see_images(model_id, provider):
return None
try:
mmproj = mr.GGUF_VLM_MMPROJ_MAP.get(model_id)
ans = models.vlm_answer(question, images, context=context, model_id=model_id,
mmproj_path=mmproj, lang_key=lang_key, n_ctx=n_ctx,
provider=provider)
# A failed VLM generation surfaces as a ❌ error string from
# vlm_answer — treat it as unusable so the text-only LLM runs
# instead of shipping an error bubble as the answer.
if not ans or str(ans).lstrip().startswith("❌"):
return None
return ans
except Exception as e:
print(f"[RAG] VLM grounding unavailable — falling back to text: {e}")
return None
def _visual_footer_note(model_id, provider, lang_key, visual_pages,
visual_images, vlm_used) -> str:
"""The response-footer's visual-grounding segment (agentic RAG). Three
states:
* the grounding pass RAN → ' · 🖼️ VLM-grounded (N page image(s))'
* the AGENT used the visual index (its `visual_retriever` tool pulled
page images) but the RAG model is TEXT-ONLY — the VRAM-saving
same-model rule skipped the VLM, so say honestly that the pages
were retrieved but the answer was NOT image-verified.
* otherwise → '' (nothing visual happened this run).
"""
if vlm_used:
n = len(visual_images)
return (f" · 🖼️ VLM-grounded ({n} page image"
+ ("s" if n != 1 else "") + ")")
n = int(visual_pages or 0)
if n > 0 and not _rag_model_can_see_images(model_id, provider):
if lang_key == "kh":
return (f" · 🖼️ បានទាញរូបភាពទំព័រ {n} — ម៉ូដែល RAG មើលរូបភាពមិនបាន "
"(ចម្លើយមិនបានផ្ទៀងផ្ទាត់ជាមួយរូបភាព)")
return (f" · 🖼️ {n} page image" + ("s" if n != 1 else "")
+ " retrieved — RAG model is text-only (answer not image-verified)")
return ""
def chat_rag_direct(user_message: str, history: list, model_label: str, use_memory: bool = True,
theme: str = "", subtheme: str = "", lang_key: str = "kh",
sources: Optional[list] = None,
visual_retrieval: bool = False):
"""Non-agentic RAG: always retrieve context from ChromaDB first (same
retrieval call the agentic path's `retriever` tool wraps), then hand
that context straight to the LLM in one direct call — no CodeAgent,
no tool-calling, no code-generation steps to parse.
This exists because tool-calling reliability depends heavily on the
underlying model (see rag_agent.py's caveat about Gemma-4-E2B): small
or older models often never call the retriever tool, call it
malformed, or burn every retry step failing to parse, and end up
hallucinating or timing out instead of answering. Retrieval here is
unconditional and handled entirely by the app, so even a very small
model just has to read the provided context and answer — nothing to
invoke, nothing to parse.
"""
if not user_message.strip():
yield history, ""
return
history = history or []
history.append({"role": "user", "content": user_message})
provider = mr.get_saved_provider("rag")
model_id = mr.resolve_model_id(model_label, provider=provider)
n_ctx = mr.get_saved_context_window("rag")
ans = None # plain-markdown answer — the .docx export source (set in both success branches)
try:
# Immediate status yield so UI updates instantly before retrieval
status_msg = "📚 កំពុងទាញយកបរិបទ…" if lang_key == "kh" else "📚 Retrieving context…"
history.append({"role": "assistant", "content": status_msg})
yield history, ""
history.pop()
context, sources = kb.retrieve_context(user_message, theme, subtheme, sources=sources)
# Visual grounding: ALSO retrieve related PAGE IMAGES from the
# visual index (charts / scans / image-heavy PDFs that text
# extraction misses). When pages match, the RAG chat's OWN model
# (no second VLM loaded into VRAM) answers from both the text
# context and the actual images. Only attempted when the RAG model
# is itself multimodal — a text-only model skips the visual
# retrieval entirely (no wasted 2-8 GB retriever load).
visual_images = []
if visual_retrieval and _rag_model_can_see_images(model_id, provider):
# The FIRST visual retrieval lazily loads the 2-8 GB retriever
# model — announce that cold load with its own status line so the
# UI isn't stuck on "Context retrieved. Generating answer…" with
# no feedback for tens of seconds. When the model is already
# cached (warm), the bubble is skipped — no flicker, and the
# fast path stays untouched.
if kb.visual_retriever_needs_load():
vis_load_status = ("🖼️ កំពុងផ្ទុកលិបិក្រមរូបភាព…" if lang_key == "kh"
else "🖼️ Loading visual index…")
history.append({"role": "assistant", "content": vis_load_status})
yield history, ""
history.pop()
visual_images = _visual_grounding_images(user_message)
if not context and not visual_images:
ans = rag_agent.nothing_found_message(lang_key)
formatted = format_llm_response(ans, lang_key)
response = (
formatted +
f"\n\n<hr><sub>model: <code>{model_id}</code> ({DEVICE.upper()}) "
f"| direct RAG (no relevant context found)</sub>"
)
else:
system = _lang_instruction(lang_key) + (
"You are a strict retrieval-augmented assistant. Answer the "
"user's question using ONLY the context below, which was "
"retrieved from the user's own indexed knowledge base. Never "
"use your own general knowledge or training data, even if you "
"believe you know the answer. If the context doesn't contain "
"the answer, say clearly that the knowledge base doesn't "
"contain this information — do not guess or fill the gap "
"yourself.\n\n"
"CITATION REQUIREMENT: each context chunk below is tagged "
"with its source in brackets, e.g. '[report.pdf]'. Cite "
"each claim in-text with a bracketed NUMBER (e.g. [1], "
"[2]) assigned per source, and finish your answer with a "
"'### References' section mapping each number to its "
"source filename (e.g. '[1] report.pdf'). IMPORTANT: inside "
"the in-text brackets write ONLY the number — NEVER the "
"source filename (e.g. write [1], not [report.pdf]); "
"filenames appear only in the References section.\n\n"
f"Context:\n{context}"
)
# The retrieved context goes into the system prompt separately
# from memory, so reserve its token size in the memory budget —
# otherwise memory could crowd out a large retrieval (see
# _recent_memory_messages()'s `reserve_tokens`).
memory_messages = _recent_memory_messages(history[:-1], model_id=model_id,
provider=provider, n_ctx=n_ctx,
reserve_tokens=agent_memory.estimate_text_tokens(context)) if use_memory else []
if memory_messages:
system += (
"\n\nThe earlier turns of this conversation shown below "
"ARE genuinely visible to you in full — they are not "
"hidden or inaccessible. If asked what was said earlier "
"in this conversation, or a follow-up refers back to "
"something mentioned before, look at those earlier turns "
"and answer from them directly (this is separate from — "
"and does not override — the knowledge-base-only rule "
"above for actual content questions). Do NOT claim you "
"lack memory or cannot see prior messages — you can."
)
# ── "Answers the system prompt" guard ── (see
# chat_general_direct()'s identical block): the retrieved
# context currently ends the system message, and a small model
# that can't distinguish system from user roles latches onto
# that context blob (or the instructions) instead of the
# question. Repeating the question as the last SYSTEM content
# anchors the generation on it.
system += (
"\n\nThe user's question is:\n"
f"{user_message}\n"
"Answer that question directly now, citing from the context "
"above — do not respond to these instructions or repeat "
"the context."
)
status2_msg = "📚 បរិបទត្រូវបានទាញយក។ កំពុងបង្កើតចម្លើយ…" if lang_key == "kh" else "📚 Context retrieved. Generating answer…"
history.append({"role": "assistant", "content": status2_msg})
yield history, ""
history.pop()
# Visual grounding: when page images matched, let the saved
# Vision-tab VLM answer from the text context + the ACTUAL page
# images (the VLM is only loaded when images were retrieved).
vlm_used = False
if visual_retrieval and visual_images:
vis_status = ("🖼️ កំពុងផ្ទៀងផ្ទាត់ចម្លើយជាមួយរូបភាពទំព័រ…" if lang_key == "kh"
else "🖼️ Grounding the answer with page images…")
history.append({"role": "assistant", "content": vis_status})
yield history, ""
history.pop()
t_v = time.time()
vlm_ans = _vlm_grounded_answer(user_message, visual_images, context,
model_id, provider=provider,
lang_key=lang_key, n_ctx=n_ctx)
if vlm_ans:
ans, elapsed, vlm_used = vlm_ans, time.time() - t_v, True
if not vlm_used:
user_message_final = mr.apply_reasoning_toggle(user_message)
ans, elapsed, n_tokens = models._call_llm(model_id, system, user_message_final, history=memory_messages, provider=provider, n_ctx=n_ctx)
else:
n_tokens = models._estimate_tokens(ans)
refs = rag_agent.extract_verified_references(ans, sources)
ans = general_agent.strip_trailing_references_section(ans)
if refs:
# Renumber FIRST so the sequential [N] map is final, then
# rewrite in-text [filename] / (filename) markers the model
# pasted verbatim into their verified [N] / (N) form (small
# GGUFs often ignore the "numbers only" rule). Running the
# sanitizer BEFORE renumbering would leave parenthesized
# markers stale whenever the model's own reference numbers
# were non-sequential — renumber_citations only remaps
# [digits] brackets, never (N) parens.
used_sources = [(str(n), name, name) for n, name in refs]
ans, renumbered_refs = general_agent.renumber_citations(ans, used_sources)
ans = rag_agent.normalize_in_text_citations(
ans, [(int(n), name) for n, name, _ in renumbered_refs])
ref_lines = [f"- [{n}] {name}" for n, name, _ in renumbered_refs]
ans += f"\n\n<div class=\"sources-block\">\n\n**📚 References:**\n" + "\n".join(ref_lines) + "\n\n</div>"
formatted = format_llm_response(ans, lang_key)
_img_txt = "page image" if len(visual_images) == 1 else "page images"
mode_txt = (f"direct RAG · VLM-grounded ({len(visual_images)} {_img_txt})"
if vlm_used else "direct RAG")
response = (
formatted +
f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
f"({DEVICE.upper()}) | {mode_txt}</div>"
)
except Exception as e:
import traceback
response = f"❌ {e}\n\n{traceback.format_exc()}"
history.append({"role": "assistant", "content": response})
# The final yield carries the plain-markdown answer (second slot) so the
# UI can export it to .docx; "" (or None) means nothing to export.
yield history, _export_markdown(ans)
def chat_rag(user_message: str, history: list, model_label: str, use_agentic: bool = True, use_memory: bool = True,
theme: str = "", subtheme: str = "", max_steps: Optional[int] = None,
searcher_max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None,
lang_key: str = "kh", use_tool_calling: bool = True,
sources: Optional[list] = None,
visual_retrieval: bool = False):
"""RAG Chat entry point. `max_steps` / `searcher_max_steps` are the
agentic-mode step budgets for the manager and its `knowledge_searcher`
sub-agent respectively (the per-tab AgentControls in the web UI); None
uses each agent's model-scaled default. `visual_retrieval` (default
False) toggles the resource-intensive visual path: when OFF, neither the
page-image retrieval (the agent's `visual_retriever` tool in agentic
mode, or the direct visual-index query) nor the VLM grounding pass runs
— the RAG chat becomes a pure text-retrieval + text-LLM pipeline."""
if not use_agentic:
yield from chat_rag_direct(user_message, history, model_label, use_memory, theme, subtheme, lang_key,
sources=sources, visual_retrieval=visual_retrieval)
return
if not user_message.strip():
yield history, ""
return
history = history or []
history.append({"role": "user", "content": user_message})
# Immediate status yield so UI updates instantly before agent construction / retrieval
status_msg = "📚🤖 កំពុងរៀបចំប្រព័ន្ធ RAG…" if lang_key == "kh" else "📚🤖 Initializing RAG search agent…"
history.append({"role": "assistant", "content": status_msg})
yield history, ""
history.pop()
provider = mr.get_saved_provider("rag")
model_id = mr.resolve_model_id(model_label, provider=provider)
n_ctx = mr.get_saved_context_window("rag")
# Persisted step budgets (the per-tab "Max Steps" / "Search steps"
# controls): the WS payload's explicit values win; None falls back to
# the saved budgets, else AUTO (model-scaled defaults inside
# get_rag_agent / _build_searcher_agent).
max_steps = max_steps if max_steps is not None else mr.get_saved_agent_steps("rag")
searcher_max_steps = searcher_max_steps if searcher_max_steps is not None else mr.get_saved_sub_agent_steps("rag")
# Per-step code-execution timeout (the RAG "Exec timeout" control in
# agentic mode): the payload's explicit value wins; None falls back to
# the saved per-tab value, else AUTO (the agent factory's default).
execution_timeout = execution_timeout if execution_timeout is not None else mr.get_saved_execution_timeout("rag")
export_text = None # plain-markdown answer for .docx export (set when the run produced one)
try:
agent = rag_agent.get_rag_agent(model_id, theme, subtheme, max_steps,
searcher_max_steps=searcher_max_steps,
execution_timeout=execution_timeout,
use_tool_calling=use_tool_calling,
provider=provider, n_ctx=n_ctx,
sources=sources,
visual_retrieval=visual_retrieval)
rag_agent.reset_retriever_stats()
task = rag_agent.build_strict_task(user_message, lang_key, theme=theme, subtheme=subtheme, sources=sources)
task = mr.apply_reasoning_toggle(task)
t0 = time.time()
# Token-budget-aware memory compaction (see agent_memory.py) — same
# reasoning as chat_general_agentic(); the fixed turn-cap below stays
# as the post-run safety net.
if use_memory and _maybe_compact_agent_memory(agent, model_id, lang_key, tab_key="rag"):
history.append({"role": "assistant", "content": _compaction_status_msg(lang_key)})
yield history, ""
history.pop()
result = None
diag = None # snapshot from the stream's final yield (every stream path ends with one); stays None only if the loop never ran
for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key):
if not is_final:
if step_msg is not None:
history.append(step_msg)
yield history, ""
continue
result = final_output
if use_memory:
agent_memory.cap_agent_memory(agent, max_turns=AGENTIC_MEMORY_TURNS)
elapsed = time.time() - t0
call_count = 0 # defined so the footer below never NameErrors on the abort path
# visual-grounding state (footer + pass): the page images the
# grounding pass used (visual_images / vlm_used) plus the page-image
# count the agent's OWN visual_retriever tool pulled this run
# (visual_pages — read from get_visual_retriever_stats below, 0 on
# the abort/never-searched paths).
visual_images, vlm_used, visual_pages = [], False, 0
if diag and diag.get("aborted"):
# The fail-fast guard aborted this run — surface its guidance
# message instead of the "never searched" verdict (which would
# wrongly claim the agent never tried).
ans = str(result)
else:
call_count, found_count, sources_used = rag_agent.get_retriever_stats()
# The visual_retriever tool's OWN stats — the aggregate above
# mixes text + visual + summary tools, so it can't answer "did
# the agent use the visual index?" (the footer note's trigger).
_vis_calls, _vis_found, visual_pages = rag_agent.get_visual_retriever_stats()
# The never-searched / nothing-found verdict is user-facing, so it
# renders in the UI language (Khmer UI → Khmer message) — the
# hardcoded English constants were why a Khmer UI got an English
# "I didn't search…" answer.
if call_count == 0:
ans = rag_agent.never_searched_message(lang_key)
elif found_count == 0:
ans = rag_agent.nothing_found_message(lang_key)
else:
ans = str(result)
# Visual grounding pass: when the visual index has pages
# relevant to the question (either the ones the agent's OWN
# `visual_retriever` tool retrieved this run — cached — or a
# fresh query), have the SAME model (the RAG chat's own — no
# second VLM in VRAM) verify the agent's draft against the
# ACTUAL page images. Only attempted when the RAG model is
# itself multimodal; the stale tool cache is cleared either
# way.
visual_images = []
if visual_retrieval and _rag_model_can_see_images(model_id, provider):
visual_images = (kb.consume_visual_tool_hits()
or _visual_grounding_images(user_message))
else:
kb.consume_visual_tool_hits()
if visual_images:
vis_status = ("🖼️ កំពុងផ្ទៀងផ្ទាត់ចម្លើយជាមួយរូបភាពទំព័រ…" if lang_key == "kh"
else "🖼️ Grounding the answer with page images…")
history.append({"role": "assistant", "content": vis_status})
yield history, ""
history.pop()
grounded = _vlm_grounded_answer(
user_message,
visual_images,
context=("A text-search agent drafted this answer from the "
"knowledge base — verify it against the page images "
"above and produce the final grounded answer, "
"correcting anything the images contradict:\n\n"
f"{ans}"),
model_id=model_id, provider=provider,
lang_key=lang_key, n_ctx=n_ctx,
)
if grounded:
ans, vlm_used = grounded, True
refs = rag_agent.extract_verified_references(ans, sources_used)
ans = general_agent.strip_trailing_references_section(ans)
if refs:
# Same [filename] -> [N] / (filename) -> (N) normalization as
# the direct path — but run AFTER renumbering so the
# parenthesized markers carry the FINAL sequential numbers
# (renumber_citations only remaps [digits] brackets, so
# sanitizing before it would leave (N) parens stale for
# non-sequential reference numbers).
used_sources = [(str(n), name, name) for n, name in refs]
ans, renumbered_refs = general_agent.renumber_citations(ans, used_sources)
ans = rag_agent.normalize_in_text_citations(
ans, [(int(n), name) for n, name, _ in renumbered_refs])
ref_lines = [f"- [{n}] {name}" for n, name, _ in renumbered_refs]
ans += f"\n\n<div class=\"sources-block\">\n\n**📚 References:**\n" + "\n".join(ref_lines) + "\n\n</div>"
export_text = _export_markdown(ans)
n_tokens = models._estimate_tokens(ans)
formatted = format_llm_response(ans, lang_key)
# Surface compaction activity in the footer (see agent_memory.py).
compacted_n = getattr(agent, "_compaction_count", 0) or 0
memory_txt = "on" if use_memory else "off"
if use_memory and compacted_n:
memory_txt = f"on (compacted {compacted_n}×)"
# Effective step budget the manager + knowledge_searcher sub-agent
# actually ran with (model-scaled when the controls are on auto).
steps_txt = _agent_steps_budget_txt(agent)
steps_seg = f"· {steps_txt} " if steps_txt else ""
response = (
formatted +
agent_streaming._agent_abort_html(lang_key, diag) +
f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
f"({DEVICE.upper()}) | agentic RAG · {_agent_mechanism_txt(use_tool_calling)} · "
f"strict grounding (searched {call_count}x) {steps_seg}· memory: {memory_txt}"
+ _visual_footer_note(model_id, provider, lang_key, visual_pages,
visual_images, vlm_used)
+ "</div>"
+ _agent_failure_hint(lang_key, diag)
)
except Exception as e:
import traceback
response = f"❌ {e}\n\n{traceback.format_exc()}"
yield from _stream_final_text(history, response, export_text)
def chat_vision(user_message: str, uploaded_image, history: list,
vlm_label: str, use_memory: bool = True,
lang_key: str = "kh", mmproj_label: str = ""):
if not user_message.strip() and uploaded_image is None:
yield history, None, ""
return
history = history or []
history.append({"role": "user", "content": user_message or "(image)"})
# Immediate status yield so UI updates instantly before VLM processing
status_msg = "🖼️ កំពុងវិភាគរូបភាព…" if lang_key == "kh" else "🖼️ Analyzing image…"
history.append({"role": "assistant", "content": status_msg})
yield history, None, ""
history.pop()
provider = mr.get_saved_provider("vlm")
vlm_id = mr.resolve_model_id(vlm_label, provider=provider, model_type="vlm")
n_ctx = mr.get_saved_context_window("vlm")
ans = None # plain-markdown answer — the .docx export source (set in the success branch)
mmproj_path = mr.GGUF_VLM_MMPROJ_MAP.get(vlm_id) if not mmproj_label else None
if mmproj_label and vlm_id:
candidates = mr.get_mmproj_choices_for_vlm(vlm_id)
mmproj_path = candidates.get(mmproj_label) or mmproj_path
try:
vlm_model, _ = models.get_vlm(vlm_id, mmproj_path=mmproj_path, provider=provider, n_ctx=n_ctx)
pil_images = []
if uploaded_image is not None:
if isinstance(uploaded_image, Image.Image):
pil_images.append(uploaded_image)
elif isinstance(uploaded_image, str):
pil_images.append(Image.open(uploaded_image).convert("RGB"))
# The Vision tab is FULLY INDEPENDENT of the knowledge base: neither
# the vector-DB text context (kb.retrieve_context) nor the visual
# index image retrieval (kb.visual_retrieve) feed the VLM. A model
# asked to describe an uploaded image used to receive KB chunks /
# related images alongside it and would answer about that content
# instead of the image. Only the uploaded image(s) and the
# conversation-memory window (below) reach the VLM.
context = ""
recent = _recent_memory_messages(history[:-1], max_turns=3, model_obj=vlm_model, n_ctx=n_ctx) if use_memory else []
if recent:
convo = "\n".join(f"{t['role']}: {t['content']}" for t in recent)
context = f"Recent conversation:\n{convo}"
t0 = time.time()
ans = models.vlm_answer(user_message, pil_images, context=context, model_id=vlm_id, mmproj_path=mmproj_path, lang_key=lang_key, n_ctx=n_ctx)
elapsed = time.time() - t0
n_tokens = models._estimate_tokens(ans)
formatted = format_llm_response(ans, lang_key)
response = (
formatted +
f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | VLM: <code>{vlm_id}</code> ({DEVICE.upper()}) | images: {len(pil_images)}</div>"
)
except Exception as e:
import traceback
for h, exp in _stream_final_text(history, response, _export_markdown(ans)):
yield h, None, exp
def chat_data(user_message: str, history: list, model_label: str, files: list,
use_memory: bool = True, lang_key: str = "kh",
max_steps: Optional[int] = None,
worker_max_steps: Optional[int] = None,
execution_timeout: Optional[int] = None):
"""Data Analysis tab — the same chat shape as the other tabs: the EDA
CodeAgent (agents/data_analysis.run_data_analysis) runs against the
uploaded data files, live agent steps stream as thinking/working
bubbles, and the final report markdown is the answer bubble (the UI's
enhance pipeline converts it, exactly like the unwrapped raw-markdown
answers).
`files` are temp paths from /api/data/upload; the WS handler deletes
them after the run. `max_steps` is the manager's step budget and
`worker_max_steps` the data_worker sub-agent's (both AUTO when None —
the model-scaled defaults apply; a saved per-tab budget is used when
the payload leaves the field untouched). Yields (history, export) —
export carries the plain report markdown on the final yield only (the
.docx source)."""
history = history or []
# AUTO on the control = the tab's SAVED budget, then the model-scaled
# default (mirrors the RAG/Deep Research saved-budget plumbing).
if max_steps is None:
max_steps = mr.get_saved_agent_steps("data")
if worker_max_steps is None:
worker_max_steps = mr.get_saved_sub_agent_steps("data")
# Same saved-fallback as the other agentic tabs: the payload's explicit
# per-step code-execution timeout wins; None falls back to the SAVED
# Data-tab value (the "Exec timeout" preset), else AUTO (the tab's own
# DATA_EXECUTION_TIMEOUT_DEFAULT inside the worker builder).
if execution_timeout is None:
execution_timeout = mr.get_saved_execution_timeout("data")
# Immediate status yield so the UI updates before agent construction +
# CSV loading (the run's own first yield comes only once streaming
# actually starts).
status_msg = "📊 កំពុងវិភាគទិន្នន័យ…" if lang_key == "kh" else "📊 Analyzing data…"
history.append({"role": "assistant", "content": status_msg})
yield history, ""
history.pop()
from agents import data_analysis # lazy: heavy pandas/plotly imports
export_text = ""
try:
final = None
for h, gallery, report_file in data_analysis.run_data_analysis(
files or [], user_message, model_label, history,
use_memory=use_memory, lang_key=lang_key,
max_steps=max_steps, worker_max_steps=worker_max_steps,
execution_timeout=execution_timeout,
):
if gallery is None:
# Live agent step — the step message the stream appended is
# this turn's thinking/working bubble.
yield list(h), ""
else:
final = (h, gallery, report_file)
if final is not None:
h, _gallery, _report_file = final
content = (h[-1].get("content") or "") if h else ""
# Export = the report markdown minus the trailing <hr> footer
# (and the abort badge on failed runs) — the shared tag-strip
# keeps the .docx clean, never the footer text.
export_text = _export_markdown(content.split("<hr>")[0])
yield list(h), export_text
except Exception as e: # defensive — the WS layer also catches
history.append({"role": "assistant", "content": f"❌ {e}"})
yield list(history), ""
def chat_deep_research(user_message: str, history: list, model_label: str, use_memory: bool = True, use_playwright: bool = False, headless: bool = True, manager_max_steps: int = 12, search_max_steps: int = 6, timeout: int = 90, execution_timeout: Optional[int] = None, lang_key: str = "kh", use_tool_calling: bool = True):
"""Deep Research tab"""
if not user_message.strip():
yield history, ""
return
history = history or []
history.append({"role": "user", "content": user_message})
# Immediate status yield so UI updates instantly before agent construction
status_msg = "🔬🤖 កំពុងចាប់ផ្តើមការស្រាវជ្រាវ…" if lang_key == "kh" else "🔬🤖 Starting deep research…"
history.append({"role": "assistant", "content": status_msg})
yield history, ""
history.pop()
provider = mr.get_saved_provider("dr")
model_id = mr.resolve_model_id(model_label, provider=provider)
n_ctx = mr.get_saved_context_window("dr")
# Persisted step budgets (the per-tab "Manager steps" / "Search steps"
# controls): the WS payload's explicit values win; None falls back to
# the saved budgets, else the function's own defaults (12 / 6).
manager_max_steps = manager_max_steps if manager_max_steps is not None else mr.get_saved_agent_steps("dr")
search_max_steps = search_max_steps if search_max_steps is not None else mr.get_saved_sub_agent_steps("dr")
# Per-step code-execution timeout (the DrControls "Exec timeout" field
# in agentic mode): the payload's explicit value wins; None falls back
# to the saved per-tab value, else AUTO (the agent factory's default).
# DISTINCT from the whole-run `timeout` above — that one is the run
# deadline, enforced at the WS stream layer (web_api._run_stream), and
# is deliberately NOT threaded into the agent builders here (a wall-
# clock run budget must not double as a per-step executor cap).
# `timeout` is kept in the signature for backward compatibility with
# callers that pass it (it no longer affects agent construction).
execution_timeout = execution_timeout if execution_timeout is not None else mr.get_saved_execution_timeout("dr")
export_text = None # plain-markdown answer for .docx export (set when the run produced one)
try:
agent = deep_research_agent.get_deep_research_agent(
model_id, use_playwright, headless, manager_max_steps, search_max_steps,
execution_timeout, use_tool_calling=use_tool_calling, provider=provider, n_ctx=n_ctx)
deep_research_agent.reset_tool_usage()
t0 = time.time()
# reset=False keeps the manager's own memory (its steps include
# every call it made to web_search_agent) across turns — same
# smolagents pattern as every other agentic tab. Capped right
# after so a long research conversation doesn't grow the prompt
# unboundedly turn after turn.
#
# Wrapped with a per-task citation reminder (NOT just the raw
# user_message) for the same reason as chat_general_agentic()
# above: DEEP_RESEARCH_INSTRUCTIONS' citation requirement only
# reaches the manager if this smolagents version's CodeAgent
# accepts `instructions=` — on a version where it doesn't, this
# is the only place the requirement is ever stated.
task = deep_research_agent.build_task_with_citation_reminder(user_message, lang_key)
# See chat_general_direct()'s matching comment — a no-op unless
# the "🧠 Enable Model Reasoning" toggle is off. This is the tab
# most likely to benefit: a heavy thinking-tuned manager model
# (e.g. Gemma-4-26B-A4B) burning its whole MAX_NEW_TOKENS budget
# on internal reasoning is exactly what produces the "Executing
# parsed code:" steps with an EMPTY body / Out: None seen in
# practice on this tab.
task = mr.apply_reasoning_toggle(task)
# Live step streaming — the manager's OWN steps stream (its
# thought/code, and each call it makes to the `web_search_agent`
# sub-agent shows up as a tool-call-shaped line with that call's
# returned text as the "output"). The search sub-agent's own
# internal steps don't stream separately — deep_research_agent.py's
# managed_agents mechanism runs it as one synchronous Python call
# from inside the manager's executed code, same as smolagents
# itself — but seeing each delegated sub-question and what it
# found, live, is already a large improvement over a single
# "thinking…" line for however many minutes the whole multi-step
# research run takes (see MANAGER_DEFAULT_MAX_STEPS's comment in
# deep_research_agent.py).
# Token-budget-aware memory compaction (see agent_memory.py) — same
# reasoning as chat_general_agentic(); Deep Research turns are the
# heaviest (manager + sub-agent calls), so it defaults to one recent
# turn kept verbatim (tunable in Settings) and the fixed turn-cap
# below stays as the post-run safety net.
if use_memory and _maybe_compact_agent_memory(agent, model_id, lang_key, tab_key="dr"):
history.append({"role": "assistant", "content": _compaction_status_msg(lang_key)})
yield history, ""
history.pop()
result = None
diag = None # snapshot from the stream's final yield (every stream path ends with one); stays None only if the loop never ran
for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key):
if not is_final:
if step_msg is not None:
history.append(step_msg)
yield history, ""
continue
result = final_output
if use_memory:
agent_memory.cap_agent_memory(agent, max_turns=DEEP_RESEARCH_MEMORY_TURNS)
elapsed = time.time() - t0
turn_count = sum(1 for s in agent.memory.steps if s.__class__.__name__ == "TaskStep")
ans = str(result)
n_tokens = models._estimate_tokens(ans)
# Same verified-sources approach as General Chat's agentic mode —
# reuses general_agent's own citation-checking helpers rather than
# duplicating that logic, since they're generic string/list
# functions with no dependency on general_agent's own tool state.
queries, urls, links = deep_research_agent.get_tool_usage()
used_sources = general_agent.resolve_actually_used_sources(ans, urls, links)
ans = general_agent.strip_trailing_references_section(ans)
if used_sources:
ans, used_sources = general_agent.renumber_citations(ans, used_sources)
# Same in-text [URL] / [page-title] -> [N] normalization as the
# RAG paths: the manager is told to cite with bare numbers, but
# small local models often paste the whole source URL or page
# title into the bracket instead. The renumbered refs are
# (num, title, url) tuples, so a bracket containing EITHER the
# title OR the URL resolves to the source's final number.
ans = rag_agent.normalize_in_text_citations(ans, used_sources)
ref_lines = ["**🔗 Sources used for this report:**"]
for num, title, url in used_sources:
link_str = f"[{title}]({url})" if title != url else url
ref_lines.append(f"- [{num}] {link_str}")
ans += f"\n\n<div class=\"sources-block\">\n\n" + "\n".join(ref_lines) + "\n\n</div>"
export_text = _export_markdown(ans)
formatted = format_llm_response(ans, lang_key)
# Surface compaction activity in the footer (see agent_memory.py).
compacted_n = getattr(agent, "_compaction_count", 0) or 0
memory_txt = "off"
if use_memory:
memory_txt = f"on ({turn_count} turn(s))"
if compacted_n:
memory_txt = f"on ({turn_count} turn(s), compacted {compacted_n}×)"
# Effective step budgets the manager + web_search_agent sub-agent
# actually ran with (model-scaled when the controls are on auto).
steps_txt = _agent_steps_budget_txt(agent)
steps_seg = f"· {steps_txt} " if steps_txt else ""
response = (
formatted +
agent_streaming._agent_abort_html(lang_key, diag) +
f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
f"({DEVICE.upper()}) | deep research · {_agent_mechanism_txt(use_tool_calling)} · "
f"manager + web-search sub-agent {steps_seg}· memory: {memory_txt}</div>"
+ _agent_failure_hint(lang_key, diag)
)
except Exception as e:
import traceback
response = f"❌ {e}\n\n{traceback.format_exc()}"
yield from _stream_final_text(history, response, export_text)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891"""
component_downloader.py — On-demand downloader for heavy external tools & binaries
(llama-server.exe, whisper-server.exe, Poppler, Playwright Chromium).
Keeps initial setup ultra-fast and lightweight (~200MB) by deferring multi-GB optional
downloads to the UI.
"""
import os
import re
import sys
import json
import shutil
import zipfile
import urllib.request
import subprocess
import time
from pathlib import Path
from backend.paths import third_party_dir
from backend.llama_health import _gpu_name
CREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0
THIRD_PARTY_DIR = third_party_dir()
_READ_CHUNK_BYTES = 256 * 1024
_MB = 1024 * 1024
def _safe_extract_zip(zip_path: Path, target_dir: Path) -> None:
"""Safely extract a zip archive preventing Zip Slip (path traversal) vulnerabilities."""
target_dir = target_dir.resolve()
target_dir.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
for member in zip_ref.infolist():
member_path = (target_dir / member.filename).resolve()
try:
member_path.relative_to(target_dir)
except ValueError:
raise RuntimeError(
f"Zip Slip detected: archive member '{member.filename}' escapes target directory '{target_dir}'."
)
zip_ref.extractall(target_dir)
# Fallback URLs used only when the GitHub API is unreachable (offline /
# rate-limited). These are known-good at the time of writing; the API path
# always resolves the true latest release first.
_FALLBACK_URLS = {
"llama_server_cpu": "https://github.com/ggml-org/llama.cpp/releases/download/b10276/llama-b10276-bin-win-cpu-x64.zip",
"llama_server_cuda12": "https://github.com/ggml-org/llama.cpp/releases/download/b10276/llama-b10276-bin-win-cuda-12.4-x64.zip",
"llama_server_cuda13": "https://github.com/ggml-org/llama.cpp/releases/download/b10276/llama-b10276-bin-win-cuda-13.3-x64.zip",
"llama_server_cudart_cuda12": "https://github.com/ggml-org/llama.cpp/releases/download/b10276/cudart-llama-bin-win-cuda-12.4-x64.zip",
"llama_server_cudart_cuda13": "https://github.com/ggml-org/llama.cpp/releases/download/b10276/cudart-llama-bin-win-cuda-13.3-x64.zip",
"whisper_server": "https://github.com/ggerganov/whisper.cpp/releases/download/v1.9.2/whisper-bin-x64.zip",
"whisper_server_cuda11": "https://github.com/ggerganov/whisper.cpp/releases/download/v1.9.2/whisper-cublas-11.8.0-bin-x64.zip",
"whisper_server_cuda12": "https://github.com/ggerganov/whisper.cpp/releases/download/v1.9.2/whisper-cublas-12.4.0-bin-x64.zip",
"poppler": "https://github.com/oschwartz10612/poppler-windows/releases/download/v26.02.0-0/Release-26.02.0-0.zip",
}
def _latest_release_info(repo: str, timeout: float = 30.0):
"""Fetch a GitHub repo's latest release as (tag, assets) where `tag` is
the release tag (e.g. llama.cpp's 'b10276', whisper.cpp's 'v1.9.2') and
`assets` are its (name, download_url) pairs. Returns (None, []) on any
failure — never raises, so callers can fall back to the hardcoded URLs.
The llama-server path uses the tag to SHOW the user which release it is
about to install (the popup's detection report + the download log), so a
download always resolves the LATEST release when the API is reachable and
says so when it had to fall back to a pinned build."""
url = f"https://api.github.com/repos/{repo}/releases/latest"
req = urllib.request.Request(url, headers={"User-Agent": "LocalAILab/1.0"})
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
data = json.load(resp)
return (
data.get("tag_name"),
[(a["name"], a["browser_download_url"]) for a in data.get("assets", [])],
)
except Exception:
return None, []
def _latest_release_assets(repo: str):
"""Asset (name, download_url) pairs of a GitHub repo's latest release.
Returns [] on any failure — never raises, so callers can fall back to the
hardcoded URLs."""
return _latest_release_info(repo)[1]
def _llama_version_from_url(url: str) -> str:
"""Extract the llama.cpp release tag from an asset URL, e.g.
'https://github.com/ggml-org/llama.cpp/releases/download/b10276/'
'llama-b10276-bin-win-cuda-12.4-x64.zip' -> 'b10276'. Returns '' when the
URL does not carry a tag (should not happen for the app's own URLs)."""
m = re.search(r"/releases/download/([^/]+)/", url or "")
if m:
return m.group(1)
m = re.search(r"llama-([\w.]+)-bin", url or "")
return m.group(1) if m else ""
def _driver_cuda_version():
"""NVIDIA driver's supported CUDA version (e.g. '13.0') or None."""
try:
from backend import hardware
return hardware.HardwareManager.detect_nvidia_cuda_version()
except Exception:
return None
def _cuda_tuple(name: str):
"""Parse the CUDA tier out of an asset name like
'llama-b10276-bin-win-cuda-13.3-x64.zip' -> (13, 3)."""
m = re.search(r"cuda[-_]?(\d+)\.(\d+)", name)
if not m:
return (0, 0)
try:
return (int(m.group(1)), int(m.group(2)))
except ValueError:
return (0, 0)
def _version_tuple(ver):
"""Parse a dotted version string ('13.0', '12.4.58') into (major, minor)
so it can be compared against the CUDA tiers. Returns None if unparseable."""
try:
parts = str(ver).split(".")
return (int(parts[0]), int(parts[1]) if len(parts) > 1 else 0)
except (TypeError, ValueError):
return None
def _pick_cudart_asset(assets, cuda_tier):
"""Find the cudart DLLs zip matching a chosen CUDA build's tier, e.g.
tier (13, 3) -> 'cudart-llama-bin-win-cuda-13.3-x64.zip'. Returns the
(name, url) pair, or None when the release has no matching split."""
if cuda_tier is None or cuda_tier == (0, 0):
return None
want = f"cudart-llama-bin-win-cuda-{cuda_tier[0]}.{cuda_tier[1]}-x64.zip"
for name, url in assets:
if name == want:
return (name, url)
return None
def _pick_llama_asset_for_choice(choice: str, assets):
"""Resolve the llama-server build for an EXPLICIT user choice ('cpu' /
'cuda12' / 'cuda13') from the release assets, falling back to the
known-good URLs when the GitHub API is unreachable (the same tier logic
as the auto path). Returns (url, cudart_url_or_None) — the CPU build
bundles no CUDA runtime DLLs, so its cudart is always None."""
# Prefer x64 builds (exclude arm64) so a Windows x64 box never grabs an
# ARM binary, matching the auto path's `_pick_llama_asset` filter.
x64 = [x for x in assets if "x64" in x[0]]
if x64:
assets = x64
if choice in ("cuda12", "cuda13"):
tier = (12, 4) if choice == "cuda12" else (13, 3)
for n, u in assets:
if (
n.startswith("llama-") and "win" in n and "cuda" in n
and n.endswith(".zip") and _cuda_tuple(n) == tier
):
cudart = _pick_cudart_asset(assets, tier)
return u, (cudart[1] if cudart else None)
if choice == "cuda12":
return _FALLBACK_URLS["llama_server_cuda12"], _FALLBACK_URLS["llama_server_cudart_cuda12"]
return _FALLBACK_URLS["llama_server_cuda13"], _FALLBACK_URLS["llama_server_cudart_cuda13"]
# CPU
for n, u in assets:
if n.startswith("llama-") and "win" in n and "cpu" in n and n.endswith(".zip"):
return u, None
return _FALLBACK_URLS["llama_server_cpu"], None
def get_llama_server_download_plan() -> dict:
"""Detect which llama-server builds are AVAILABLE on this machine and
report each with a bilingual reason — the Settings popup shows the user
every viable option and lets THEM choose, instead of silently picking
one (mirrors HardwareManager.get_llama_cpp_install_plan for
llama-cpp-python).
Unlike the llama-cpp-python wheels, every llama-server CUDA build ships
its OWN CUDA runtime DLLs (the matching cudart zip downloads beside the
exe), so the ONLY hardware gate is an NVIDIA GPU whose DRIVER's
supported CUDA version (nvidia-smi's "CUDA Version" / "CUDA UMD
Version") is at least the build's tier: the CUDA 12.4 build needs a
12.x-capable driver, the CUDA 13.3 build needs 13.3+.
Returns {
"detected": {gpu_brand, gpu_name, cpu_name, driver_cuda_version,
driver_tuple},
"options": [ {"id", "label_key", "reason_key", "params",
"available", "recommended"}, ... ],
}
The option `id` is one of: auto / cpu / cuda12 / cuda13. `auto` and
`cpu` are always available; each CUDA tier only when the NVIDIA driver
can actually run it.
"""
from backend import hardware
status = hardware.HardwareManager.get_system_status()
brand = status.get("gpu_brand") or "none"
driver_ver = _driver_cuda_version()
driver_t = _version_tuple(driver_ver)
gpu_name = _gpu_name()
cpu_name = hardware._cpu_name()
# The llama.cpp release the download will resolve — the LATEST release
# tag when the GitHub API answers (short timeout so an offline machine's
# popup is not blocked long), None when it can't be checked. The download
# itself always re-resolves the latest at download time.
release_tag, _assets = _latest_release_info("ggml-org/llama.cpp", timeout=6)
detected = {
"gpu_brand": brand,
"gpu_name": gpu_name,
"cpu_name": cpu_name,
"driver_cuda_version": driver_ver,
"driver_tuple": driver_t,
"release_tag": release_tag,
}
def _cuda_option(cid, ok_key, old_driver_key, tier, recommended):
if brand == "nvidia":
if driver_t is not None and driver_t >= tier:
return {
"id": cid,
"label_key": f"llsrv_opt_{cid}",
"reason_key": ok_key,
"params": {"driver": driver_ver},
"available": True,
"recommended": recommended,
}
reason_key = "llsrv_reason_cuda_no_driver" if driver_t is None else old_driver_key
params = {} if driver_t is None else {"driver": driver_ver}
else:
reason_key, params = "llsrv_reason_cuda_requires_nvidia", {}
return {
"id": cid,
"label_key": f"llsrv_opt_{cid}",
"reason_key": reason_key,
"params": params,
"available": False,
"recommended": False,
}
# Recommended = the highest CUDA tier the driver can run (CUDA 13.3
# preferred, else CUDA 12.4); no GPU → nothing recommended (auto stays
# the dialog's default selection).
rec13 = brand == "nvidia" and driver_t is not None and driver_t >= (13, 3)
rec12 = (
brand == "nvidia" and driver_t is not None
and (12, 0) <= driver_t < (13, 3)
)
options = [
{
"id": "auto",
"label_key": "llsrv_opt_auto",
"reason_key": "llsrv_reason_auto",
"params": {},
"available": True,
"recommended": False,
},
{
"id": "cpu",
"label_key": "llsrv_opt_cpu",
"reason_key": "llsrv_reason_cpu_always",
"params": {},
"available": True,
"recommended": False,
},
_cuda_option("cuda12", "llsrv_reason_cuda12_ok", "llsrv_reason_cuda12_old_driver", (12, 0), rec12),
_cuda_option("cuda13", "llsrv_reason_cuda13_ok", "llsrv_reason_cuda13_old_driver", (13, 3), rec13),
]
return {"detected": detected, "options": options}
def _pick_whisper_asset_for_choice(choice: str, assets):
"""Resolve the whisper-server build for an EXPLICIT user choice ('cuda11'
/ 'cuda12') from the release assets, falling back to the known-good URL.
The CPU build (whisper-bin-x64.zip) is the auto/cpu default handled by
the caller. Returns the download URL."""
want = "11.8" if choice == "cuda11" else "12.4"
for n, u in assets:
if n.startswith("whisper-cublas-") and want in n and "x64" in n and n.endswith(".zip"):
return u
return _FALLBACK_URLS[f"whisper_server_cuda{choice[-2:]}"]
def get_whisper_server_download_plan() -> dict:
"""Detect which whisper-server builds are AVAILABLE on this machine and
report each with a bilingual reason — the Settings popup shows the user
every viable option and lets THEM choose (mirrors
get_llama_server_download_plan / get_llama_cpp_install_plan).
Unlike llama-server's CUDA builds (which bundle their own runtime DLLs),
whisper.cpp's cuBLAS builds need the CUDA RUNTIME DLLs installed on the
machine (cublas64_11.dll / cublas64_12.dll from the CUDA toolkit), so the
gate is the INSTALLED CUDA runtime major — exactly like the
llama-cpp-python wheels. The available Windows x64 builds are
`whisper-bin-x64.zip` (CPU) plus the cuBLAS 11.8 / cuBLAS 12.4 builds.
Returns {
"detected": {gpu_brand, gpu_name, cpu_name, cuda_runtime_major},
"options": [ {"id", "label_key", "reason_key", "params",
"available", "recommended"}, ... ],
}
The option `id` is one of: auto / cpu / cuda11 / cuda12. `auto` and
`cpu` are always available; each cuBLAS tier only when the matching CUDA
runtime DLL family is installed.
"""
from backend import hardware
status = hardware.HardwareManager.get_system_status()
brand = status.get("gpu_brand") or "none"
runtime_major = hardware.HardwareManager.detect_installed_cuda_runtime_major()
gpu_name = _gpu_name()
cpu_name = hardware._cpu_name()
detected = {
"gpu_brand": brand,
"gpu_name": gpu_name,
"cpu_name": cpu_name,
"cuda_runtime_major": runtime_major,
}
def _cuda_option(cid, ok_key, mismatch_key, tier, recommended):
if brand == "nvidia" and runtime_major == tier:
return {
"id": cid,
"label_key": f"wsrv_opt_{cid}",
"reason_key": ok_key,
"params": {"runtime": runtime_major},
"available": True,
"recommended": recommended,
}
if brand != "nvidia":
reason_key, params = "wsrv_reason_cuda_requires_nvidia", {}
elif runtime_major is None:
reason_key, params = "wsrv_reason_cuda_no_runtime", {}
else:
reason_key, params = mismatch_key, {"runtime": runtime_major}
return {
"id": cid,
"label_key": f"wsrv_opt_{cid}",
"reason_key": reason_key,
"params": params,
"available": False,
"recommended": False,
}
# Recommended = the highest installed CUDA runtime tier that matches a
# shipped build (CUDA 12 preferred, else CUDA 11); no matching runtime →
# nothing recommended (auto stays the dialog's default selection).
rec12 = brand == "nvidia" and runtime_major == 12
rec11 = brand == "nvidia" and runtime_major == 11
options = [
{
"id": "auto",
"label_key": "wsrv_opt_auto",
"reason_key": "wsrv_reason_auto",
"params": {},
"available": True,
"recommended": False,
},
{
"id": "cpu",
"label_key": "wsrv_opt_cpu",
"reason_key": "wsrv_reason_cpu_always",
"params": {},
"available": True,
"recommended": False,
},
_cuda_option("cuda11", "wsrv_reason_cuda11_ok", "wsrv_reason_cuda11_mismatch", 11, rec11),
_cuda_option("cuda12", "wsrv_reason_cuda12_ok", "wsrv_reason_cuda12_mismatch", 12, rec12),
]
return {"detected": detected, "options": options}
def _pick_llama_asset(assets):
"""Choose the best llama.cpp Windows binary for this machine.
Prefers the CUDA build when an NVIDIA driver is present, matching the
driver's CUDA tier when a compatible build exists (a driver reporting
12.6 runs the CUDA 12.4 build, not the CUDA 13.3 one); when the driver
is older than every available build, the safest CUDA build is chosen
rather than the newest. Falls back to the CPU build when no GPU is
present.
"""
win = [x for x in assets if x[0].startswith("llama-") and "win" in x[0] and x[0].endswith(".zip")]
if not win:
return None
# Prefer x64 builds (exclude arm64) so we never grab an ARM binary on a
# typical x64 Windows box when the CPU branch is selected.
x64 = [x for x in win if "x64" in x[0]]
if x64:
win = x64
driver_ver = _driver_cuda_version()
cuda = [x for x in win if "cuda" in x[0]]
if driver_ver and cuda:
driver_t = _version_tuple(driver_ver)
if driver_t is not None:
compatible = [x for x in cuda if _cuda_tuple(x[0]) <= driver_t]
if compatible:
return max(compatible, key=lambda x: _cuda_tuple(x[0]))
# Old driver (e.g. reports 12.0 / 11.x): the newest build is the
# least likely to load, so fall back to the oldest CUDA build.
return min(cuda, key=lambda x: _cuda_tuple(x[0]))
return min(cuda, key=lambda x: _cuda_tuple(x[0]))
cpu = [x for x in win if "cpu" in x[0]]
if cpu:
return cpu[0]
return win[0]
def _flatten(root):
"""Move every file found under `root` up to `root` itself, dropping the
now-empty subfolders.
The GitHub release zips extract into versioned subfolders
(e.g. llama-b10276-bin-win-cuda-13.3-x64/llama-server.exe or
Release/whisper-server.exe), so the exe is almost never at the archive
root — and its sibling DLLs (ggml.dll, ggml-cuda.dll, whisper.dll, ...)
must stay beside it for Windows to load them. Flattening keeps the exe
and every DLL it imports in one flat folder.
"""
if not root.is_dir():
return
for sub in list(root.iterdir()):
if not sub.is_dir():
continue
for p in sub.rglob("*"):
if p.is_file():
dest = root / p.name
if dest.exists():
dest.unlink()
shutil.move(str(p), str(dest))
shutil.rmtree(str(sub), ignore_errors=True)
def _remove_llama_leftovers(third_party):
"""Remove artifacts of previous download layouts (loose .exe/.dll files directly
under third_party/) so all binaries strictly reside in their dedicated subfolders."""
for p in third_party.iterdir():
name = p.name
if p.is_file() and (name.endswith(".dll") or name.endswith(".exe") or name.startswith("llama-b") or name.startswith("cudart-llama")):
try:
p.unlink()
except Exception:
pass
elif p.is_dir() and (name.startswith("llama-b") or name.startswith("cudart-llama")):
shutil.rmtree(str(p), ignore_errors=True)
def _configure_llama_server_path(exe_path: str) -> None:
"""Persist the canonical exe path into llama_backend's config so the
downloaded binary is immediately usable (and survives restarts)."""
from backend import llama_backend
llama_backend.set_llama_server_exe_path(exe_path)
def _configure_whisper_server_path(exe_path: str) -> None:
"""Persist the canonical exe path into whisper_cpp_backend's config."""
from backend import whisper_cpp_backend
whisper_cpp_backend.set_whisper_server_exe_path(exe_path)
def _manual_llama_server_instructions(target_dir: Path, llama_url: str, cudart_url: str | None = None,
cpu_url: str | None = None) -> str:
"""Return plain-English manual recovery instructions for llama-server."""
lines = [
"🧰 Manual install option:",
f"1. Download the llama-server ZIP: [llama-server ZIP]({llama_url})",
]
if cudart_url:
lines.append(f"2. Download the matching CUDA runtime ZIP: [CUDA runtime ZIP]({cudart_url})")
lines.append(f"3. Extract both ZIPs into: {target_dir}")
lines.append("4. Make sure llama-server.exe and all DLLs end up in that folder together.")
elif cpu_url:
lines.append(f"2. If you want the CPU fallback instead, download: [CPU llama-server ZIP]({cpu_url})")
lines.append(f"3. Extract it into: {target_dir}")
lines.append("4. Make sure llama-server.exe and its DLLs stay side by side in that folder.")
else:
lines.append(f"2. Extract it into: {target_dir}")
lines.append("3. Make sure llama-server.exe and its DLLs stay side by side in that folder.")
return "\n".join(lines) + "\n"
def _manual_single_zip_instructions(title: str, url: str, target_dir: Path, notes: list[str] | None = None) -> str:
"""Return manual recovery instructions for a single downloadable ZIP."""
lines = [
f"🧰 Manual install option for {title}:",
f"1. Download: [{title} ZIP]({url})",
f"2. Extract into: {target_dir}",
]
if notes:
for idx, note in enumerate(notes, start=3):
lines.append(f"{idx}. {note}")
return "\n".join(lines) + "\n"
def _manual_playwright_instructions() -> str:
"""Return manual recovery instructions for Chromium/Playwright."""
return (
"🧰 Manual install option for Playwright Chromium:\n"
"1. Open a terminal in this app's environment.\n"
"2. Run: .venv\\Scripts\\python.exe -m playwright install chromium\n"
"3. If the app is frozen, use the Settings tab's Playwright installer instead.\n"
)
def _download_with_progress(url, dest, label, retries: int = 3, retry_delay: float = 2.0):
"""Stream a file to `dest` in chunks, yielding live progress log lines.
Replaces the blocking urllib.request.urlretrieve() so a multi-hundred-MB
download (llama-server, whisper-server, Poppler) shows a stream of
progress updates in the UI log textbox instead of appearing frozen at
"📥 Downloading..." until the whole file has been transferred.
"""
last_exc = None
for attempt in range(1, max(1, retries) + 1):
downloaded = 0
try:
if dest.exists():
try:
dest.unlink()
except Exception:
pass
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=60) as resp:
content_length = resp.headers.get("Content-Length")
total = int(content_length) if content_length else None
last_pct = -1
with open(dest, "wb") as f:
while True:
chunk = resp.read(_READ_CHUNK_BYTES)
if not chunk:
break
f.write(chunk)
downloaded += len(chunk)
if total:
pct = int(downloaded * 100 / total)
if pct != last_pct:
last_pct = pct
yield (
f"📥 Downloading {label}... "
f"{downloaded / _MB:.1f} / {total / _MB:.1f} MB ({pct}%)\n"
)
elif downloaded // _MB != (downloaded - len(chunk)) // _MB:
yield f"📥 Downloading {label}... {downloaded / _MB:.1f} MB\n"
yield f"✅ Downloaded {label}: {os.path.basename(str(dest))} ({downloaded / _MB:.1f} MB)\n"
return
except Exception as exc:
last_exc = exc
if dest.exists():
try:
dest.unlink()
except Exception:
pass
if attempt >= max(1, retries):
raise
yield (
f"⚠️ Download failed for {label} on attempt {attempt}/{retries}: {exc}. "
f"Retrying...\n"
)
time.sleep(retry_delay * attempt)
if last_exc is not None:
raise last_exc
def _playwright_cmd(args):
"""Return the argv needed to run the Playwright CLI.
Works both in the dev environment and inside the PyInstaller-frozen app.
IMPORTANT: in a frozen build `sys.executable` IS LocalAiLab_App.exe, so
`sys.executable -m playwright ...` would re-launch the whole app and cause
a self-replicating process fork-bomb. Always use Playwright's bundled node
driver instead.
"""
try:
from playwright._impl._driver import compute_driver_executable
node_exe, cli_js = compute_driver_executable()
return [node_exe, cli_js] + list(args)
except Exception:
if getattr(sys, "frozen", False):
return None
return [sys.executable, "-m", "playwright"] + list(args)
def get_component_statuses() -> dict:
third_party = THIRD_PARTY_DIR
llama_exe = third_party / "llama-server" / "llama-server.exe"
whisper_exe = third_party / "whisper-server" / "whisper-server.exe"
poppler_dir = third_party / "poppler"
playwright_ok = False
cmd = _playwright_cmd(["--version"])
if cmd:
try:
res = subprocess.run(
cmd, capture_output=True, text=True, check=False, timeout=30,
creationflags=CREATE_NO_WINDOW,
)
playwright_ok = (res.returncode == 0)
except Exception:
playwright_ok = False
return {
"llama_server": llama_exe.exists(),
"whisper_server": whisper_exe.exists(),
"poppler": poppler_dir.exists() and any(
(p / "Library" / "bin" / "pdftoppm.exe").exists()
for p in poppler_dir.iterdir()
),
"playwright": playwright_ok,
}
def download_component_gen(component_name: str, choice: str | None = None):
third_party = THIRD_PARTY_DIR
third_party.mkdir(parents=True, exist_ok=True)
yield f"🚀 Starting component setup for: {component_name}...\n"
try:
if component_name == "llama_server":
def _cpu_llama_url(assets_list):
cpu_asset = next(
(
(n, u)
for n, u in assets_list
if n.startswith("llama-") and "win" in n and "cpu" in n and n.endswith(".zip")
),
None,
)
return cpu_asset[1] if cpu_asset else _FALLBACK_URLS["llama_server_cpu"]
release_tag, assets = _latest_release_info("ggml-org/llama.cpp")
# An EXPLICIT user choice (from the Settings popup: cpu /
# cuda12 / cuda13) overrides auto-detection. The tier is still
# resolved from the real release when possible, falling back to
# the known-good URLs. auto (None) keeps the historical pick.
if choice in ("cpu", "cuda12", "cuda13"):
url, cudart_url = _pick_llama_asset_for_choice(choice, assets)
cudart = (None, cudart_url) if cudart_url else None
if choice == "cpu":
yield "ℹ️ CPU llama-server selected (no GPU offload).\n"
else:
tier_label = "CUDA 12.4" if choice == "cuda12" else "CUDA 13.3"
yield f"ℹ️ {tier_label} llama-server selected (NVIDIA GPU offload, runtime DLLs bundled).\n"
else:
asset = _pick_llama_asset(assets)
if asset:
url = asset[1]
cudart = _pick_cudart_asset(assets, _cuda_tuple(asset[0]))
else:
# GitHub API unreachable — use the last-known-good URLs.
# Pick CUDA vs CPU from the driver, and within CUDA pick the
# tier the driver supports, matching the API path's logic.
driver_t = _version_tuple(_driver_cuda_version())
if driver_t is not None and driver_t >= (13, 3):
url = _FALLBACK_URLS["llama_server_cuda13"]
cudart = (None, _FALLBACK_URLS["llama_server_cudart_cuda13"])
elif driver_t is not None:
url = _FALLBACK_URLS["llama_server_cuda12"]
cudart = (None, _FALLBACK_URLS["llama_server_cudart_cuda12"])
else:
url = _FALLBACK_URLS["llama_server_cpu"]
cudart = None
# The version being installed, made explicit: the resolved URL's
# own release tag, labeled '(latest)' when it IS the live latest
# release, else an honest '(not the latest — offline/older fallback)'
# so a pinned build is never silently passed off as current.
version = _llama_version_from_url(url)
if release_tag and version == release_tag:
version_note = f"release {version} (latest)"
else:
version_note = f"release {version} (not the latest — offline/older fallback)"
_remove_llama_leftovers(third_party)
target_dir = third_party / "llama-server"
target_dir.mkdir(parents=True, exist_ok=True)
for f in target_dir.iterdir():
if f.is_dir():
shutil.rmtree(str(f), ignore_errors=True)
else:
try:
f.unlink()
except Exception:
pass
target_zip = third_party / "llama-server.zip"
yield (f"📥 Downloading llama-server from GitHub Releases — {version_note}...\n"
f"Download URL: [llama-server ZIP]({url})\n")
for line in _download_with_progress(url, target_zip, "llama-server"):
yield line
yield "📦 Extracting llama-server.exe...\n"
_safe_extract_zip(target_zip, target_dir)
if target_zip.exists():
target_zip.unlink()
# Flatten the versioned subfolder so llama-server.exe sits next
# to every DLL it imports.
_flatten(target_dir)
fallback_to_cpu = False
if cudart:
yield (f"📥 Downloading matching CUDA runtime DLLs (cudart/cublas)...\n"
f"Download URL: [CUDA runtime ZIP]({cudart[1]})\n")
cudart_zip = third_party / "cudart.zip"
try:
for line in _download_with_progress(cudart[1], cudart_zip, "CUDA runtime"):
yield line
yield "📦 Extracting CUDA runtime DLLs...\n"
_safe_extract_zip(cudart_zip, target_dir)
if cudart_zip.exists():
cudart_zip.unlink()
_flatten(target_dir)
except Exception as e:
fallback_to_cpu = True
yield (
f"⚠️ CUDA runtime download or extraction failed ({e}). "
f"Falling back to CPU llama-server so setup can still finish.\n"
)
yield _manual_llama_server_instructions(
target_dir,
url,
cudart_url=cudart[1],
cpu_url=_cpu_llama_url(assets),
)
if fallback_to_cpu:
shutil.rmtree(str(target_dir), ignore_errors=True)
target_dir.mkdir(parents=True, exist_ok=True)
cpu_url = _cpu_llama_url(assets)
target_zip = third_party / "llama-server-cpu.zip"
yield f"📥 Downloading CPU llama-server instead...\nDownload URL: [CPU llama-server ZIP]({cpu_url})\n"
for line in _download_with_progress(cpu_url, target_zip, "llama-server (CPU)"):
yield line
yield "📦 Extracting CPU llama-server.exe...\n"
_safe_extract_zip(target_zip, target_dir)
if target_zip.exists():
target_zip.unlink()
_flatten(target_dir)
yield _manual_llama_server_instructions(target_dir, cpu_url, cpu_url=cpu_url)
canonical = target_dir / "llama-server.exe"
if canonical.exists():
_configure_llama_server_path(str(canonical))
yield "✅ llama-server.exe downloaded, extracted and path configured in Settings!\n"
else:
yield "❌ Could not locate llama-server.exe inside the archive.\n"
elif component_name == "whisper_server":
assets = _latest_release_assets("ggerganov/whisper.cpp")
# An EXPLICIT user choice (from the Settings popup: cuda11 /
# cuda12) picks the matching cuBLAS build. auto (None) / cpu keep
# the historical CPU build.
if choice in ("cuda11", "cuda12"):
url = _pick_whisper_asset_for_choice(choice, assets)
tier_label = "CUDA 11.8" if choice == "cuda11" else "CUDA 12.4"
yield (f"ℹ️ {tier_label} whisper-server selected (NVIDIA GPU offload — "
f"needs the matching CUDA runtime installed).\n")
else:
win = next(((n, u) for n, u in assets if n == "whisper-bin-x64.zip"), None)
url = win[1] if win else _FALLBACK_URLS["whisper_server"]
stale_exe = third_party / "whisper-server.exe"
if stale_exe.exists():
try:
stale_exe.unlink()
except Exception:
pass
target_dir = third_party / "whisper-server"
target_dir.mkdir(parents=True, exist_ok=True)
for f in target_dir.iterdir():
if f.is_dir():
shutil.rmtree(str(f), ignore_errors=True)
else:
try:
f.unlink()
except Exception:
pass
target_zip = third_party / "whisper-server.zip"
yield f"📥 Downloading whisper-server from GitHub Releases...\nDownload URL: [whisper-server ZIP]({url})\n"
for line in _download_with_progress(url, target_zip, "whisper-server"):
yield line
yield "📦 Extracting whisper-server.exe...\n"
_safe_extract_zip(target_zip, target_dir)
if target_zip.exists():
target_zip.unlink()
# whisper.cpp's release zip puts everything under a Release/
# subfolder — flatten so the exe sits next to its DLLs.
_flatten(target_dir)
canonical = target_dir / "whisper-server.exe"
if canonical.exists():
_configure_whisper_server_path(str(canonical))
yield "✅ whisper-server.exe downloaded, extracted and path configured in Settings!\n"
else:
yield "❌ Could not locate whisper-server.exe inside the archive.\n"
elif component_name == "poppler":
assets = _latest_release_assets("oschwartz10612/poppler-windows")
win = next(((n, u) for n, u in assets if n.startswith("Release-") and n.endswith(".zip")), None)
url = win[1] if win else _FALLBACK_URLS["poppler"]
target_zip = third_party / "poppler.zip"
poppler_out = third_party / "poppler"
yield f"📥 Downloading Poppler PDF Utilities (~30MB)...\nDownload URL: [Poppler ZIP]({url})\n"
for line in _download_with_progress(url, target_zip, "Poppler"):
yield line
yield "📦 Extracting Poppler to third_party/poppler...\n"
_safe_extract_zip(target_zip, poppler_out)
if target_zip.exists():
target_zip.unlink()
yield "✅ Poppler PDF Utilities installed successfully!\n"
elif component_name == "playwright":
yield "📥 Installing Playwright Chromium browser (~170MB)...\n"
cmd = _playwright_cmd(["install", "chromium"])
if not cmd:
yield "❌ Playwright is not bundled in this build; cannot install Chromium here.\n"
else:
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
creationflags=CREATE_NO_WINDOW,
)
for line in proc.stdout:
yield line
proc.wait()
if proc.returncode == 0:
yield "✅ Playwright Chromium installed successfully!\n"
else:
yield f"❌ Playwright Chromium installation failed with exit code {proc.returncode}\n"
else:
yield f"❌ Unknown component: {component_name}\n"
except Exception as e:
yield f"❌ Download/Installation failed: {str(e)}\n"
if component_name == "llama_server":
try:
assets = _latest_release_assets("ggml-org/llama.cpp")
asset = _pick_llama_asset(assets)
llama_url = asset[1] if asset else _FALLBACK_URLS["llama_server_cpu"]
cudart_url = None
if asset:
cudart = _pick_cudart_asset(assets, _cuda_tuple(asset[0]))
cudart_url = cudart[1] if cudart else None
yield _manual_llama_server_instructions(
THIRD_PARTY_DIR / "llama-server",
llama_url,
cudart_url=cudart_url,
cpu_url=_FALLBACK_URLS["llama_server_cpu"],
)
except Exception:
pass
elif component_name == "whisper_server":
try:
assets = _latest_release_assets("ggerganov/whisper.cpp")
win = next(((n, u) for n, u in assets if n == "whisper-bin-x64.zip"), None)
url = win[1] if win else _FALLBACK_URLS["whisper_server"]
yield _manual_single_zip_instructions(
"whisper-server",
url,
THIRD_PARTY_DIR / "whisper-server",
notes=["Make sure whisper-server.exe stays beside its DLLs."],
)
except Exception:
pass
elif component_name == "poppler":
try:
assets = _latest_release_assets("oschwartz10612/poppler-windows")
win = next(((n, u) for n, u in assets if n.startswith("Release-") and n.endswith(".zip")), None)
url = win[1] if win else _FALLBACK_URLS["poppler"]
yield _manual_single_zip_instructions(
"Poppler",
url,
THIRD_PARTY_DIR / "poppler",
notes=["The app expects the extracted 'Library\\bin' folder inside third_party\\poppler."],
)
except Exception:
pass
elif component_name == "playwright":
try:
yield _manual_playwright_instructions()
except Exception:
pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293"""backend/docx_export.py — Shared Markdown → Word (.docx) exporter.
Single source of truth for converting Markdown reports/answers into Word
(.docx) documents via python-docx. The Data Analysis tab converts its
agent-written `report.md` with markdown_to_docx(); any other tab (RAG,
Deep Research, …) can offer Word export of an answer by handing the raw
text to markdown_text_to_docx().
Self-contained on purpose: only the stdlib plus a lazy python-docx import
(the same lazy-import convention as knowledge_base.index_docx_file), so
importing this module never drags in the heavy model stack. Both public
functions are total — bad markup, missing files, or a missing python-docx
degrade to a plain-text Word document or None, and never raise into a
chat handler.
Public API
----------
markdown_to_docx(md_path, image_search_dirs=None, max_chars=200_000)
Read a Markdown file and write a .docx beside it (md_path with a
.docx suffix). Returns the .docx path, or None (unreadable/missing
source, no python-docx).
markdown_text_to_docx(markdown_text, docx_path, image_search_dirs=None,
max_chars=200_000)
Convert Markdown TEXT directly into a Word document at docx_path —
the building block the file version delegates to. Use this when the
markdown lives in memory (e.g. a chat answer) rather than on disk.
Supported Markdown (best effort, everything else → plain text): headings,
bullet/numbered lists, blockquotes, fenced code blocks, tables,
horizontal rules, standalone images (embedded when the file exists), and
inline **bold** / *italic* / `code` / [links].
"""
import re
from pathlib import Path
from typing import Optional
def _strip_inline(text: str) -> str:
"""Plain-text version of a markdown line (for headings): drop **bold**,
*italic*, `code`, and [text](url) markup."""
text = re.sub(r'`([^`]+)`', r'\1', text)
text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text)
text = re.sub(r'\*([^*]+)\*', r'\1', text)
return re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
def _add_hr(document) -> None:
"""Thin bottom-bordered separator paragraph for a markdown `---` rule."""
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
p = document.add_paragraph()
pPr = p._p.get_or_add_pPr()
pBdr = OxmlElement('w:pBdr')
bottom = OxmlElement('w:bottom')
bottom.set(qn('w:val'), 'single')
bottom.set(qn('w:sz'), '6')
bottom.set(qn('w:space'), '1')
bottom.set(qn('w:color'), '999999')
pBdr.append(bottom)
pPr.append(pBdr)
def _add_rich_text(paragraph, text: str) -> None:
"""Best-effort inline markdown → docx runs: **bold**, *italic*,
`code`, and [text](url) links (rendered as text + URL)."""
from docx.shared import Pt
token_re = re.compile(r'(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*|\[[^\]]+\]\([^)]+\))')
for tok in token_re.split(text):
if not tok:
continue
if len(tok) > 4 and tok.startswith('**') and tok.endswith('**'):
r = paragraph.add_run(tok[2:-2])
r.bold = True
elif len(tok) > 2 and tok.startswith('`') and tok.endswith('`'):
r = paragraph.add_run(tok[1:-1])
r.font.name = 'Consolas'
r.font.size = Pt(9.5)
else:
m = re.match(r'\[([^\]]+)\]\(([^)]+)\)', tok)
if m:
r = paragraph.add_run(m.group(1))
r.bold = True
r2 = paragraph.add_run(f' ({m.group(2)})')
r2.font.size = Pt(8.5)
elif len(tok) > 2 and tok.startswith('*') and tok.endswith('*'):
r = paragraph.add_run(tok[1:-1])
r.italic = True
else:
paragraph.add_run(tok)
def _resolve_image(ref: str, base_dir: Path,
search_dirs: Optional[list] = None) -> Optional[Path]:
"""Resolve a markdown image reference to a real file: absolute path,
relative to the document's own directory, or relative to any of the
caller-provided image search directories (e.g. the data-analysis
output dir where matplotlib charts land)."""
p = Path(ref)
if not p.is_absolute():
candidates = [base_dir / p]
if search_dirs:
candidates += [Path(d) / p for d in search_dirs]
for c in candidates:
if c.is_file():
return c
return None
return p if p.is_file() else None
def markdown_text_to_docx(markdown_text: str, docx_path: str,
image_search_dirs: Optional[list] = None,
max_chars: int = 200_000) -> Optional[str]:
"""Convert Markdown TEXT into a Word (.docx) document at `docx_path`.
Best-effort markdown → OOXML (see the module docstring for the
supported constructs). Anything that fails to map cleanly falls back
to plain text, and on any unexpected error the raw text is written as
plain paragraphs so a Word export is still produced. Returns
`docx_path` on success, or None only if python-docx is unavailable
and even the fallback fails. Never raises.
"""
try:
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches, Pt
except Exception:
return None
try:
out = Path(docx_path)
out.parent.mkdir(parents=True, exist_ok=True)
text = (markdown_text or '')[:max_chars]
document = docx.Document()
lines = text.split('\n')
i = 0
while i < len(lines):
line = lines[i].rstrip('\r')
stripped = line.strip()
# Fenced code block
if stripped.startswith('```'):
i += 1
while i < len(lines) and not lines[i].strip().startswith('```'):
p = document.add_paragraph()
r = p.add_run(lines[i])
r.font.name = 'Consolas'
r.font.size = Pt(9)
i += 1
i += 1 # skip the closing fence
continue
# Markdown table: consecutive | ... | rows, skipping |---|---|
# separators. Guarded against indented-code lines whose stripped
# form starts with '|' (only non-indented pipe lines are tables).
if (stripped.startswith('|') and stripped.endswith('|')
and '|' in stripped[1:-1]
and line and line[0] not in (' ', '\t')):
j = i
table_rows = []
while (j < len(lines)
and (not lines[j] or lines[j][0] not in (' ', '\t'))
and lines[j].strip().startswith('|')
and lines[j].strip().endswith('|')):
table_rows.append(lines[j].strip())
j += 1
rows = []
for tr in table_rows:
cells = [c.strip() for c in tr.strip('|').split('|')]
if all(re.fullmatch(r':?-{2,}:?', c) for c in cells if c):
continue # separator row
rows.append(cells)
if len(rows) >= 2:
ncols = max(len(r) for r in rows)
table = document.add_table(rows=len(rows), cols=ncols)
try:
table.style = 'Table Grid'
except Exception:
pass
for ri, cells in enumerate(rows):
for ci in range(ncols):
table.rows[ri].cells[ci].text = (
cells[ci] if ci < len(cells) else '')
document.add_paragraph()
i = j
continue
# Heading
m = re.match(r'^(#{1,6})\s+(.*)$', stripped)
if m:
document.add_heading(_strip_inline(m.group(2)),
level=min(len(m.group(1)), 6))
i += 1
continue
# Horizontal rule
if re.fullmatch(r'([-*_])\1{2,}', stripped):
_add_hr(document)
i += 1
continue
# Blockquote
if stripped.startswith('>'):
p = document.add_paragraph()
p.paragraph_format.left_indent = Inches(0.3)
r = p.add_run(stripped.lstrip('> ').strip())
r.italic = True
i += 1
continue
# Bullet list
m = re.match(r'^[-*+]\s+(.*)$', stripped)
if m:
p = document.add_paragraph(style='List Bullet')
_add_rich_text(p, m.group(1))
i += 1
continue
# Numbered list
m = re.match(r'^\d+[.)]\s+(.*)$', stripped)
if m:
p = document.add_paragraph(style='List Number')
_add_rich_text(p, m.group(1))
i += 1
continue
# Image on its own line
m = re.match(r'^!\[([^\]]*)\]\(([^)]+)\)$', stripped)
if m:
img = _resolve_image(m.group(2), out.parent, image_search_dirs)
if img:
p = document.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
try:
p.add_run().add_picture(str(img), width=Inches(6))
cap = m.group(1).strip()
if cap:
cp = document.add_paragraph()
cp.alignment = WD_ALIGN_PARAGRAPH.CENTER
cr = cp.add_run(cap)
cr.italic = True
cr.font.size = Pt(8.5)
i += 1
continue
except Exception:
pass # image load failed → fall through to alt text
p = document.add_paragraph()
_add_rich_text(p, m.group(1) or m.group(2))
i += 1
continue
if not stripped:
i += 1
continue
# Plain paragraph
p = document.add_paragraph()
_add_rich_text(p, stripped)
i += 1
document.save(str(out))
return str(out)
except Exception:
# Absolute fallback: dump the raw text as plain paragraphs so a
# Word export is still available even if a construct mis-parsed.
try:
document = docx.Document()
for ln in text.split('\n'):
document.add_paragraph(ln)
document.save(str(out))
return str(out)
except Exception:
return None
def markdown_to_docx(md_path: str,
image_search_dirs: Optional[list] = None,
max_chars: int = 200_000) -> Optional[str]:
"""Read a Markdown file and write a .docx beside it (same name with a
.docx suffix). Returns the .docx path, or None if the source is
missing/unreadable or python-docx is unavailable. Never raises."""
try:
md = Path(md_path)
if not md.is_file():
return None
text = md.read_text(encoding='utf-8', errors='replace')
except Exception:
# Unreadable source (locked/permission) → no Word export at all;
# never raise into the chat handler.
return None
return markdown_text_to_docx(
text, str(md.with_suffix('.docx')),
image_search_dirs=image_search_dirs, max_chars=max_chars)123456789101112131415161718192021222324252627282930313233343536373839category,label,model_id,download_size_gb,defaultboth,🦙 Gemma-4-E2B QAT Q4_0 (~1.8 GB download | GGUF | HF Hub),google/gemma-4-E2B-it-qat-q4_0-gguf,1.8,defaultboth,🦙 Gemma-4-E4B QAT Q4_0 (~2.8 GB download | GGUF | HF Hub),google/gemma-4-E4B-it-qat-q4_0-gguf,2.8,both,🦙 Gemma-4-12B QAT Q4_0 (~7.5 GB download | GGUF | HF Hub),google/gemma-4-12B-it-qat-q4_0-gguf,7.5,both,🦙 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,15.2,both,🦙 Gemma-4-31B QAT Q4_0 (~18.5 GB download | GGUF | HF Hub),google/gemma-4-31B-it-qat-q4_0-gguf,18.5,llm,🧠 Qwen2.5-Coder-7B-Instruct Q4_K_M (~4.7 GB download | GGUF | HF Hub | code-tuned),Qwen/Qwen2.5-Coder-7B-Instruct-GGUF,4.7,llm,🧠 Qwen2.5-Coder-14B-Instruct Q4_K_M (~9.0 GB download | GGUF | HF Hub | code-tuned),Qwen/Qwen2.5-Coder-14B-Instruct-GGUF,9,llm,🧠 Qwen2.5-Coder-32B-Instruct Q4_K_M (~19.9 GB download | GGUF | HF Hub | code-tuned),Qwen/Qwen2.5-Coder-32B-Instruct-GGUF,19.9,llm,🧠 Qwen3-Coder-30B-A3B-Instruct Q4_K_M (~18.6 GB download | MoE GGUF | HF Hub | code-tuned | thinking),unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF,18.6,llm,🧠 Qwen3-4B Q8_0 (~4.3 GB download | GGUF | HF Hub | verified on Data agent),Qwen/Qwen3-4B-GGUF,4.3,vlm,🔭 Qwen3-VL-2B Q4_K_M (~1.1 GB download | GGUF | HF Hub | VLM),Qwen/Qwen3-VL-2B-Instruct-GGUF,1.1,vlm,🔭 Qwen3-VL-4B Q4_K_M (~2.3 GB download | GGUF | HF Hub | VLM),Qwen/Qwen3-VL-4B-Instruct-GGUF,2.3,vlm,🔭 Qwen3-VL-8B Q4_K_M (~4.7 GB download | GGUF | HF Hub | VLM),Qwen/Qwen3-VL-8B-Instruct-GGUF,4.7,llm,🧠 Muse-Glimmer-30B Q4_K_M (~16.8 GB download | GGUF | HF Hub | agentic | planning-off),meta-models/Muse-Glimmer-30B-GGUF,16.8,llm,🧠 GLM-4.7-Flash UD-TQ1_0 (~8.3 GB download | GGUF | HF Hub | MoE | ⚠ unverified quant — weak instruction/multilingual quality),unsloth/GLM-4.7-Flash-GGUF#GLM-4.7-Flash-UD-TQ1_0.gguf,8.3,llm,🧠 GLM-4.7-Flash Q2_K (~11.3 GB download | GGUF | HF Hub | MoE | CPU/RAM-friendly),unsloth/GLM-4.7-Flash-GGUF#GLM-4.7-Flash-Q2_K.gguf,11.3,llm,🧠 GLM-4.7-Flash Q2_K_L (~11.4 GB download | GGUF | HF Hub | MoE | CPU/RAM-friendly),unsloth/GLM-4.7-Flash-GGUF#GLM-4.7-Flash-Q2_K_L.gguf,11.4,llm,🧠 GLM-4.7-Flash Q3_K_M (~14.6 GB download | GGUF | HF Hub | MoE | mid-tier CPU/GPU),unsloth/GLM-4.7-Flash-GGUF#GLM-4.7-Flash-Q3_K_M.gguf,14.6,llm,🧠 GLM-4.7-Flash Q4_0 (~17.2 GB download | GGUF | HF Hub | MoE),unsloth/GLM-4.7-Flash-GGUF#GLM-4.7-Flash-Q4_0.gguf,17.2,llm,🧠 GLM-4.7-Flash Q4_K_S (~17.3 GB download | GGUF | HF Hub | MoE),unsloth/GLM-4.7-Flash-GGUF#GLM-4.7-Flash-Q4_K_S.gguf,17.3,llm,🧠 GLM-4.7-Flash Q4_K_M (~18.3 GB download | GGUF | HF Hub | MoE | 24 GB VRAM),unsloth/GLM-4.7-Flash-GGUF#GLM-4.7-Flash-Q4_K_M.gguf,18.3,llm,🧠 Qwen3.8-27B UD-IQ2_XXS (~9.0 GB download | GGUF | HF Hub | CPU/RAM-friendly),unsloth/Qwen3.8-27B-GGUF#Qwen3.8-27B-UD-IQ2_XXS.gguf,9,llm,🧠 Qwen3.8-27B Q3_K_S (~12.6 GB download | GGUF | HF Hub | mid-tier CPU/GPU),unsloth/Qwen3.8-27B-GGUF#Qwen3.8-27B-Q3_K_S.gguf,12.6,both,🧠 Qwen3.8-27B Q4_K_M (~17.1 GB + 0.9 GB mmproj download | GGUF | HF Hub | 24 GB VRAM | VLM),unsloth/Qwen3.8-27B-GGUF#Qwen3.8-27B-Q4_K_M.gguf#mmproj-F16.gguf,17.1,llm,🧠 Gemma-3n-E2B-it F16 (~8.9 GB download | GGUF | HF Hub),mradermacher/gemma-3n-E2B-GGUF#gemma-3n-E2B.f16.gguf,8.92,llm,🧠 Gemma-3n-E4B-it F16 (~13.7 GB download | GGUF | HF Hub),mradermacher/gemma-3n-E4B-it-GGUF#gemma-3n-E4B-it.f16.gguf,13.7,embed,🔎 Qwen3-Embedding-0.6B Q8_0 (~0.6 GB download | GGUF | HF Hub | multilingual),Qwen/Qwen3-Embedding-0.6B-GGUF,0.6,embed,🔎 nomic-embed-text-v1.5 Q8_0 (~0.1 GB download | GGUF | HF Hub | sentence similarity),nomic-ai/nomic-embed-text-v1.5-GGUF,0.1,embed,🔎 EmbeddingGemma-300M Q8_0 (~0.3 GB download | GGUF | HF Hub | lightweight),unsloth/embeddinggemma-300m-GGUF,0.3,stt,🎙️ Whisper-tiny GGUF (~0.04 GB download | whisper.cpp),ggerganov/whisper.cpp#ggml-tiny.bin,0.04,defaultstt,🎙️ Whisper-base GGUF (~0.07 GB download | whisper.cpp),ggerganov/whisper.cpp#ggml-base.bin,0.07,stt,🎙️ Whisper-small GGUF (~0.24 GB download | whisper.cpp),ggerganov/whisper.cpp#ggml-small.bin,0.24,stt,🎙️ Whisper-large-v3-turbo GGUF (~0.81 GB download | whisper.cpp),ggerganov/whisper.cpp#ggml-large-v3-turbo.bin,0.81,stt,🎙️ Whisper-large-v3 GGUF (~1.5 GB download | whisper.cpp),ggerganov/whisper.cpp#ggml-large-v3.bin,1.5,stt,🎙️ VibeVoice-ASR-BitNet (~13 GB download | GGUF | ASR),microsoft/VibeVoice-ASR-BitNet,13,stt,🇰🇭 Qwen3-ASR-0.6B-Khmer F16 (~0.38 GB download | GGUF | Khmer ASR),mradermacher/Qwen3-ASR-0.6B-Khmer-GGUF#Qwen3-ASR-0.6B-Khmer.f16.gguf,0.38,stt,🎙️ Gemma-3n-E2B ASR F16 (~8.92 GB download | GGUF | HF Hub),mradermacher/gemma-3n-E2B-GGUF#gemma-3n-E2B.f16.gguf,8.92,stt,🎙️ Gemma-3n-E4B ASR F16 (~13.7 GB download | GGUF | HF Hub),mradermacher/gemma-3n-E4B-it-GGUF#gemma-3n-E4B-it.f16.gguf,13.7,123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794"""
hardware.py — GPU/device detection and the "Fix Environment" self-repair
helper (installs a hardware-matched PyTorch build at runtime).
"""
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Optional
import torch
import warnings
# Windows flag to suppress creating a console window for spawned subprocesses
CREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0
# ── Frozen-build pip helpers ───────────────────────────────────────────────
# In the PyInstaller/Store build sys.executable is the app exe (not Python),
# so we ship a minimal bundled Python+pip alongside the app and use it for
# all runtime pip installs (GPU PyTorch, llama-cpp-python, agent packages).
# Packages install into user_data/packages/ (writable, isolated from the
# frozen bundle) and the startup hook (pyi_rth_smolagents_source.py) adds
# that directory to sys.path + torch/lib to os.environ["PATH"].
FROZEN_PYTHON_EXE: Optional[str] = None # resolved once, cached
def _find_frozen_python() -> Optional[str]:
"""Locate the bundled Python interpreter shipped with the frozen app.
The build pipeline (build_standalone.py) downloads the Python embeddable
package, adds pip, and places it in <app>/python/. This function finds
that interpreter so pip-based installs work in the packaged build.
Returns the path to python.exe or None when unavailable.
"""
global FROZEN_PYTHON_EXE
if FROZEN_PYTHON_EXE is not None:
return FROZEN_PYTHON_EXE
if not getattr(sys, "frozen", False):
return None
# APP_ROOT = parent of internal/ (the PyInstaller contents_directory).
app_root = Path(sys._MEIPASS).parent
candidate = app_root / "python" / "python.exe"
if candidate.is_file():
FROZEN_PYTHON_EXE = str(candidate)
return FROZEN_PYTHON_EXE
return None
def _frozen_pip_target() -> str:
"""Return the --target directory for pip installs in the frozen build.
Packages land in user_data/packages/ which the startup hook adds to
sys.path (and torch/lib to os.environ["PATH"]).
"""
from backend.paths import user_data_dir
return str(user_data_dir() / "packages")
def _pip_base_args() -> list:
"""Return the base pip-install command prefix.
In the frozen build the bundled Python+pip is used and every install
targets user_data/packages/ (--target) for isolation. In dev/venv
builds the normal sys.executable is used.
"""
frozen_py = _find_frozen_python()
if frozen_py:
return [frozen_py, "-m", "pip", "install", "--target", _frozen_pip_target()]
return [sys.executable, "-m", "pip", "install"]
# Canonical GPU-detection helpers live in llama_health (which never imports
# backend modules, so there is no import cycle). Reuse them here instead of
# maintaining a second copy — the compute-capability signal decides whether
# any CUDA wheel can actually run on this machine.
from backend.llama_health import _gpu_compute_capability, _gpu_name
def _llama_cpp_cpu_wheel_url() -> Optional[str]:
"""Prebuilt CPU wheel for llama-cpp-python on Windows (any Python 3.x).
`pip install llama-cpp-python` without an explicit wheel URL resolves to
the sdist and builds from source — which needs a C/C++ toolchain that most
end-user PCs (and always the packaged Microsoft Store build) don't have,
so the install fails out of the box. Every CPU fallback must therefore
install this prebuilt wheel instead. Returns None on non-Windows, where
the plain PyPI package remains the fallback."""
if sys.platform != "win32":
return None
return (
"https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34/"
"llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
)
def _llama_cpp_vulkan_wheel_url() -> Optional[str]:
"""Prebuilt Vulkan wheel for llama-cpp-python on Windows — hardware
offload for AMD/Intel GPUs via the Vulkan backend. Like the CPU wheel it
is built WITHOUT AVX-512 code paths, so it loads on the same Intel
consumer CPUs the CUDA wheels crash on (see _cpu_supports_avx512)."""
if sys.platform != "win32":
return None
return (
"https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34-vulkan/"
"llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
)
def _cpu_supports_avx512() -> bool:
"""True when this CPU can actually execute AVX-512 instructions.
The abetlen llama-cpp-python CUDA wheels (v0.3.34-cu124 / -cu130 — the
ones the installer picks for a modern NVIDIA GPU with a matching CUDA
runtime) are compiled WITH AVX-512 code paths. On CPUs without AVX-512
— every Intel consumer chip since Alder Lake, e.g. i7-14700F (Raptor
Lake) — model LOADING crashes with STATUS_ILLEGAL_INSTRUCTION
(0xc000001d / WinError -1073741795) inside llama.cpp's native code
because some quantize/load paths are not runtime-dispatched: the app
showed "Failed to load GGUF model … Windows Error 0xc000001d" for EVERY
local GGUF on such a machine. The CPU wheel (and the vulkan wheel) are
built WITHOUT AVX-512 and load fine, so the installer must pick them on
such CPUs — GPU offload still works via the external llama-server
backend, whose release binaries ship per-architecture CPU DLLs.
Detected via Windows' documented IsProcessorFeaturePresent(
PF_AVX512F_INSTRUCTIONS_AVAILABLE). Non-Windows / unknown OS verdicts
return True so a capable machine is never denied the CUDA wheel.
"""
if sys.platform != "win32":
return True
try:
import ctypes
return bool(ctypes.windll.kernel32.IsProcessorFeaturePresent(41))
except Exception:
# OS can't tell us — assume AVX-512 capable (the historical default).
return True
def _cpu_name() -> str:
"""The CPU's model name (e.g. 'Intel(R) Core(TM) i7-14700F') for
installer messages — read from the registry, never raising."""
try:
import winreg
with winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
) as key:
value, _ = winreg.QueryValueEx(key, "ProcessorNameString")
return str(value).strip() or "unknown CPU"
except Exception:
return "this CPU"
def is_illegal_instruction_error(exc) -> bool:
"""True when an exception (or any exception in its chain) is Windows'
STATUS_ILLEGAL_INSTRUCTION (0xc000001d / WinError -1073741795) — the
signature of a native binary executing a CPU instruction this CPU does
not support, e.g. an AVX-512 llama-cpp-python CUDA wheel on an Intel
consumer CPU (see _cpu_supports_avx512). Used to route around a broken
wheel (auto-fallback to llama-server) and to surface the REAL cause in
GGUF load errors instead of "corrupted file" guesses."""
seen = set()
while exc is not None and id(exc) not in seen:
seen.add(id(exc))
msg = f"{exc!r} {exc}".lower()
if any(tok in msg for tok in ("0xc000001d", "-1073741795",
"illegal instruction",
"status_illegal_instruction")):
return True
exc = getattr(exc, "__cause__", None) or getattr(exc, "__context__", None)
return False
class HardwareManager:
PYTORCH_AUTO = "auto"
PYTORCH_CPU = "cpu"
PYTORCH_CUDA = "cuda"
PYTORCH_XPU = "xpu"
PYTORCH_ROCM = "rocm"
LLAMA_CPP_AUTO = "auto"
LLAMA_CPP_CPU = "cpu"
LLAMA_CPP_CUDA = "cuda"
LLAMA_CPP_VULKAN = "vulkan"
@staticmethod
def _normalize_gpu_brand(name: str) -> str:
lowered = (name or "").lower()
if any(token in lowered for token in ("nvidia", "geforce", "rtx", "gtx", "quadro")):
return "nvidia"
if any(token in lowered for token in ("amd", "radeon", "rx ", "vega", "firepro")):
return "amd"
if "intel" in lowered:
return "intel"
return "unknown"
@staticmethod
def detect_video_controllers() -> list[dict]:
"""Return display adapters visible to the OS.
This intentionally does not depend on torch. Store/customer machines
often start with CPU-only torch, which means torch cannot see Intel,
AMD, or even NVIDIA hardware yet. Windows CIM is the most reliable
low-friction signal for recommending an install path.
VRAM note: Win32_VideoController.AdapterRAM is a 32-bit DWORD, so it
caps at ~4 GB and returns the 0xFFFFFFFF "unknown" sentinel when
unavailable — on any NVIDIA GPU with more VRAM than that it is
garbage (a 24 GB card reports ~4.0 GB). NVIDIA controllers therefore
get their true total VRAM from nvidia-smi (memory.total), matched by
GPU name with an index-order fallback; non-NVIDIA cards keep the CIM
value (their VRAM fits in a DWORD).
"""
controllers = []
if sys.platform == "win32":
ps = (
"Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue | "
"Select-Object Name,AdapterRAM,DriverVersion,DriverDate | ConvertTo-Json -Compress"
)
try:
result = subprocess.run(
["powershell", "-NoProfile", "-Command", ps],
capture_output=True, text=True, check=False, timeout=10,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0 and result.stdout.strip():
import json
data = json.loads(result.stdout)
if isinstance(data, dict):
data = [data]
for item in data or []:
name = str(item.get("Name") or "").strip()
if not name:
continue
controllers.append({
"name": name,
"brand": HardwareManager._normalize_gpu_brand(name),
"adapter_ram": item.get("AdapterRAM"),
"driver_version": item.get("DriverVersion") or "",
"driver_date": item.get("DriverDate") or "",
})
except Exception:
pass
# Only NVIDIA VRAM is untrustworthy (DWORD cap), so only then is
# an nvidia-smi probe worth spawning — pure Intel/AMD machines
# never pay for it.
nvidia_controllers = [c for c in controllers if c["brand"] == "nvidia"]
if nvidia_controllers:
smi_gpus = HardwareManager._nvidia_smi_gpus()
used = set()
for c in nvidia_controllers:
# Prefer a name match — CIM and nvidia-smi can order GPUs
# differently on multi-GPU machines — then fall back to
# the first unmatched GPU (index order).
target = None
for i, g in enumerate(smi_gpus):
if i not in used and HardwareManager._gpu_names_match(c["name"], g["name"]):
target = i
break
if target is None:
for i in range(len(smi_gpus)):
if i not in used:
target = i
break
if target is not None:
used.add(target)
c["adapter_ram"] = HardwareManager._vram_bytes(smi_gpus[target]["vram_mib"])
if controllers:
return controllers
# Fallbacks for machines where CIM is unavailable.
for g in HardwareManager._nvidia_smi_gpus():
controllers.append({
"name": g["name"],
"brand": "nvidia",
"adapter_ram": HardwareManager._vram_bytes(g["vram_mib"]),
"driver_version": g.get("driver_version") or "",
"driver_date": "",
})
return controllers
@staticmethod
def _nvidia_smi_gpus() -> list[dict]:
"""Name + total VRAM (MiB) + driver version of each NVIDIA GPU, from
nvidia-smi. Returns [] when nvidia-smi is unavailable — callers must
treat that as "unknown VRAM", never as zero. Win32_VideoController.
AdapterRAM cannot be trusted for VRAM: it is a 32-bit DWORD that caps
at ~4 GB (see detect_video_controllers).
"""
try:
result = subprocess.run(
["nvidia-smi", "--query-gpu=name,memory.total,driver_version",
"--format=csv,noheader,nounits"],
capture_output=True, text=True, check=False, timeout=10,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode != 0:
return []
gpus = []
for line in result.stdout.splitlines():
parts = [p.strip() for p in line.split(",")]
if not parts or not parts[0] or parts[0].lower() == "n/a":
continue
mib = 0
m = re.search(r"\d+", parts[1] if len(parts) > 1 else "")
if m:
mib = int(m.group(0))
gpus.append({
"name": parts[0],
"vram_mib": mib,
"driver_version": parts[2] if len(parts) > 2 else "",
})
return gpus
except Exception:
return []
@staticmethod
def _gpu_names_match(a: str, b: str) -> bool:
"""True if two GPU names refer to the same card — normalized substring
match (either direction). CIM and nvidia-smi usually agree exactly on
NVIDIA names but can differ in spacing/case."""
na = re.sub(r"[^a-z0-9]+", "", (a or "").lower())
nb = re.sub(r"[^a-z0-9]+", "", (b or "").lower())
return bool(na and nb and (na in nb or nb in na))
@staticmethod
def _vram_bytes(mib: int) -> int:
"""Convert nvidia-smi MiB to bytes (stored in adapter_ram so existing
consumers keep working)."""
return int(mib) * 1024 * 1024
@staticmethod
def _intel_xpu_likely_supported(gpu_name: str) -> bool:
lowered = (gpu_name or "").lower()
# Arc / Xe / Core Ultra iGPUs are the realistic Windows XPU target.
# Older UHD/HD iGPUs usually expose graphics/Vulkan but not a usable
# PyTorch XPU runtime, so recommending XPU there creates huge downloads
# followed by a failed kernel test.
return any(token in lowered for token in (" arc", "intel(r) arc", " iris xe", " xe graphics", "core ultra"))
@staticmethod
def _amd_rocm_likely_supported(gpu_name: str) -> bool:
lowered = (gpu_name or "").lower()
# Windows ROCm support is much narrower than "any Radeon". Keep this
# conservative; CPU/Vulkan remain the broad compatibility path.
return any(token in lowered for token in ("7900", "7800", "7700", "7600", "w7900", "w7800"))
@staticmethod
def _adapter_ram_gb(gpu: dict) -> Optional[float]:
"""Best-effort VRAM (GB). None/0 are unknown, and the exact
0xFFFFFFFF value is Win32_VideoController.AdapterRAM's documented
"unknown" sentinel — never rendered as a number.
The sentinel is the only DWORD value that can be reliably detected: a
>4 GB card's raw AdapterRAM wraps to an arbitrary-looking number
(e.g. 4293918720 for a 24 GB card), which this check alone cannot
distinguish from a legit ~4 GB value. Those cases are handled by the
nvidia-smi enrichment in detect_video_controllers (available on any
NVIDIA machine with a working driver); a machine without nvidia-smi
and without the exact sentinel keeps the raw DWORD — a known residual
limitation.
"""
try:
ram = gpu.get("adapter_ram")
if not ram:
return None
ram = int(ram)
# Exactly 0xFFFFFFFF is the documented "unknown" sentinel of the
# 32-bit DWORD — a raw AdapterRAM can never exceed it, while a
# real byte count (e.g. the nvidia-smi enrichment) legitimately
# can, so the comparison must be exact equality, not >=.
if ram == 0xFFFFFFFF:
return None
return ram / (1024 ** 3)
except Exception:
return None
@staticmethod
def _nvidia_generation_from_cc(cc: Optional[str]) -> str:
try:
major = int(str(cc).split(".")[0])
except Exception:
return "unknown generation"
return {
5: "Maxwell-class or older",
6: "Pascal-class",
7: "Turing/Volta-class",
8: "Ampere/Ada-class",
9: "Hopper/Ada/Blackwell-class",
}.get(major, "new NVIDIA generation" if major > 9 else "legacy NVIDIA generation")
@staticmethod
def _intel_generation_hint(name: str) -> str:
lowered = (name or "").lower()
if "arc" in lowered:
return "Intel Arc discrete GPU"
if "core ultra" in lowered:
return "Core Ultra / modern Xe iGPU"
if "iris xe" in lowered or " xe graphics" in lowered:
return "Iris Xe / Xe-class iGPU"
if "uhd" in lowered or " hd graphics" in lowered:
return "older Intel UHD/HD iGPU"
return "Intel graphics"
@staticmethod
def get_acceleration_decision_tree() -> dict:
"""Detailed hardware decision tree for the Settings tab.
The installer intentionally lays down a CPU baseline only. This
method explains what the user can optionally install afterward and
why, using hardware signals that matter for native AI packages:
GPU family/generation, NVIDIA compute capability, installed CUDA
runtime DLLs, driver hint, and VRAM.
"""
gpus = HardwareManager.detect_video_controllers()
cc = _gpu_compute_capability()
cuda_driver = HardwareManager.detect_nvidia_cuda_version()
cuda_runtime = HardwareManager.detect_installed_cuda_runtime_major()
lines = ["Install baseline: CPU PyTorch first. Optional accelerators can be installed from Settings."]
adapter_details = []
for idx, gpu in enumerate(gpus):
name = gpu.get("name", "Unknown GPU")
brand = gpu.get("brand", "unknown")
ram_gb = HardwareManager._adapter_ram_gb(gpu)
ram_text = f"{ram_gb:.1f} GB" if ram_gb is not None else "unknown VRAM"
detail = f"{idx}: {name} | brand={brand} | VRAM={ram_text} | driver={gpu.get('driver_version') or 'unknown'}"
if brand == "nvidia":
detail += f" | compute capability={cc or 'unknown'} | {HardwareManager._nvidia_generation_from_cc(cc)}"
elif brand == "intel":
detail += f" | {HardwareManager._intel_generation_hint(name)}"
adapter_details.append(detail)
if adapter_details:
lines.extend(["", "Detected adapters:"] + [f"- {d}" for d in adapter_details])
else:
lines.extend(["", "Detected adapters:", "- none reported by the OS"])
pytorch_choice = HardwareManager.PYTORCH_CPU
pytorch_reason = "CPU PyTorch is the safe default and works on the widest range of PCs."
llama_choice = HardwareManager.LLAMA_CPP_CPU
llama_reason = "CPU llama.cpp is the safest GGUF baseline."
brands = {g.get("brand") for g in gpus}
if "nvidia" in brands:
try:
cc_f = float(cc) if cc else 0.0
except (TypeError, ValueError):
cc_f = 0.0
lines.append("")
lines.append("NVIDIA decision:")
lines.append(f"- Driver CUDA hint: {cuda_driver or 'not reported'}")
lines.append(f"- Installed CUDA runtime DLL family: cublas64_{cuda_runtime}.dll" if cuda_runtime else "- Installed CUDA runtime DLL family: not found")
lines.append(f"- Compute capability: {cc or 'unknown'} ({HardwareManager._nvidia_generation_from_cc(cc)})")
if cc_f >= 7.0:
pytorch_choice = HardwareManager.PYTORCH_CUDA
pytorch_reason = "NVIDIA compute capability is new enough for current CUDA PyTorch; install CUDA PyTorch only if you want GPU speed."
if cuda_runtime in (12, 13):
llama_choice = HardwareManager.LLAMA_CPP_CUDA
llama_reason = f"CUDA runtime {cuda_runtime} DLLs are installed, so a matching llama-cpp-python CUDA wheel can load."
else:
llama_reason = "GPU is modern, but CUDA runtime DLLs were not found; use CPU llama.cpp or install CUDA runtime before CUDA llama.cpp."
elif cc_f:
pytorch_reason = f"NVIDIA compute capability {cc} is too old for current CUDA AI wheels; CPU is recommended."
llama_reason = f"NVIDIA compute capability {cc} is too old for current llama.cpp CUDA kernels; CPU is recommended."
if "intel" in brands or "amd" in brands:
llama_choice = HardwareManager.LLAMA_CPP_VULKAN
llama_reason += " Vulkan can be tried for Intel/AMD graphics, but keep CPU as fallback."
else:
pytorch_reason = "NVIDIA GPU was detected but compute capability could not be verified; CPU is the safe default."
llama_reason = "Do not install CUDA llama.cpp blindly without compute capability and runtime verification."
elif "amd" in brands:
amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd")
if HardwareManager._amd_rocm_likely_supported(amd_names):
pytorch_choice = HardwareManager.PYTORCH_ROCM
pytorch_reason = "Recent AMD GPU detected; Windows ROCm can be tried from Settings, but it is a large optional install."
else:
pytorch_reason = "AMD GPU detected, but Windows ROCm support is narrow; CPU PyTorch is safer."
llama_choice = HardwareManager.LLAMA_CPP_VULKAN
llama_reason = "AMD graphics can try the Vulkan llama.cpp wheel; CPU remains the compatibility fallback."
elif "intel" in brands:
intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel")
if HardwareManager._intel_xpu_likely_supported(intel_names):
pytorch_choice = HardwareManager.PYTORCH_XPU
pytorch_reason = "Modern Intel Arc/Xe-class GPU detected; PyTorch XPU can be tried from Settings."
llama_choice = HardwareManager.LLAMA_CPP_VULKAN
llama_reason = "Intel graphics can try Vulkan llama.cpp; CPU remains the fallback."
else:
pytorch_reason = "Older Intel UHD/HD graphics detected; PyTorch XPU is not recommended. Use CPU."
llama_reason = "Older Intel UHD/HD graphics may expose Vulkan, but acceleration is often limited; CPU is recommended."
lines.extend([
"",
f"Recommended PyTorch path: {pytorch_choice.upper()} - {pytorch_reason}",
f"Recommended GGUF/llama.cpp path: {llama_choice.upper()} - {llama_reason}",
"",
"Rule: install GPU packages only from Settings after the app launches, and only after a real kernel/load test passes.",
])
return {
"gpus": gpus,
"nvidia_compute_capability": cc,
"nvidia_generation": HardwareManager._nvidia_generation_from_cc(cc),
"cuda_driver": cuda_driver,
"cuda_runtime_major": cuda_runtime,
"pytorch": {"choice": pytorch_choice, "reason": pytorch_reason},
"llama_cpp": {"choice": llama_choice, "reason": llama_reason},
"report": "\n".join(lines),
}
@staticmethod
def _format_gpu_list(gpus: list[dict]) -> str:
if not gpus:
return "No discrete/integrated GPU reported by the OS."
rows = []
for idx, gpu in enumerate(gpus):
ram_gb = HardwareManager._adapter_ram_gb(gpu)
ram_text = f"{ram_gb:.1f} GB" if ram_gb is not None else "unknown VRAM"
rows.append(
f"{idx}: {gpu.get('name', 'Unknown GPU')} "
f"({gpu.get('brand', 'unknown')}, {ram_text}, driver {gpu.get('driver_version') or 'unknown'})"
)
return "\n".join(rows)
@staticmethod
def get_backend_recommendations() -> dict:
"""Recommend install choices for PyTorch and llama.cpp separately."""
tree = HardwareManager.get_acceleration_decision_tree()
return {
"gpus": tree["gpus"],
"pytorch": tree["pytorch"],
"llama_cpp": tree["llama_cpp"],
}
@staticmethod
def get_pytorch_install_options() -> list[str]:
return [
"Auto recommended",
"CPU PyTorch (works on every PC)",
"NVIDIA CUDA PyTorch",
"Intel XPU PyTorch",
"AMD ROCm PyTorch",
]
@staticmethod
def parse_pytorch_install_choice(label: str) -> str:
text = (label or "").lower()
if "nvidia" in text or "cuda" in text:
return HardwareManager.PYTORCH_CUDA
if "intel" in text or "xpu" in text:
return HardwareManager.PYTORCH_XPU
if "amd" in text or "rocm" in text:
return HardwareManager.PYTORCH_ROCM
if "cpu" in text:
return HardwareManager.PYTORCH_CPU
return HardwareManager.PYTORCH_AUTO
@staticmethod
def get_llama_cpp_install_options() -> list[str]:
return [
"Auto recommended",
"CPU llama.cpp",
"NVIDIA CUDA llama.cpp",
"Vulkan llama.cpp (Intel/AMD)",
]
@staticmethod
def parse_llama_cpp_install_choice(label: str) -> str:
text = (label or "").lower()
if "nvidia" in text or "cuda" in text:
return HardwareManager.LLAMA_CPP_CUDA
if "vulkan" in text or "intel" in text or "amd" in text:
return HardwareManager.LLAMA_CPP_VULKAN
if "cpu" in text:
return HardwareManager.LLAMA_CPP_CPU
return HardwareManager.LLAMA_CPP_AUTO
@staticmethod
def format_backend_recommendations() -> str:
return HardwareManager.get_acceleration_decision_tree()["report"]
@staticmethod
def detect_vram_gb() -> Optional[float]:
"""Best-effort total VRAM (in GB) of the primary CUDA GPU, if any.
Returns None if there's no CUDA GPU, or detection fails for any
reason — callers should treat None as "unknown", not "zero", since
a failed *detection* is not the same as genuinely having no GPU.
"""
try:
if torch.cuda.is_available():
props = torch.cuda.get_device_properties(0)
return props.total_memory / (1024 ** 3)
if hasattr(torch, "xpu") and torch.xpu.is_available():
props = torch.xpu.get_device_properties(0)
return props.total_memory / (1024 ** 3)
except Exception:
pass
return None
@staticmethod
def detect_system_ram_gb() -> Optional[float]:
"""Best-effort total system RAM (in GB).
Prefers `psutil` (not a hard requirement of this app — see
requirements.txt) since it's cross-platform; falls back to
reading /proc/meminfo directly on Linux if psutil isn't
installed. Returns None if neither approach works (e.g. Windows
without psutil) — callers should treat this the same as an
unknown GPU: fall back to a conservative default tier rather than
guessing a number that could be wildly wrong.
"""
try:
import psutil
return psutil.virtual_memory().total / (1024 ** 3)
except Exception:
pass
try:
with open("/proc/meminfo") as f:
for line in f:
if line.startswith("MemTotal:"):
kb = int(line.split()[1])
return kb / (1024 ** 2)
except Exception:
pass
return None
@staticmethod
def get_memory_usage() -> dict:
"""Current live CPU + RAM + VRAM usage — the numbers shown next to
the "Free All VRAM" buttons (Settings tab + sidebar) so users can see
how much of their machine is in use (and how much freeing VRAM
actually recovered). Never raises: every probe is individually
guarded and degrades to None ("unknown") instead of crashing the
Settings tab.
Returns {
"cpu": {"pct": float|None},
"ram": {"used_gb": float|None, "total_gb": float|None, "pct": float|None},
"vram": {"used_gb": float|None, "total_gb": float|None, "pct": float|None},
}
- CPU comes from psutil.cpu_percent() (system-wide, the same
percentage Task Manager shows).
- RAM comes from psutil.virtual_memory() (used = total - available,
pct = the same percentage Task Manager shows).
- VRAM prefers nvidia-smi `memory.used`/`memory.total` (works even
when torch is a CPU-only build), falling back to torch CUDA
stats, and stays all-None on machines with no usable GPU.
"""
usage = {
"cpu": {"pct": None},
"ram": {"used_gb": None, "total_gb": None, "pct": None},
"vram": {"used_gb": None, "total_gb": None, "pct": None},
}
try:
import psutil
# A short real sampling interval (not None): cpu_percent(interval=None)
# returns 0.0 on the FIRST call because it has no baseline to compare
# against — the sidebar would show a bogus 0% on first render. A
# 100ms sample returns a real number every time, negligible against
# the 5s UI poll cadence.
usage["cpu"]["pct"] = round(psutil.cpu_percent(interval=0.1), 1)
except Exception:
pass
try:
import psutil
vm = psutil.virtual_memory()
usage["ram"]["used_gb"] = round((vm.total - vm.available) / (1024 ** 3), 1)
usage["ram"]["total_gb"] = round(vm.total / (1024 ** 3), 1)
usage["ram"]["pct"] = round(vm.percent, 1)
except Exception:
pass
# VRAM — nvidia-smi first (real used/total regardless of which torch
# build is installed), then torch CUDA as the fallback.
try:
result = subprocess.run(
["nvidia-smi", "--query-gpu=memory.used,memory.total",
"--format=csv,noheader,nounits"],
capture_output=True, text=True, check=False, timeout=10,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0 and result.stdout.strip():
used, total = None, None
for line in result.stdout.splitlines():
parts = [p.strip() for p in line.split(",")]
m_used = re.search(r"\d+", parts[0]) if parts else None
m_total = re.search(r"\d+", parts[1]) if len(parts) > 1 else None
if m_used and m_total:
used = float(m_used.group(0)) / 1024.0 # MiB -> GiB
total = float(m_total.group(0)) / 1024.0
break
if used is not None and total is not None:
usage["vram"]["used_gb"] = round(used, 1)
usage["vram"]["total_gb"] = round(total, 1)
usage["vram"]["pct"] = round(used / total * 100, 1) if total else None
except Exception:
pass
if usage["vram"]["total_gb"] is None:
try:
if torch.cuda.is_available():
props = torch.cuda.get_device_properties(0)
total = props.total_memory / (1024 ** 3)
used = torch.cuda.memory_allocated(0) / (1024 ** 3)
usage["vram"]["used_gb"] = round(used, 1)
usage["vram"]["total_gb"] = round(total, 1)
usage["vram"]["pct"] = round(used / total * 100, 1) if total else None
elif hasattr(torch, "xpu") and torch.xpu.is_available():
props = torch.xpu.get_device_properties(0)
total = props.total_memory / (1024 ** 3)
used = torch.xpu.memory_allocated(0) / (1024 ** 3)
usage["vram"]["used_gb"] = round(used, 1)
usage["vram"]["total_gb"] = round(total, 1)
usage["vram"]["pct"] = round(used / total * 100, 1) if total else None
except Exception:
pass
return usage
# ──────────────────────────────────────────────────────────────
# Hardware tiers — mirrors the "Model combos by hardware tier" table
# in README.md exactly, so the HF-side dynamic model registry (see
# model_registry.get_recommended_hf_models()) recommends the same
# models the README documents for each tier. Checked from the
# top (most capable) down, so a machine that qualifies for a higher
# tier is never mistakenly placed in a lower one.
# ──────────────────────────────────────────────────────────────
TIER_48GB_VRAM = "48gb_vram"
TIER_24GB_VRAM = "24gb_vram"
TIER_16GB_VRAM = "16gb_vram"
TIER_8GB_VRAM = "8gb_vram"
TIER_CPU_ONLY = "cpu_only"
TIER_UNKNOWN = "unknown"
@staticmethod
def detect_hardware_tier() -> str:
"""Classify the current machine into one of the README's hardware
tiers, based on detected VRAM (if a CUDA GPU is present) or system
RAM (CPU-only case). Returns TIER_UNKNOWN if neither VRAM nor RAM
could be determined — callers should fall back to the app's
existing small defaults (BASE_MODEL_OPTIONS) in that case rather
than guessing a tier that might recommend a model too large for
the actual machine.
"""
vram_gb = HardwareManager.detect_vram_gb()
if vram_gb is not None:
if vram_gb >= 44: # 48 GB tier — a little headroom below the nominal 48
return HardwareManager.TIER_48GB_VRAM
if vram_gb >= 20: # 24 GB tier
return HardwareManager.TIER_24GB_VRAM
if vram_gb >= 14: # 16 GB tier
return HardwareManager.TIER_16GB_VRAM
if vram_gb >= 6: # 8 GB tier — some headroom below nominal 8
return HardwareManager.TIER_8GB_VRAM
# A CUDA GPU exists but has less VRAM than any tier above
# assumes — safer to fall back to CPU-only-style (smaller)
# recommendations than to recommend an 8GB-tier model that
# won't fit.
return HardwareManager.TIER_CPU_ONLY
ram_gb = HardwareManager.detect_system_ram_gb()
if ram_gb is not None and ram_gb >= 56: # 64GB tier — some headroom below nominal 64
return HardwareManager.TIER_CPU_ONLY
return HardwareManager.TIER_UNKNOWN
@staticmethod
def detect_nvidia_cuda_version() -> Optional[str]:
"""Best-effort read of the driver's supported CUDA version from
nvidia-smi.
Newer NVIDIA drivers (r580+ — e.g. the 610.x header line) stopped
printing the legacy "CUDA Version: X.Y" text and now print
"CUDA UMD Version: X.Y" instead. Parse BOTH spellings so driver
detection doesn't silently fail — and the "Fix Environment" tool
doesn't fall through to a CPU recommendation — on current drivers.
"""
try:
result = subprocess.run(
["nvidia-smi"], capture_output=True, text=True, check=False,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0:
for line in result.stdout.splitlines():
for marker in ("CUDA UMD Version:", "CUDA Version:"):
if marker in line:
val = line.split(marker)[1].strip().rstrip("|").strip()
if val and val.lower() != "n/a":
return val
return None
except Exception:
return None
@staticmethod
def detect_installed_cuda_runtime_major() -> Optional[int]:
"""Best-effort read of the installed CUDA runtime DLL major version.
We look for cublas64_*.dll on PATH plus common CUDA install
locations. This is the version that matters for native wheels such
as llama-cpp-python; the NVIDIA driver's reported CUDA version is
only a compatibility hint and can disagree with the DLLs actually
present on disk.
"""
dirs = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d.strip()]
cu_path = os.environ.get("CUDA_PATH", "")
if cu_path:
dirs.append(os.path.join(cu_path, "bin"))
for base in (
"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA",
"C:/Program Files/NVIDIA Corporation/CUDNN",
):
base_p = Path(base)
if not base_p.is_dir():
continue
for child in base_p.iterdir():
if child.is_dir():
dirs.append(str(child / "bin") if (child / "bin").is_dir() else str(child))
seen = set()
majors = []
for d in dirs:
try:
names = os.listdir(d)
except Exception:
continue
for f in names:
m = re.match(r"cublas64_(\d+)\.dll$", f, re.IGNORECASE)
if not m or f in seen:
continue
seen.add(f)
try:
majors.append(int(m.group(1)))
except ValueError:
pass
return max(majors) if majors else None
@staticmethod
def get_required_torch_index(cuda_version: str) -> str:
"""Return the PyTorch wheel index best matching an NVIDIA driver's
reported CUDA version. Mirrors the SETUP.ps1 STEP 4 mapping: a wheel
is only offered if its bundled CUDA runtime is <= the driver's
supported CUDA version (a driver reporting 12.6 cannot run cu128
wheels; a 12.0 driver cannot run cu121+). For drivers newer than
any known tier the newest known tier is used, since a new driver
does not imply a new GPU — SETUP.ps1 re-verifies compatibility with
a real-kernel smoke test after install.
Also accepts the SETUP.ps1 brand tokens for non-NVIDIA backends
("rocm7.2.1" and "xpu"), mapping them to the correct index so the
Fix Environment helper never suggests a bogus CUDA tier on an
AMD/Intel machine.
"""
if not cuda_version:
return "https://download.pytorch.org/whl/cpu"
if cuda_version == "xpu":
return "https://download.pytorch.org/whl/xpu"
if cuda_version.startswith("rocm"):
return "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
try:
v_parts = cuda_version.split('.')
major = int(v_parts[0])
minor = int(v_parts[1])
if major == 11:
return "https://download.pytorch.org/whl/cu118"
elif major == 12:
if minor == 0:
return "https://download.pytorch.org/whl/cu118"
elif minor in (1, 2, 3):
return "https://download.pytorch.org/whl/cu121"
elif minor in (4, 5):
return "https://download.pytorch.org/whl/cu124"
elif minor in (6, 7):
return "https://download.pytorch.org/whl/cu126"
elif minor in (8, 9):
return "https://download.pytorch.org/whl/cu128"
else:
return "https://download.pytorch.org/whl/cu128"
elif major >= 13:
# Driver newer than any known tier -> newest known-good tier
# (a new driver does not imply a new GPU; SETUP.ps1's
# real-kernel smoke test re-verifies compatibility).
return "https://download.pytorch.org/whl/cu128"
# major < 11 (pre-Pascal-era driver): no current wheel fits,
# but mirror SETUP.ps1 and offer the oldest tier — the smoke
# test decides whether it actually runs.
return "https://download.pytorch.org/whl/cu118"
except Exception:
return "https://download.pytorch.org/whl/cpu"
@staticmethod
def get_system_status() -> dict:
decision = HardwareManager.get_acceleration_decision_tree()
recommendations = {
"gpus": decision["gpus"],
"pytorch": decision["pytorch"],
"llama_cpp": decision["llama_cpp"],
}
status = {
"gpu_brand": "none",
"gpus": recommendations["gpus"],
"recommendations": recommendations,
"acceleration_report": decision["report"],
"cuda_version": None,
"torch_cuda_available": False,
"current_device": "cpu",
"recommended_index": "https://download.pytorch.org/whl/cpu"
}
cuda_ver = HardwareManager.detect_nvidia_cuda_version()
if cuda_ver:
status["gpu_brand"] = "nvidia"
status["cuda_version"] = cuda_ver
status["recommended_index"] = HardwareManager.get_required_torch_index(cuda_ver)
try:
status["torch_cuda_available"] = torch.cuda.is_available()
if status["torch_cuda_available"]:
status["current_device"] = "cuda"
elif hasattr(torch, "xpu") and torch.xpu.is_available():
status["current_device"] = "xpu"
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
status["current_device"] = "mps"
else:
status["current_device"] = "cpu"
except Exception:
pass
if status["gpu_brand"] == "none":
brands = {g["brand"] for g in recommendations["gpus"]}
if "nvidia" in brands:
status["gpu_brand"] = "nvidia"
status["cuda_version"] = "unknown"
status["recommended_index"] = "https://download.pytorch.org/whl/cu128"
elif "amd" in brands:
status["gpu_brand"] = "amd"
status["cuda_version"] = "rocm7.2.1"
status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
elif "intel" in brands:
status["gpu_brand"] = "intel"
status["cuda_version"] = "xpu"
status["recommended_index"] = "https://download.pytorch.org/whl/xpu"
choice = recommendations["pytorch"]["choice"]
if choice == HardwareManager.PYTORCH_CPU:
status["recommended_index"] = "https://download.pytorch.org/whl/cpu"
elif choice == HardwareManager.PYTORCH_XPU:
status["recommended_index"] = "https://download.pytorch.org/whl/xpu"
elif choice == HardwareManager.PYTORCH_ROCM:
status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
elif choice == HardwareManager.PYTORCH_CUDA and not status["recommended_index"].endswith("/cpu"):
pass
if False and status["gpu_brand"] == "none":
# nvidia-smi was unavailable (or unparseable). Fall back to the
# Windows device list so an NVIDIA machine is never mislabeled
# "no GPU". Use PowerShell CIM first (works on all modern
# Windows; wmic is deprecated/removed in newer releases), then
# wmic as a fallback.
vc_names = ""
try:
result = subprocess.run(
["powershell", "-NoProfile", "-Command",
"(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue).Name -join ';'"],
capture_output=True, text=True, check=False,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0:
vc_names = result.stdout
except Exception:
pass
if not vc_names:
try:
result = subprocess.run(
["wmic", "path", "win32_VideoController", "get", "name"],
capture_output=True, text=True, check=False,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0:
vc_names = result.stdout
except Exception:
pass
if "NVIDIA" in vc_names or "GeForce" in vc_names or "RTX" in vc_names or "Quadro" in vc_names:
# NVIDIA card present but nvidia-smi didn't cooperate — treat
# it as a modern driver and point at the proven RTX-tier
# index (SETUP.ps1 uses the same fallback; the app's own
# real-kernel check verifies the result at runtime).
status["gpu_brand"] = "nvidia"
status["cuda_version"] = "unknown"
status["recommended_index"] = "https://download.pytorch.org/whl/cu128"
elif "Radeon" in vc_names or "AMD" in vc_names:
status["gpu_brand"] = "amd"
status["cuda_version"] = "rocm7.2.1"
status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
elif "Intel" in vc_names:
status["gpu_brand"] = "intel"
status["cuda_version"] = "xpu"
status["recommended_index"] = "https://download.pytorch.org/whl/xpu"
return status
@staticmethod
def fix_environment_gen(choice=None):
"""Detect hardware and install a matching PyTorch build.
choice ("auto" / "cpu" / "cuda" / "xpu" / "rocm", or None = auto):
the explicit build the user picked in the Settings popup. Auto still
decides by hardware; a non-viable explicit pick degrades to CPU with
a clear message (never a mismatched GPU install — mirrors
install_llama_cpp_python_gen)."""
status = HardwareManager.get_system_status()
if status["torch_cuda_available"]:
yield "✅ Environment is already correctly configured for GPU!", "cuda", ""
return
if hasattr(torch, "xpu") and torch.xpu.is_available():
yield "✅ Environment is already correctly configured for GPU!", "xpu", ""
return
choice = (choice or "auto").lower()
if choice not in ("auto", "cpu", "cuda", "xpu", "rocm"):
yield (f"❌ Unknown PyTorch build '{choice}' "
"(expected auto / cpu / cuda / xpu / rocm)."), "cpu", f"❌ Unknown PyTorch build '{choice}'."
return
brand = status["gpu_brand"]
cc = _gpu_compute_capability()
try:
cc_f = float(cc) if cc else 0.0
except (TypeError, ValueError):
cc_f = 0.0
gpus = status.get("gpus") or []
intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel")
amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd")
# Resolve the build that will actually be installed. Every explicit
# pick is guarded by the same machine signals the plan popup uses —
# a non-viable pick degrades to CPU with a clear message, never a
# mismatched GPU wheel (mirrors install_llama_cpp_python_gen).
if choice == "cpu":
effective = HardwareManager.PYTORCH_CPU
elif choice == "cuda":
if brand == "nvidia" and cc_f >= 7.0:
effective = HardwareManager.PYTORCH_CUDA
else:
yield ("⚠️ The NVIDIA CUDA PyTorch build is not usable on this machine "
"(requires a modern NVIDIA GPU). Falling back to the CPU build."), "cpu", \
"⚠️ The NVIDIA CUDA PyTorch build is not usable on this machine. Falling back to the CPU build."
effective = HardwareManager.PYTORCH_CPU
elif choice == "xpu":
if brand == "intel" and HardwareManager._intel_xpu_likely_supported(intel_names):
effective = HardwareManager.PYTORCH_XPU
else:
yield ("⚠️ The Intel XPU PyTorch build is not usable on this machine "
"(requires a modern Intel Arc / Xe-class GPU). Falling back to the CPU build."), "cpu", \
"⚠️ The Intel XPU PyTorch build is not usable on this machine. Falling back to the CPU build."
effective = HardwareManager.PYTORCH_CPU
elif choice == "rocm":
if brand == "amd" and HardwareManager._amd_rocm_likely_supported(amd_names):
effective = HardwareManager.PYTORCH_ROCM
else:
yield ("⚠️ The AMD ROCm PyTorch build is not usable on this machine "
"(Windows ROCm needs a recent Radeon RX 7000-class GPU). Falling back to the CPU build."), "cpu", \
"⚠️ The AMD ROCm PyTorch build is not usable on this machine. Falling back to the CPU build."
effective = HardwareManager.PYTORCH_CPU
else: # auto — the historical hardware-driven decision tree
effective = status.get("recommendations", {}).get("pytorch", {}).get(
"choice", HardwareManager.PYTORCH_CPU)
if effective == HardwareManager.PYTORCH_CPU:
report = status.get("acceleration_report") or HardwareManager.format_backend_recommendations()
if choice == "cpu":
# An explicit CPU pick needs no full report — just confirm the
# user's choice (the report would mask this line in the log).
yield "CPU PyTorch selected by the user.", "cpu", "CPU PyTorch selected by the user."
else:
yield "CPU PyTorch is recommended for this machine.", "cpu", report
yield "No GPU PyTorch package was installed. The current CPU baseline is the safest option.", "cpu", ""
return
# Resolve the wheel index for the effective build (never the auto
# recommendation's index — an explicit pick must map to its own tier).
if effective == HardwareManager.PYTORCH_CUDA:
index = HardwareManager.get_required_torch_index(status.get("cuda_version") or "")
if index.endswith("/cpu"):
# NVIDIA GPU present but driver CUDA version unknown — the same
# proven RTX-tier index get_system_status falls back to.
index = "https://download.pytorch.org/whl/cu128"
elif effective == HardwareManager.PYTORCH_XPU:
index = "https://download.pytorch.org/whl/xpu"
else: # PYTORCH_ROCM
index = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
yield "🚀 Starting environment fix...", "cuda", "🚀 Starting environment fix..."
yield f"🔍 Detected GPU: {brand.upper()}", "cuda", f"🔍 Detected GPU: {brand.upper()}"
yield f"🔗 Using PyTorch index: {index}", "cuda", f"🔗 Using PyTorch index: {index}"
try:
if effective == HardwareManager.PYTORCH_ROCM:
# AMD ROCm: SDK wheels must be installed before the torch
# wheels, and everything comes from repo.radeon.com (the
# CUDA-tier install below would resolve nothing there).
roc_base = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
sdk_wheels = [
f"{roc_base}/rocm_sdk_core-7.2.1-py3-none-win_amd64.whl",
f"{roc_base}/rocm_sdk_devel-7.2.1-py3-none-win_amd64.whl",
f"{roc_base}/rocm_sdk_libraries_custom-7.2.1-py3-none-win_amd64.whl",
f"{roc_base}/rocm-7.2.1.tar.gz",
]
torch_wheels = [
f"{roc_base}/torch-2.9.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl",
f"{roc_base}/torchaudio-2.9.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl",
f"{roc_base}/torchvision-0.24.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl",
]
yield "Running: pip install ROCm SDK wheels", "cuda", "Running: pip install ROCm SDK wheels"
sdk_cmd = _pip_base_args() + ["--no-cache-dir"] + sdk_wheels
process = subprocess.Popen(
sdk_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
creationflags=CREATE_NO_WINDOW,
)
for line in process.stdout:
yield "🛠️ Installing...", "cuda", line.strip()
process.wait()
if process.returncode != 0:
yield f"❌ ROCm SDK install failed with exit code {process.returncode}", "cpu", f"❌ ROCm SDK install failed with exit code {process.returncode}"
return
cmd = _pip_base_args() + ["--no-cache-dir"] + torch_wheels
elif effective == HardwareManager.PYTORCH_XPU:
# Intel XPU: pin exact versions (index outage bug #185608
# can silently downgrade to an old torch otherwise).
cmd = _pip_base_args() + [
"torch==2.11.0", "torchvision==0.26.0", "torchaudio==2.11.0",
"--index-url", index]
else:
cmd = _pip_base_args() + ["torch<2.12", "torchvision", "torchaudio", "--index-url", index]
yield f"Running: {' '.join(cmd)}", "cuda", f"Running: {' '.join(cmd)}"
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
creationflags=CREATE_NO_WINDOW,
)
for line in process.stdout:
yield "🛠️ Installing...", "cuda", line.strip()
process.wait()
if process.returncode == 0:
yield "✨ Installation successful!", "cuda", "✨ Installation successful!"
yield "✅ Environment fixed! Please RESTART the app to apply changes.", "cuda", "✅ Environment fixed! Please RESTART the app to apply changes."
else:
yield f"❌ Installation failed with exit code {process.returncode}", "cpu", f"❌ Installation failed with exit code {process.returncode}"
yield "❌ Installation failed. Check the logs above.", "cpu", "❌ Installation failed. Check the logs above."
except Exception as e:
yield f"❌ Error: {str(e)}", "cpu", f"❌ Error: {str(e)}"
@staticmethod
def get_pytorch_install_plan() -> dict:
"""Detect which PyTorch builds are AVAILABLE on this machine and
report each with a bilingual reason — the Settings popup shows the
user every viable option and lets THEM choose, instead of silently
installing the recommended path.
Returns {
"detected": {gpu_brand, gpu_name, cpu_name, cuda_version,
compute_capability, current_device},
"options": [ {"id", "label_key", "reason_key", "params",
"available", "recommended"}, ... ],
}
The option `id` is one of: auto / cpu / cuda / xpu / rocm. `auto` is
always available and `recommended` mirrors the acceleration decision
tree (the historical auto path).
"""
status = HardwareManager.get_system_status()
brand = status["gpu_brand"]
gpus = status.get("gpus") or []
cc = _gpu_compute_capability()
try:
cc_f = float(cc) if cc else 0.0
except (TypeError, ValueError):
cc_f = 0.0
intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel")
amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd")
# Viability — the same machine signals the decision tree uses. CUDA
# wheels bundle their own runtime DLLs, so the ONLY hard requirement
# is a modern NVIDIA GPU (no installed-runtime / AVX-512 gate like
# llama-cpp-python's CUDA wheels).
cuda_available = brand == "nvidia" and cc_f >= 7.0
xpu_available = brand == "intel" and HardwareManager._intel_xpu_likely_supported(intel_names)
rocm_available = brand == "amd" and HardwareManager._amd_rocm_likely_supported(amd_names)
if cuda_available:
recommended = "cuda"
elif rocm_available:
recommended = "rocm"
elif xpu_available:
recommended = "xpu"
else:
recommended = "cpu"
# CUDA reason — granular per obstacle (mirrors the llama-cpp plan).
if cuda_available:
cuda_key, cuda_params = "ptch_reason_cuda_ok", {}
elif brand != "nvidia":
cuda_key, cuda_params = "ptch_reason_cuda_requires_nvidia", {}
elif not cc_f:
cuda_key, cuda_params = "ptch_reason_cuda_cc_unknown", {}
else: # NVIDIA but too old for current CUDA wheels
cuda_key, cuda_params = "ptch_reason_cuda_old_gpu", {"cc": cc}
# XPU reason.
if xpu_available:
xpu_key, xpu_params = "ptch_reason_xpu_ok", {}
elif brand != "intel":
xpu_key, xpu_params = "ptch_reason_xpu_requires_intel", {}
else: # Intel but old UHD/HD-class iGPU
xpu_key, xpu_params = "ptch_reason_xpu_old_gpu", {}
# ROCm reason.
if rocm_available:
rocm_key, rocm_params = "ptch_reason_rocm_ok", {}
elif brand != "amd":
rocm_key, rocm_params = "ptch_reason_rocm_requires_amd", {}
else: # AMD but not RX 7000-class
rocm_key, rocm_params = "ptch_reason_rocm_old_gpu", {}
options = [
{
"id": "auto",
"label_key": "ptch_opt_auto",
"reason_key": "ptch_reason_auto",
"params": {},
"available": True,
"recommended": False,
},
{
"id": "cpu",
"label_key": "ptch_opt_cpu",
"reason_key": "ptch_reason_cpu_always",
"params": {},
"available": True,
"recommended": recommended == "cpu",
},
{
"id": "cuda",
"label_key": "ptch_opt_cuda",
"reason_key": cuda_key,
"params": cuda_params,
"available": cuda_available,
"recommended": recommended == "cuda",
},
{
"id": "xpu",
"label_key": "ptch_opt_xpu",
"reason_key": xpu_key,
"params": xpu_params,
"available": xpu_available,
"recommended": recommended == "xpu",
},
{
"id": "rocm",
"label_key": "ptch_opt_rocm",
"reason_key": rocm_key,
"params": rocm_params,
"available": rocm_available,
"recommended": recommended == "rocm",
},
]
detected = {
"gpu_brand": brand,
"gpu_name": _gpu_name(),
"cpu_name": _cpu_name(),
"cuda_version": status.get("cuda_version"),
"compute_capability": cc,
"current_device": status.get("current_device", "cpu"),
}
return {"detected": detected, "options": options}
@staticmethod
def get_llama_cpp_install_plan() -> dict:
"""Detect which llama-cpp-python builds are AVAILABLE on this machine
and report each with a bilingual reason — the Settings popup shows the
user every viable option and lets THEM choose, instead of silently
installing the CPU wheel.
Returns {
"detected": {gpu_brand, gpu_name, cpu_name, cuda_version,
runtime_major, compute_capability, avx512},
"options": [ {"id", "label_key", "reason_key", "params",
"available", "recommended"}, ... ],
}
The option `id` is one of: auto / cpu / cuda / vulkan. `reason_key`
is an i18n key resolved with `params` (e.g. "{cc}" / "{runtime}"). An
option is `available` when it can actually run on this machine and
`recommended` when it is the best pick. `auto` is always available.
"""
status = HardwareManager.get_system_status()
brand = status["gpu_brand"]
cuda_version = status["cuda_version"]
runtime_major = HardwareManager.detect_installed_cuda_runtime_major()
cc = _gpu_compute_capability()
try:
cc_f = float(cc) if cc else 0.0
except (TypeError, ValueError):
cc_f = 0.0
avx512 = _cpu_supports_avx512()
gpu_name = _gpu_name()
cpu_name = _cpu_name()
detected = {
"gpu_brand": brand,
"gpu_name": gpu_name,
"cpu_name": cpu_name,
"cuda_version": cuda_version,
"runtime_major": runtime_major,
"compute_capability": cc,
"avx512": avx512,
}
options = [
{
"id": "auto",
"label_key": "llcpp_opt_auto",
"reason_key": "llcpp_reason_auto",
"params": {},
"available": True,
"recommended": False,
},
{
"id": "cpu",
"label_key": "llcpp_opt_cpu",
"reason_key": "llcpp_reason_cpu_always",
"params": {},
"available": True,
"recommended": False,
},
]
# CUDA — viable ONLY when every hardware condition holds (same signals
# the installer guards on: NVIDIA brand, modern compute capability, a
# CUDA runtime DLL family actually installed, AVX-512-capable CPU).
cuda_available = (
brand == "nvidia"
and cc_f >= 7.0
and runtime_major in (12, 13)
and avx512
)
if cuda_available:
cuda_key, cuda_params = "llcpp_reason_cuda_ok", {"runtime": runtime_major}
cuda_recommended = True
elif brand != "nvidia":
cuda_key, cuda_params = "llcpp_reason_cuda_requires_nvidia", {}
cuda_recommended = False
elif not cc_f:
cuda_key, cuda_params = "llcpp_reason_cuda_cc_unknown", {}
cuda_recommended = False
elif cc_f < 7.0:
cuda_key, cuda_params = "llcpp_reason_cuda_old_gpu", {"cc": cc}
cuda_recommended = False
elif runtime_major not in (12, 13):
cuda_key, cuda_params = "llcpp_reason_cuda_no_runtime", {}
cuda_recommended = False
else: # modern GPU + runtime but no AVX-512 → CUDA wheels crash
cuda_key, cuda_params = "llcpp_reason_cuda_no_avx512", {"cpu": cpu_name}
cuda_recommended = False
options.append({
"id": "cuda",
"label_key": "llcpp_opt_cuda",
"reason_key": cuda_key,
"params": cuda_params,
"available": cuda_available,
"recommended": cuda_recommended,
})
# Vulkan — viable for AMD/Intel GPUs (built without AVX-512, so it
# also loads on the consumer CPUs where the CUDA wheels crash).
vulkan_available = brand in ("amd", "intel")
options.append({
"id": "vulkan",
"label_key": "llcpp_opt_vulkan",
"reason_key": "llcpp_reason_vulkan_ok" if vulkan_available else "llcpp_reason_vulkan_no_gpu",
"params": {},
"available": vulkan_available,
"recommended": vulkan_available and not cuda_available,
})
return {"detected": detected, "options": options}
@staticmethod
def install_llama_cpp_python_gen(choice=None):
"""Install a matching llama-cpp-python package for this machine.
choice ("auto" / "cpu" / "cuda" / "vulkan", or None = auto): the
explicit build the user picked in the Settings popup. Auto still
decides by hardware; a non-viable explicit pick degrades to CPU with a
clear message (never a mismatched GPU wheel).
For NVIDIA CUDA GPUs:
- Detects CUDA version / compute capability.
- Installs from abetlen pre-built CUDA wheel index (e.g. cu124, cu121, cu118).
For CPU / unknown:
- Installs standard CPU llama-cpp-python package from PyPI.
Yields progress messages for UI streaming.
"""
status = HardwareManager.get_system_status()
brand = status["gpu_brand"]
cuda_ver = status["cuda_version"]
runtime_major = HardwareManager.detect_installed_cuda_runtime_major()
yield "🚀 Starting llama-cpp-python installation..."
yield f"🔍 Detected Hardware: GPU Brand = {brand.upper()}, CUDA Version = {cuda_ver or 'N/A'}"
if runtime_major is not None:
yield f"ℹ️ Detected installed CUDA runtime DLL family: cublas64_{runtime_major}.dll"
# The ONLY signals that decide whether a CUDA wheel is safe here are
# (a) the GPU's compute capability and (b) the CUDA runtime DLLs
# actually installed on this PC. The NVIDIA driver's reported CUDA
# version is NOT one of them (a modern driver can report CUDA 13 while
# only a CUDA-12 runtime exists — a CUDA-13 wheel then fails to load),
# and neither is torch.cuda.is_available() (a CPU-only torch build
# simply cannot see the GPU at all, e.g. the Store package or any
# machine whose torch got installed as the CPU build). Compute
# capability is resolved independently of torch (torch → nvidia-smi)
# so the old-GPU guard below also fires on CPU-only builds.
cc = _gpu_compute_capability()
try:
cc_f = float(cc) if cc else 0.0
except (TypeError, ValueError):
cc_f = 0.0
gpu_name = _gpu_name()
wheel_url = None
# An explicit choice (cpu / cuda / vulkan — from the Settings popup)
# overrides auto-detection. Every guard below still applies: a choice
# the machine cannot actually run NEVER installs a broken wheel — it
# degrades to the CPU build with a clear message, exactly like the
# auto path (never a silent, mismatched GPU wheel).
choice = (choice or "auto").lower()
if choice not in ("auto", "cpu", "cuda", "vulkan"):
yield f"❌ Unknown llama-cpp-python build '{choice}' (expected auto / cpu / cuda / vulkan)."
return
if choice == "cpu":
yield "ℹ️ CPU build selected by the user."
elif choice == "cuda":
if (
brand == "nvidia"
and cc_f >= 7.0
and runtime_major in (12, 13)
and _cpu_supports_avx512()
):
tag = "v0.3.34-cu130" if runtime_major >= 13 else "v0.3.34-cu124"
wheel_url = (
f"https://github.com/abetlen/llama-cpp-python/releases/download/{tag}/"
f"llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
)
yield f"ℹ️ NVIDIA CUDA build selected by the user ({tag})."
else:
yield (
"⚠️ The NVIDIA CUDA build is not usable on this machine "
"(requires a modern NVIDIA GPU, an installed CUDA 12/13 runtime "
"and an AVX-512 CPU). Falling back to the CPU build."
)
elif choice == "vulkan":
if brand in ("amd", "intel"):
vulkan_url = _llama_cpp_vulkan_wheel_url()
if vulkan_url:
wheel_url = vulkan_url
yield "ℹ️ Vulkan build selected by the user (AMD/Intel GPU)."
else:
yield (
"⚠️ The Vulkan prebuilt wheel is not available on this platform. "
"Falling back to the CPU build."
)
else:
yield (
"⚠️ The Vulkan build needs an AMD or Intel GPU (detected "
f"GPU brand: {brand or 'unknown'}). Falling back to the CPU build."
)
elif brand == "nvidia":
if cc_f and cc_f < 7.0:
# Pascal (6.x) and older cannot run the CUDA kernels in any
# current llama.cpp build — a CUDA wheel would import (if the
# runtime DLLs happen to be present) but blow up on the first
# real kernel launch. CPU is the only correct choice.
yield (
f"⚠️ NVIDIA GPU '{gpu_name or 'unknown'}' (compute capability {cc}, Pascal or older) "
"is too old for current llama.cpp CUDA kernels. "
"Using CPU llama-cpp-python to keep the app stable."
)
elif cc_f and cc_f >= 7.0 and runtime_major in (12, 13):
# Modern GPU + a matching installed CUDA runtime: install the
# wheel that links against the runtime DLLs actually present
# (cublas64_12.dll → cu124, cublas64_13.dll → cu130) — BUT only
# when the CPU can execute AVX-512. Those CUDA wheels are
# compiled with AVX-512 code paths, and on Intel consumer CPUs
# (no AVX-512 since Alder Lake, e.g. i7-14700F) EVERY model
# load crashes with STATUS_ILLEGAL_INSTRUCTION (0xc000001d).
# The CPU wheel below has no AVX-512 and loads fine; GPU
# offload on such machines still works via the external
# llama-server backend (per-architecture CPU DLL dispatch).
if not _cpu_supports_avx512():
yield (
f"⚠️ CPU '{_cpu_name()}' does not support AVX-512, but the "
"llama-cpp-python CUDA wheels are compiled with AVX-512 "
"code paths and would crash loading any GGUF "
"(STATUS_ILLEGAL_INSTRUCTION 0xc000001d). Installing the "
"CPU wheel instead — GPU offload still works via the "
"🖥️ llama-server backend."
)
else:
tag = "v0.3.34-cu130" if runtime_major >= 13 else "v0.3.34-cu124"
wheel_url = (
f"https://github.com/abetlen/llama-cpp-python/releases/download/{tag}/"
f"llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
)
elif cc_f and cc_f >= 7.0:
# Modern GPU but no supported CUDA runtime DLLs on PATH (e.g.
# driver-only gaming rigs — very common). A CUDA wheel cannot
# load without the runtime it links against.
yield (
"⚠️ Your GPU supports CUDA, but no matching CUDA runtime DLLs "
"(cublas64_12.dll / cublas64_13.dll) were found on this PC, so a CUDA "
"wheel could not load. Using the CPU llama-cpp-python package instead."
)
else:
# Compute capability could not be determined (torch is a
# CPU-only build and nvidia-smi is unavailable). Installing a
# CUDA wheel blind is exactly how broken installs happen — CPU
# is the safe out-of-the-box default.
yield (
"⚠️ Could not verify this NVIDIA GPU's compute capability, so a CUDA wheel "
"could be mismatched. Using the safe CPU llama-cpp-python package instead "
"(install a CUDA wheel manually if your GPU is supported)."
)
elif brand in ("amd", "intel"):
wheel_url = "https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34-vulkan/llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
try:
if wheel_url:
yield f"🔗 Found hardware-matched pre-built wheel: {wheel_url}"
cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", wheel_url]
else:
cpu_url = _llama_cpp_cpu_wheel_url()
if cpu_url:
yield f"ℹ️ Using prebuilt CPU wheel for llama-cpp-python (avoids a source build): {cpu_url}"
cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", cpu_url]
else:
yield "ℹ️ Using standard CPU/default PyPI package for llama-cpp-python."
cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", "llama-cpp-python"]
yield f"Running: {' '.join(cmd)}"
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
creationflags=CREATE_NO_WINDOW,
)
for line in process.stdout:
yield line.strip()
process.wait()
if process.returncode != 0 and wheel_url:
yield f"⚠️ CUDA wheel install exited with code {process.returncode}. Retrying with the CPU wheel..."
cpu_url = _llama_cpp_cpu_wheel_url()
cmd_fallback = _pip_base_args() + ["--no-cache-dir",
cpu_url or "llama-cpp-python"]
yield f"Running: {' '.join(cmd_fallback)}"
p2 = subprocess.Popen(
cmd_fallback, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
creationflags=CREATE_NO_WINDOW,
)
for line in p2.stdout:
yield line.strip()
p2.wait()
process = p2
if process.returncode == 0:
yield "✨ llama-cpp-python installation finished successfully!"
try:
import importlib # `sys` is already module-level; importing it here would shadow the global and break getattr(sys, 'frozen') above
for mod_name in list(sys.modules.keys()):
if mod_name == "llama_cpp" or mod_name.startswith("llama_cpp."):
del sys.modules[mod_name]
if "backend.llama_backend" in sys.modules:
importlib.reload(sys.modules["backend.llama_backend"])
import backend.llama_backend as lb
if not lb.LLAMA_CPP_AVAILABLE and wheel_url:
yield "⚠️ Installed wheel still cannot import cleanly. Reinstalling the CPU llama-cpp-python package..."
cpu_url = _llama_cpp_cpu_wheel_url()
cmd_cpu = _pip_base_args() + [
"--force-reinstall", "--no-cache-dir",
cpu_url or "llama-cpp-python"]
yield f"Running: {' '.join(cmd_cpu)}"
process_cpu = subprocess.Popen(
cmd_cpu, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
creationflags=CREATE_NO_WINDOW,
)
for line in process_cpu.stdout:
yield line.strip()
process_cpu.wait()
if process_cpu.returncode != 0:
yield f"❌ CPU fallback install failed with exit code {process_cpu.returncode}."
return
for mod_name in list(sys.modules.keys()):
if mod_name == "llama_cpp" or mod_name.startswith("llama_cpp."):
del sys.modules[mod_name]
if "backend.llama_backend" in sys.modules:
importlib.reload(sys.modules["backend.llama_backend"])
import backend.llama_backend as lb
lb.LLAMA_CPP_AVAILABLE = True
lb.LLAMA_CPP_GPU_AVAILABLE = lb._detect_llama_cpp_gpu_support()
gpu_state = "GPU CUDA offload" if lb.LLAMA_CPP_GPU_AVAILABLE else "CPU mode"
yield f"✅ llama-cpp-python is ready ({gpu_state})!"
except Exception as e:
yield f"✅ llama-cpp-python installed! (Note: backend state refresh notice: {e})"
else:
yield f"❌ llama-cpp-python installation failed with exit code {process.returncode}."
except Exception as e:
yield f"❌ Error during installation: {e}"
# ──────────────────────────────────────────────────────────────────
# Real GPU/PyTorch kernel-compatibility check
# ──────────────────────────────────────────────────────────────────
# `torch.cuda.is_available()` only checks that the CUDA *driver* and
# runtime can be initialized — it does NOT mean this specific PyTorch
# build actually ships compiled kernels for this specific GPU's compute
# capability. PyTorch wheels only include kernels ("sm_XX" binaries) for
# a fixed list of architectures; older cards (e.g. Pascal/sm_6x,
# Maxwell/sm_5x) have been dropped from recent stable releases even
# though `torch.cuda.is_available()` still happily reports True and the
# model even *loads* onto the device — it only blows up the moment a
# real CUDA kernel is launched (e.g. during model loading's
# tie_weights()), with "CUDA error: no kernel image is available for
# execution on the device".
#
# This is exactly the gap that let a machine with e.g. an NVIDIA GeForce
# MX230 (compute capability 6.1) silently get a "cuda-capable" verdict
# from is_available(), install a GPU build via SETUP.ps1, and then crash
# on first real use. SETUP.ps1 now does a real-kernel smoke test right
# after installing torch (mirroring the same pattern already used there
# for llama-cpp-python) and falls back to a CPU wheel automatically if it
# fails — but a user could still end up here via a manual `pip install
# torch` re-install, a different Python environment, a driver/GPU swap,
# etc. So this same check is repeated here at app-import time as a
# runtime safety net: DEVICE only resolves to "cuda" if a real kernel
# actually runs successfully, not just because is_available() said so.
# ──────────────────────────────────────────────────────────────────
def _detect_gpu_kernel_incompatibility() -> Optional[dict]:
"""Best-effort: if a CUDA GPU is visible but this torch build has no
compiled kernels for its compute capability, return a small dict with
enough detail for the UI to build a clear, actionable warning
(gpu_name, compute capability, and the archs this torch build DOES
support). Returns None if the GPU is fully usable (or there's no GPU
at all — that's a normal CPU-only setup, not a warning-worthy state).
"""
if not torch.cuda.is_available():
return None
try:
gpu_name = torch.cuda.get_device_name(0)
cc_major, cc_minor = torch.cuda.get_device_capability(0)
cc_str = f"{cc_major}.{cc_minor}"
try:
arch_list = torch.cuda.get_arch_list()
except Exception:
arch_list = []
archs_str = ", ".join(a.replace("sm_", "") for a in arch_list) if arch_list else "unknown"
# The real test: actually launch a kernel, not just check
# is_available(). Wrapped so a torch UserWarning about the CC
# mismatch (torch itself often prints one on this exact call)
# doesn't spam the console a second time here — SETUP.ps1 /
# the terminal already shows torch's own version of this warning;
# this function only needs the pass/fail result.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
x = torch.randn(8, device="cuda")
_ = x @ x
torch.cuda.synchronize()
kernel_ok = True
except Exception:
kernel_ok = False
if kernel_ok:
return None
return {
"gpu_name": gpu_name,
"compute_capability": cc_str,
"supported_archs": archs_str,
}
except Exception:
# Detection itself failing shouldn't block startup or produce a
# false warning — treat as "couldn't determine", not "broken".
return None
def _xpu_kernel_works() -> bool:
"""Real-kernel check for Intel XPU (torch.xpu). Like the CUDA path,
is_available() can report True while this torch build/driver can't
actually run kernels (or has no usable device); DEVICE must only
resolve to "xpu" after a real kernel launches successfully.
"""
if not (hasattr(torch, "xpu") and torch.xpu.is_available()):
return False
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
x = torch.randn(8, device="xpu")
_ = x @ x
torch.xpu.synchronize()
return True
except Exception:
return False
# ── Resolved once at import time ────────────────────────────────────
_GPU_INCOMPATIBILITY_INFO = _detect_gpu_kernel_incompatibility()
if torch.cuda.is_available() and _GPU_INCOMPATIBILITY_INFO is None:
DEVICE = "cuda"
elif _xpu_kernel_works():
DEVICE = "xpu"
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
DEVICE = "mps"
else:
DEVICE = "cpu"
if _GPU_INCOMPATIBILITY_INFO is not None:
print(
f"[Hardware] WARNING: GPU '{_GPU_INCOMPATIBILITY_INFO['gpu_name']}' "
f"(compute capability {_GPU_INCOMPATIBILITY_INFO['compute_capability']}) "
f"was detected, but this PyTorch build has no compiled kernels for it "
f"(supports: {_GPU_INCOMPATIBILITY_INFO['supported_archs']}). "
f"Falling back to CPU — see the warning banner in the UI for how to fix this."
)
def get_gpu_incompatibility_info() -> Optional[dict]:
"""Read-only accessor for ui.py: returns the dict built at import time
(see _detect_gpu_kernel_incompatibility() above) describing a
detected-but-unusable GPU, or None if the GPU is fine / there's no
GPU. Used to render a one-time warning banner in the UI so a
non-technical user isn't left guessing why everything is "running on
CPU" despite clearly having an NVIDIA card — the banner explains it
and points at the fix.
"""
return _GPU_INCOMPATIBILITY_INFO
TORCH_DTYPE = torch.float16 if DEVICE != "cpu" else torch.float32
def refresh_system_ui():
status = HardwareManager.get_system_status()
return (
"🔄 Status Refreshed",
# Report the DEVICE this app is ACTUALLY using (resolved once at
# import time above, already accounting for the real-kernel
# compatibility check) rather than status["current_device"], which
# only reflects torch.cuda.is_available() and would misleadingly
# say "CUDA" even on a machine that silently fell back to CPU due
# to a GPU/PyTorch-build compute-capability mismatch.
DEVICE.upper(),
status["cuda_version"] or "N/A",
"✅ Yes" if status["torch_cuda_available"] else "❌ No",
"" # Clear logs
)
def fix_system_ui_generator():
status = HardwareManager.get_system_status()
yield (
"🚀 Starting fix...",
status["current_device"].upper(),
status["cuda_version"] or "N/A",
"✅ Yes" if status["torch_cuda_available"] else "❌ No",
"Starting..."
)
for msg, dev, log in HardwareManager.fix_environment_gen():
yield (
msg,
dev.upper(),
status["cuda_version"] or "N/A",
"✅ Yes" if status["torch_cuda_available"] else "❌ No",
log
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128category,label,model_id,download_size_gb,default,price_in_usd,price_out_usd
hf_api,Gemma-SEA-LION-v4-27B-IT (publicai),aisingapore/Gemma-SEA-LION-v4-27B-IT,,,0.2,0.4
hf_api,Qwen-SEA-LION-v4-32B-IT (publicai),aisingapore/Qwen-SEA-LION-v4-32B-IT,,,0.25,0.5
hf_api,WizardLM-2-8x22B (novita),alpindale/WizardLM-2-8x22B,,,0.62,0.62
hf_api,aya-expanse-32b (cohere),CohereLabs/aya-expanse-32b,,,,
hf_api,aya-vision-32b (cohere),CohereLabs/aya-vision-32b,,,,
hf_api,c4ai-command-a-03-2025 (cohere),CohereLabs/c4ai-command-a-03-2025,,,,
hf_api,c4ai-command-r-08-2024 (cohere),CohereLabs/c4ai-command-r-08-2024,,,,
hf_api,c4ai-command-r7b-12-2024 (cohere),CohereLabs/c4ai-command-r7b-12-2024,,,,
hf_api,c4ai-command-r7b-arabic-02-2025 (cohere),CohereLabs/c4ai-command-r7b-arabic-02-2025,,,,
hf_api,command-a-reasoning-08-2025 (cohere),CohereLabs/command-a-reasoning-08-2025,,,,
hf_api,tiny-aya-earth (cohere),CohereLabs/tiny-aya-earth,,,,
hf_api,tiny-aya-fire (cohere),CohereLabs/tiny-aya-fire,,,,
hf_api,tiny-aya-global (cohere),CohereLabs/tiny-aya-global,,,,
hf_api,tiny-aya-water (cohere),CohereLabs/tiny-aya-water,,,,
hf_api,cogito-671b-v2.1 (together+fireworks),deepcogito/cogito-671b-v2.1,,,1.25,1.25
hf_api,cogito-671b-v2.1-FP8 (together),deepcogito/cogito-671b-v2.1-FP8,,,1.25,1.25
hf_api,DeepSeek-R1 (novita),deepseek-ai/DeepSeek-R1,,,0.7,2.5
hf_api,DeepSeek-R1-0528 (novita+deepinfra),deepseek-ai/DeepSeek-R1-0528,,,0.5,2.15
hf_api,DeepSeek-R1-Distill-Llama-70B (novita),deepseek-ai/DeepSeek-R1-Distill-Llama-70B,,,0.8,0.8
hf_api,DeepSeek-R1-Distill-Llama-8B (nscale),deepseek-ai/DeepSeek-R1-Distill-Llama-8B,,,0.05,0.05
hf_api,DeepSeek-R1-Distill-Qwen-14B (nscale),deepseek-ai/DeepSeek-R1-Distill-Qwen-14B,,,0.2,0.2
hf_api,DeepSeek-R1-Distill-Qwen-7B (nscale),deepseek-ai/DeepSeek-R1-Distill-Qwen-7B,,,0.15,0.15
hf_api,DeepSeek-V3 (novita+deepinfra),deepseek-ai/DeepSeek-V3,,,0.32,0.89
hf_api,DeepSeek-V3.1 (novita+deepinfra),deepseek-ai/DeepSeek-V3.1,,,0.25,0.95
hf_api,DeepSeek-V3.1-Terminus (novita+deepinfra),deepseek-ai/DeepSeek-V3.1-Terminus,,,0.27,0.95
hf_api,DeepSeek-V3.2 (novita+deepinfra),deepseek-ai/DeepSeek-V3.2,,,0.26,0.38
hf_api,DeepSeek-V3.2-Exp (novita),deepseek-ai/DeepSeek-V3.2-Exp,,,0.27,0.41
hf_api,DeepSeek-V3-0324 (novita+deepinfra),deepseek-ai/DeepSeek-V3-0324,,,0.24,0.9
hf_api,DeepSeek-V4-Flash (novita+fireworks+deepinfra),deepseek-ai/DeepSeek-V4-Flash,,,0.09,0.18
hf_api,DeepSeek-V4-Flash-0731 (novita+together+fireworks+baseten+deepinfra),deepseek-ai/DeepSeek-V4-Flash-0731,,,0.08,0.18
hf_api,DeepSeek-V4-Flash-0731 (deepinfra),deepseek-ai/DeepSeek-V4-Flash-0731:deepinfra,,,0.08,0.18
hf_api,DeepSeek-V4-Pro (novita+together+fireworks+baseten+deepinfra),deepseek-ai/DeepSeek-V4-Pro,,,1.3,2.6
hf_api,Gemma-3-12b-it (deepinfra),google/gemma-3-12b-it,,,0.05,0.15
hf_api,Gemma-3-27b-it (deepinfra),google/gemma-3-27b-it,,,0.08,0.16
hf_api,Gemma-3-4b-it (deepinfra),google/gemma-3-4b-it,,,0.05,0.1
hf_api,Gemma-3n-E4B-it (together),google/gemma-3n-E4B-it,,,0.06,0.12
hf_api,Gemma-4-26B-A4B-it (novita+scaleway+deepinfra),google/gemma-4-26B-A4B-it,,,0.07,0.34
hf_api,Gemma-4-31B-it (novita+cerebras+together+deepinfra),google/gemma-4-31B-it,,,0.13,0.38
hf_api,Ling-2.6-1T (novita),inclusionAI/Ling-2.6-1T,,,0.3,2.5
hf_api,LLaMA-3.1-8B-Instruct (novita+nscale+deepinfra),meta-llama/Llama-3.1-8B-Instruct,,,0.02,0.05
hf_api,LLaMA-3.3-70B-Instruct (groq+novita+together+scaleway+ovhcloud),meta-llama/Llama-3.3-70B-Instruct,,,0.14,0.4
hf_api,LLaMA-4-Maverick-17B-128E-Instruct-FP8 (novita),meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8,,,0.27,0.85
hf_api,LLaMA-4-Scout-17B-16E-Instruct (groq+novita+nscale+deepinfra),meta-llama/Llama-4-Scout-17B-16E-Instruct,,,0.09,0.29
hf_api,phi-4 (deepinfra),microsoft/phi-4,,,0.07,0.14
hf_api,MiniMax-M1-80k (novita),MiniMaxAI/MiniMax-M1-80k,,,0.55,2.2
hf_api,MiniMax-M2 (novita),MiniMaxAI/MiniMax-M2,,,0.3,1.2
hf_api,MiniMax-M2.1 (novita),MiniMaxAI/MiniMax-M2.1,,,0.3,1.2
hf_api,MiniMax-M2.5 (novita),MiniMaxAI/MiniMax-M2.5,,,0.3,1.2
hf_api,MiniMax-M2.7 (novita+fireworks+deepinfra),MiniMaxAI/MiniMax-M2.7,,,0.25,1
hf_api,MiniMax-M3 (novita+together+fireworks+deepinfra),MiniMaxAI/MiniMax-M3,,,0.28,1.1
hf_api,Mixtral-8x22B-Instruct-v0.1 (nscale),mistralai/Mixtral-8x22B-Instruct-v0.1,,,1.2,1.2
hf_api,Kimi-K2.5 (novita+deepinfra),moonshotai/Kimi-K2.5,,,0.45,2.25
hf_api,Kimi-K2.6 (novita+together+fireworks+baseten+deepinfra),moonshotai/Kimi-K2.6,,,0.75,3.4
hf_api,Kimi-K2.7-Code (novita+together+fireworks+baseten+deepinfra),moonshotai/Kimi-K2.7-Code,,,0.68,3.4
hf_api,Kimi-K2-Instruct (novita),moonshotai/Kimi-K2-Instruct,,,0.57,2.3
hf_api,Kimi-K2-Instruct-0905 (novita),moonshotai/Kimi-K2-Instruct-0905,,,0.6,2.5
hf_api,MoonshotAI Kimi-K3 (together+fireworks+baseten+deepinfra),moonshotai/Kimi-K3,,,2.85,14.25
hf_api,Hermes-3-Llama-3.1-70B (deepinfra),NousResearch/Hermes-3-Llama-3.1-70B,,,0.7,0.7
hf_api,Nemotron-3-Ultra-550B-A55B-BF16 (deepinfra),nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16,,,1,5
hf_api,Nemotron-3-Ultra-550B-A55B-NVFP4 (together+fireworks),nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4,,,0.6,2.4
hf_api,GPT-OSS-120B (groq+novita+cerebras+nscale+together+fireworks+scaleway+baseten+ovhcloud+deepinfra),openai/gpt-oss-120b,,,0.04,0.17
hf_api,GPT-OSS-20B (groq+novita+nscale+together+fireworks+ovhcloud+deepinfra),openai/gpt-oss-20b,,,0.03,0.14
hf_api,Gemma-4-31B-it-pearl (together),pearl-ai/Gemma-4-31B-it-pearl,,,0.28,0.86
hf_api,Ternary-Bonsai-27B-AWQ-4bit (together),prism-ml/Ternary-Bonsai-27B-AWQ-4bit,,,0,0
hf_api,Ternary-Bonsai-27B-GGUF (together),prism-ml/Ternary-Bonsai-27B-gguf,,,0,0
hf_api,Qwen2.5-72B-Instruct (novita+deepinfra),Qwen/Qwen2.5-72B-Instruct,,,0.36,0.4
hf_api,Qwen2.5-7B-Instruct (together),Qwen/Qwen2.5-7B-Instruct,,,0.3,0.3
hf_api,Qwen2.5-Coder-32B-Instruct (nscale),Qwen/Qwen2.5-Coder-32B-Instruct,,,0.06,0.2
hf_api,Qwen2.5-Coder-3B-Instruct (nscale),Qwen/Qwen2.5-Coder-3B-Instruct,,,0.01,0.03
hf_api,Qwen2.5-Coder-7B-Instruct (nscale),Qwen/Qwen2.5-Coder-7B-Instruct,,,0.01,0.03
hf_api,Qwen3.5-122B-A10B (novita+deepinfra),Qwen/Qwen3.5-122B-A10B,,,0.29,2.4
hf_api,Qwen3.5-27B (novita+deepinfra),Qwen/Qwen3.5-27B,,,0.26,2.4
hf_api,Qwen3.5-35B-A3B (novita+deepinfra),Qwen/Qwen3.5-35B-A3B,,,0.14,1
hf_api,Qwen3.5-397B-A17B (novita+scaleway+ovhcloud+deepinfra),Qwen/Qwen3.5-397B-A17B,,,0.45,3
hf_api,Qwen3.5-9B (together+ovhcloud+deepinfra),Qwen/Qwen3.5-9B,,,0.1,0.15
hf_api,Qwen3.6-27B (ovhcloud+deepinfra),Qwen/Qwen3.6-27B,,,0.32,3.19
hf_api,Qwen3.6-35B-A3B (scaleway+deepinfra),Qwen/Qwen3.6-35B-A3B,,,0.1,0.95
hf_api,Qwen3-14B (nscale+deepinfra),Qwen/Qwen3-14B,,,0.07,0.2
hf_api,Qwen3-235B-A22B (novita+nscale),Qwen/Qwen3-235B-A22B,,,0.2,0.6
hf_api,Qwen3-235B-A22B-Instruct-2507 (novita+nscale+scaleway+deepinfra),Qwen/Qwen3-235B-A22B-Instruct-2507,,,0.09,0.55
hf_api,Qwen3-235B-A22B-Thinking-2507 (novita+deepinfra),Qwen/Qwen3-235B-A22B-Thinking-2507,,,0.23,2.3
hf_api,Qwen3-30B-A3B (novita+deepinfra),Qwen/Qwen3-30B-A3B,,,0.12,0.5
hf_api,Qwen3-32B (groq+novita+nscale+deepinfra),Qwen/Qwen3-32B,,,0.08,0.25
hf_api,Qwen3-4B-Instruct-2507 (nscale),Qwen/Qwen3-4B-Instruct-2507,,,0.01,0.03
hf_api,Qwen3-4B-Thinking-2507 (nscale),Qwen/Qwen3-4B-Thinking-2507,,,0.01,0.03
hf_api,Qwen3-8B (nscale),Qwen/Qwen3-8B,,,0.07,0.18
hf_api,Qwen3-Coder-30B-A3B-Instruct (scaleway),Qwen/Qwen3-Coder-30B-A3B-Instruct,,,0.23,0.91
hf_api,Qwen3-Coder-480B-A35B-Instruct (novita),Qwen/Qwen3-Coder-480B-A35B-Instruct,,,0.38,1.55
hf_api,Qwen3-Coder-Next (novita),Qwen/Qwen3-Coder-Next,,,0.2,1.5
hf_api,Qwen3-Next-80B-A3B-Instruct (novita+deepinfra),Qwen/Qwen3-Next-80B-A3B-Instruct,,,0.09,1.1
hf_api,Qwen3-VL-235B-A22B-Instruct (novita+deepinfra),Qwen/Qwen3-VL-235B-A22B-Instruct,,,0.2,0.88
hf_api,Qwen3-VL-235B-A22B-Thinking (novita),Qwen/Qwen3-VL-235B-A22B-Thinking,,,0.98,3.95
hf_api,Qwen3-VL-30B-A3B-Instruct (novita+deepinfra),Qwen/Qwen3-VL-30B-A3B-Instruct,,,0.15,0.6
hf_api,L3-8B-Lunaris-v1 (novita),Sao10K/L3-8B-Lunaris-v1,,,0.05,0.05
hf_api,L3-8B-Stheno-v3.2 (novita),Sao10K/L3-8B-Stheno-v3.2,,,0.05,0.05
hf_api,Bielik-11B-v3.0-Instruct (publicai),speakleash/Bielik-11B-v3.0-Instruct,,,0.4,0.4
hf_api,Step-3.5-Flash (deepinfra),stepfun-ai/Step-3.5-Flash,,,0.1,0.3
hf_api,Step-3.7-Flash (deepinfra),stepfun-ai/Step-3.7-Flash,,,0.2,1.15
hf_api,Apertus-70B-Instruct-2509 (publicai),swiss-ai/Apertus-70B-Instruct-2509,,,0.82,2.92
hf_api,Apertus-8B-Instruct-2509 (publicai),swiss-ai/Apertus-8B-Instruct-2509,,,0.1,0.2
hf_api,Apertus-v1.5-70B (publicai),swiss-ai/Apertus-v1.5-70B,,,0.82,2.92
hf_api,Apertus-v1.5-8B (publicai),swiss-ai/Apertus-v1.5-8B,,,0.1,0.2
hf_api,Hy3 (deepinfra),tencent/Hy3,,,0.14,0.58
hf_api,Inkling (together+fireworks+baseten+deepinfra),thinkingmachines/Inkling,,,0.95,4.05
hf_api,Inkling-Small (together+baseten+deepinfra),thinkingmachines/Inkling-Small,,,0.45,1.2
hf_api,MiMo-V2.5 (deepinfra),XiaomiMiMo/MiMo-V2.5,,,0.4,2
hf_api,MiMo-V2.5-Pro (deepinfra),XiaomiMiMo/MiMo-V2.5-Pro,,,1,3
hf_api,AutoGLM-Phone-9B-Multilingual (novita),zai-org/AutoGLM-Phone-9B-Multilingual,,,0.04,0.14
hf_api,GLM-4.5-Air (novita+zai-org),zai-org/GLM-4.5-Air,,,0.13,0.85
hf_api,GLM-4.5V (novita+zai-org),zai-org/GLM-4.5V,,,0.6,1.8
hf_api,GLM-4.5V-FP8 (zai-org),zai-org/GLM-4.5V-FP8,,,,
hf_api,GLM-4.6 (novita+zai-org+deepinfra),zai-org/GLM-4.6,,,0.5,2
hf_api,GLM-4.6-FP8 (zai-org),zai-org/GLM-4.6-FP8,,,,
hf_api,GLM-4.6V (zai-org),zai-org/GLM-4.6V,,,,
hf_api,GLM-4.6V-Flash (novita+zai-org),zai-org/GLM-4.6V-Flash,,,0.3,0.9
hf_api,GLM-4.6V-FP8 (zai-org),zai-org/GLM-4.6V-FP8,,,,
hf_api,GLM-4.7 (novita+cerebras+zai-org+baseten+deepinfra),zai-org/GLM-4.7,,,0.4,1.75
hf_api,GLM-4.7-Flash (novita+zai-org+deepinfra),zai-org/GLM-4.7-Flash,,,0.06,0.4
hf_api,GLM-4.7-FP8 (zai-org),zai-org/GLM-4.7-FP8,,,,
hf_api,GLM-4-32B-0414 (novita),zai-org/GLM-4-32B-0414,,,0.55,1.66
hf_api,GLM-5 (novita+zai-org+deepinfra),zai-org/GLM-5,,,0.6,2.08
hf_api,GLM-5.1 (zai-org+deepinfra),zai-org/GLM-5.1,,,1.05,3.5
hf_api,GLM-5.1-FP8 (zai-org),zai-org/GLM-5.1-FP8,,,,
hf_api,ZAI GLM-5.2 (novita+together+fireworks+zai-org+scaleway+baseten+deepinfra),zai-org/GLM-5.2,,,0.75,2.4
hf_api,GLM-5.2-FP8 (zai-org),zai-org/GLM-5.2-FP8,,,,
hf_api,GPT-OSS Safeguard 20B (Groq),openai/gpt-oss-safeguard-20b:groq,,,,
hf_api,GLM-5 (zai-org),zai-org/GLM-5:zai-org,,,,1234567891011121314151617181920212223242526272829303132category,label,model_id,download_size_gb,default
stt,🟢 Whisper-tiny (0.04 GB download | fastest),openai/whisper-tiny,0.04,default
stt,🟡 Whisper-base (0.07 GB download),openai/whisper-base,0.07,
stt,🟡 Whisper-small (0.23 GB download | recommended),openai/whisper-small,0.23,
stt,🇰🇭 Whisper-small — ខ្មែរ (0.23 GB download | Khmer-tuned),seanghay/whisper-small-khmer-v2,0.23,
stt,🇰🇭 Whisper-large-v3-turbo — ខ្មែរ (0.75 GB download | best for Khmer),metythorn/whisper-large-v3-turbo-mixed-20eps-clean-text-197k,0.75,
stt,"🔵 Whisper-large-v3 (1.44 GB download | best accuracy, multilingual incl. Khmer)",openai/whisper-large-v3,1.44,
both,🧠 Gemma-4-E2B Mobile QAT (2.18 GB download | CPU/edge tier),google/gemma-4-E2B-it-qat-mobile-transformers,2.18,default
embed,"BGE-M3 (2.2 GB download | multilingual, recommended default)",BAAI/bge-m3,2.2,default
both,🧠 Gemma-4-E4B Mobile QAT (3.1 GB download | CPU/edge tier),google/gemma-4-E4B-it-qat-mobile-transformers,3.1,default
embed,Jina Embeddings v4 (3.5 GB download | 48GB+ VRAM tier),jinaai/jina-embeddings-v4,3.5,
embed,Qwen3-Embedding-4B (3.75 GB download | 24GB+ VRAM tier),Qwen/Qwen3-Embedding-4B,3.75,
both,🔵 Gemma-4-E2B (4.8 GB download → 3 GB VRAM @4-bit | CPU/<8GB tier),google/gemma-4-E2B-it,4.8,
both,🦥 Unsloth Gemma-4-E2B BnB 4-bit (4.8 GB download | 4-bit pre-quantized),unsloth/gemma-4-E2B-it-unsloth-bnb-4bit,4.8,
both,🧠 Gemma-4-E2B Mobile CT (5.16 GB download | compressed-tensors),google/gemma-4-E2B-it-qat-mobile-ct,5.16,
both,⚡ Gemma-4-E2B W4A16 CT (5.18 GB download | 4-bit compressed-tensors),google/gemma-4-E2B-it-qat-w4a16-ct,5.18,
both,🟢 Gemma-4-E4B (7.4 GB download → 5 GB VRAM @4-bit | 8-12GB tier),google/gemma-4-E4B-it,7.4,
both,🦥 Unsloth Gemma-4-E4B BnB 4-bit (7.4 GB download | 4-bit pre-quantized),unsloth/gemma-4-E4B-it-unsloth-bnb-4bit,7.4,
both,🧠 Gemma-4-E4B Mobile CT (8.08 GB download | compressed-tensors),google/gemma-4-E4B-it-qat-mobile-ct,8.08,
both,⚡ Gemma-4-E4B W4A16 CT (8.14 GB download | 4-bit compressed-tensors),google/gemma-4-E4B-it-qat-w4a16-ct,8.14,
both,"🟠 Gemma-4-12B QAT (11.1 GB download | QAT-optimized, 11% smaller)",google/gemma-4-12B-it-qat-q4_0-unquantized,11.1,
both,⚡ Gemma-4-12B W4A16 CT (12.39 GB download | 4-bit compressed-tensors),google/gemma-4-12B-it-qat-w4a16-ct,12.39,
both,🟠 Gemma-4-12B (24.5 GB download | manual pick),google/gemma-4-12B-it,24.5,
both,🔴 Gemma-4-26B-A4B QAT (26 GB download | QAT-optimized MoE),google/gemma-4-26B-A4B-it-qat-q4_0-unquantized,26,
both,🦥 Unsloth Gemma-4-31B BnB 4-bit (29.1 GB download | 4-bit pre-quantized),unsloth/gemma-4-31B-it-unsloth-bnb-4bit,29.1,
both,"🔴 Gemma-4-31B QAT (31 GB download | QAT-optimized, 10% smaller)",google/gemma-4-31B-it-qat-q4_0-unquantized,31,
both,⚡ Gemma-4-31B W4A16 CT (31.29 GB download | 4-bit compressed-tensors),google/gemma-4-31B-it-qat-w4a16-ct,31.29,
vlm,🔭 Qwen3-VL-2B-Instruct (4.7 GB download | small fast VLM),Qwen/Qwen3-VL-2B-Instruct,4.7,
vlm,🔭 Qwen3-VL-4B-Instruct (9.0 GB download | mid-tier VLM),Qwen/Qwen3-VL-4B-Instruct,9.0,
vlm,🔭 Qwen3-VL-8B-Instruct (18.0 GB download | high-accuracy VLM),Qwen/Qwen3-VL-8B-Instruct,18.0,
embed,🌐 EmbeddingGemma-300M (0.3 GB download | lightweight multilingual),google/embeddinggemma-300m,0.3,embed,🌐 Qwen3-Embedding-0.6B (0.6 GB download | multilingual),Qwen/Qwen3-Embedding-0.6B,0.6,12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394#!/usr/bin/env python3
"""
index_docs.py — CLI indexing tool for LocalAiLab Assistant (by LocalAiLab).
Indexes documents into the app's ChromaDB knowledge base without launching the UI.
Usage examples:
# Index a PDF
python index_docs.py --pdf path/to/doc.pdf
# Index a text file
python index_docs.py --txt path/to/notes.txt
# Index a whole folder of PDFs + txts
python index_docs.py --dir ./my_docs
# Load a HuggingFace dataset
python index_docs.py --hf-dataset m-ric/huggingface_doc --text-col text --source-col source
# Show stats
python index_docs.py --stats
# Clear the index
python index_docs.py --clear
"""
import argparse
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description="Index documents into the RAG knowledge base.")
parser.add_argument("--pdf", help="Path to a PDF file to index")
parser.add_argument("--txt", help="Path to a TXT/MD file to index")
parser.add_argument("--docx", help="Path to a DOCX file to index")
parser.add_argument("--dir", help="Directory; indexes all .pdf / .txt / .md / .docx files inside")
parser.add_argument("--hf-dataset", help="HuggingFace dataset name")
parser.add_argument("--text-col", default="text", help="Column containing text (for HF datasets)")
parser.add_argument("--source-col", default="source", help="Column containing source name (optional)")
parser.add_argument("--stats", action="store_true", help="Print index stats and exit")
parser.add_argument("--clear", action="store_true", help="Clear the entire index and exit")
args = parser.parse_args()
# Import after argparse so --help is instant
from backend.models import get_embed_model, get_chroma_collection
from backend.knowledge_base import (
get_index_stats,
index_pdf_file, index_txt_file, index_docx_file, index_hf_dataset, clear_index,
)
# Pre-warm
get_embed_model()
get_chroma_collection()
if args.clear:
# clear_index returns ([], message_string)
_, msg = clear_index()
print(msg)
return
if args.stats:
print(get_index_stats())
return
if args.pdf:
# index_pdf_file returns a plain string
print(index_pdf_file(args.pdf))
if args.txt:
# index_txt_file returns a plain string
print(index_txt_file(args.txt))
if args.docx:
# index_docx_file returns a plain string
print(index_docx_file(args.docx))
if args.dir:
folder = Path(args.dir)
for f in sorted(folder.iterdir()):
if f.suffix.lower() == ".pdf":
print(index_pdf_file(str(f)))
elif f.suffix.lower() in (".txt", ".md"):
print(index_txt_file(str(f)))
elif f.suffix.lower() == ".docx":
print(index_docx_file(str(f)))
if args.hf_dataset:
# index_hf_dataset returns (message_string, table_list)
msg, _ = index_hf_dataset(args.hf_dataset, args.text_col, args.source_col)
print(msg)
print(get_index_stats())
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""live_stream.py — the live token-streaming bus.
While a chat run is in flight, the model wrappers push the incremental textthey generate onto this module-global bus. The running WS stream drains thebus on the SAME live timer that already forwards `[Tag]` log lines, and theclient receives the deltas as `live` WS events. The chat UI then shows themodel's ACTUAL generated text growing in real time — the raw stream theterminal sees — instead of nothing until the step/answer completes.
Design notes:
- Single global bus, one chat run at a time (the UI gates sends on `busy`).- Run-scoped: ``begin_run()`` clears stale frames and marks the bus active; everything pushed before a run's ``end_run()`` is ignored. Wrappers check ``bus.running`` and keep their ORIGINAL non-streaming path otherwise, so a model call outside a WS chat run (STT report analysis, memory compaction, …) behaves exactly as before.- Generation-scoped: each model call calls ``begin_generation()`` (emits a RESET frame so the UI clears the previous live bubble) then pushes text deltas, then ``end_generation()``. ``drain()`` returns the collapsed view: a single ``(reset, text)`` pair covering everything since the last drain — text after the LAST reset, since intermediate generations' text is never shown live anyway (their complete result lands via `update`/`final` WS events and replaces the transient live bubble)."""
import threading
class LiveGenerationBus: """Thread-safe buffer for incremental generated text, drained by the WS run. See the module docstring for the reset/generation semantics."""
def __init__(self): self._lock = threading.Lock() self._running = False # a WS chat run is active self._gen_active = False # a model call is currently streaming self._frames = [] # ("reset",) / ("text", str) in arrival order
@property def running(self) -> bool: """True while a WS chat run owns the bus (streaming is enabled).""" with self._lock: return self._running
def begin_run(self): """Start a chat run: drop stale frames and enable streaming.""" with self._lock: self._running = True self._gen_active = False self._frames = []
def end_run(self): """Finish a chat run: stop accepting pushes (nothing left to show).""" with self._lock: self._running = False self._gen_active = False self._frames = []
def begin_generation(self): """A new model call is generating: emit a RESET so the UI clears the previous live bubble (the next drain's ``reset`` is True).""" with self._lock: if not self._running: return self._gen_active = True self._frames.append(("reset", ""))
def end_generation(self): """The model call finished its stream (no more in-progress text).""" with self._lock: self._gen_active = False
def push(self, text: str): """A text delta from the generating model. Dropped when no run or no generation is active (a wrapper writing outside its own epoch).""" if not text: return with self._lock: if self._running and self._gen_active: self._frames.append(("text", text))
def drain(self) -> tuple: """Return ``(reset, text)`` for everything since the last drain: ``reset`` True when at least one generation began, ``text`` = the deltas AFTER the LAST reset marker (earlier generations' deltas are dropped — their complete results arrive via update/final anyway). Clears the buffer so the next drain returns only new deltas.""" with self._lock: frames = self._frames self._frames = [] reset = False text = [] for kind, value in frames: if kind == "reset": reset = True text = [] else: text.append(value) return reset, "".join(text)
_bus = LiveGenerationBus()
def get_bus() -> LiveGenerationBus: """The app-wide live-streaming bus (thread-safe).""" return _bus123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356"""
llama_health.py — Launch-time health diagnostic for the llama-cpp-python
native package (llama.cpp DLLs).
WHY THIS EXISTS
---------------
llama-cpp-python is a compiled C-extension package. Its Windows wheels
bundle llama.cpp's own DLLs (ggml*.dll, llama.dll, mtmd.dll, ...) and, for
CUDA builds, link against the NVIDIA CUDA runtime DLLs
(cublas64_*.dll / cudart64_*.dll / cudnn64_*.dll) which must be installed
on the machine. A "broken" install — e.g. a CUDA-13 wheel installed on a
PC that only has the CUDA-12 runtime, or an old GPU whose compute
capability the wheel's kernels no longer target — raises
``RuntimeError: Failed to load shared library ...`` at import time, NOT
``ImportError``. The app must never crash because of that; it must launch,
detect the problem, and tell the user clearly (see the bilingual warning
banner in the Settings tab, built from get_llama_cpp_health()).
DESIGN RULES (see AGENTS.md "Hardware Diversity & Native GPU Packages")
-----------------------------------------------------------------------
* This module NEVER imports llama_cpp at module level.
* Every probe is wrapped so a failure returns a diagnostic dict instead
of raising — import llama_health must always succeed.
* The result is computed once per process and cached.
* All functions are best-effort: any internal failure degrades to a
conservative verdict (e.g. "unknown") rather than a crash.
"""
import contextlib
import functools
import importlib.util
import io
import os
import re
import struct
import subprocess
import sys
from pathlib import Path
from typing import Optional
# ── small helpers (never raise) ──────────────────────────────────────
# NOTE: _gpu_compute_capability() and _gpu_name() are the CANONICAL copies
# used app-wide — backend/hardware.py imports them from here (llama_health
# never imports backend modules, so there is no import cycle). They are kept
# in this module because it is import-light by design (torch is imported
# lazily, so they work even when the llama-cpp-python native wheel is broken
# and torch is a CPU-only build) — the compute-capability signal is what
# decides whether any CUDA wheel can actually run on a machine.
CREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0
@functools.lru_cache(maxsize=1)
def _gpu_compute_capability() -> str:
"""Best-effort compute capability string (e.g. '6.1') of GPU 0.
Returns '' (never raises) when it cannot be determined. Works even when
torch is a CPU-only build (e.g. the Microsoft Store package) by falling
back to nvidia-smi — torch.cuda.is_available() is NOT a reliable signal
for whether a CUDA wheel can run."""
try:
import torch
if torch.cuda.is_available():
maj, mnr = torch.cuda.get_device_capability(0)
return f"{maj}.{mnr}"
except Exception:
pass
try:
out = subprocess.run(
["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"],
capture_output=True, text=True, timeout=5,
creationflags=CREATE_NO_WINDOW,
)
lines = [ln.strip() for ln in out.stdout.splitlines() if ln.strip()]
if lines:
return lines[0]
except Exception:
pass
return ""
@functools.lru_cache(maxsize=1)
def _gpu_name() -> str:
"""Best-effort GPU display name (e.g. 'NVIDIA GeForce MX230').
Returns '' (never raises) when it cannot be determined. Same torch →
nvidia-smi fallback as _gpu_compute_capability()."""
try:
import torch
if torch.cuda.is_available():
return torch.cuda.get_device_name(0) or ""
except Exception:
pass
try:
out = subprocess.run(
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
capture_output=True, text=True, timeout=5,
creationflags=CREATE_NO_WINDOW,
)
lines = [ln.strip() for ln in out.stdout.splitlines() if ln.strip()]
if lines:
return lines[0]
except Exception:
pass
return ""
def _cuda_runtime_dlls() -> dict:
"""Scan PATH plus common CUDA toolkit locations for the NVIDIA runtime
DLLs llama.cpp CUDA wheels link against. Returns a dict of sorted
lists keyed by family: cublas / cublasLt / cudart / cudnn."""
found = {"cublas": [], "cublasLt": [], "cudart": [], "cudnn": []}
dirs = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d.strip()]
cu_path = os.environ.get("CUDA_PATH", "")
if cu_path:
dirs.append(os.path.join(cu_path, "bin"))
for base in ("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA",
"C:/Program Files/NVIDIA Corporation/CUDNN"):
base_p = Path(base)
if not base_p.is_dir():
continue
for child in base_p.iterdir():
if child.is_dir():
dirs.append(str(child / "bin") if (child / "bin").is_dir() else str(child))
seen = set()
for d in dirs:
try:
names = os.listdir(d)
except Exception:
continue
for f in names:
fl = f.lower()
key = None
if fl.startswith("cublas64_"):
key = "cublas"
elif fl.startswith("cublaslt64_"):
key = "cublasLt"
elif fl.startswith("cudart64_"):
key = "cudart"
elif fl.startswith("cudnn64_"):
key = "cudnn"
if key and f not in seen:
seen.add(f)
found[key].append(f)
for k in found:
found[k].sort()
return found
def _pe_imported_dlls(path: Path) -> list:
"""Names of the DLLs a Windows PE file references in its import table.
Used to learn which CUDA-major runtime a wheel's ggml-cuda.dll was
built against (e.g. 'cublas64_13.dll' -> CUDA 13) without loading it.
"""
if sys.platform != "win32":
return []
try:
data = path.read_bytes()
if data[:2] != b"MZ":
return []
pe_off = struct.unpack_from("<I", data, 0x3C)[0]
opt = pe_off + 24
magic = struct.unpack_from("<H", data, opt)[0]
is_pe32plus = magic == 0x20B
dd_import = opt + (112 if is_pe32plus else 96)
import_rva = struct.unpack_from("<I", data, dd_import)[0]
if not import_rva:
return []
num_sec = struct.unpack_from("<H", data, pe_off + 6)[0]
sect_off = opt + (240 if is_pe32plus else 224)
sections = []
for i in range(num_sec):
o = sect_off + i * 40
vsize, vaddr = struct.unpack_from("<II", data, o + 8)
rsize, raddr = struct.unpack_from("<II", data, o + 16)
sections.append((vaddr, max(vsize, rsize), raddr))
def rva_to_off(rva):
for vaddr, vsz, raddr in sections:
if vaddr <= rva < vaddr + vsz:
return raddr + (rva - vaddr)
return None
out = []
for i in range(256):
off = rva_to_off(import_rva + i * 20)
if off is None:
break
name_rva = struct.unpack_from("<I", data, off + 12)[0]
if not name_rva:
break
name_off = rva_to_off(name_rva)
if name_off is None:
continue
end = data.find(b"\x00", name_off)
if end < 0:
continue
out.append(data[name_off:end].decode("ascii", "replace"))
return out
except Exception:
return []
def _find_lib_dir() -> Optional[Path]:
"""Locate the llama_cpp package's DLL folder WITHOUT importing it
(importlib.util.find_spec does not execute the package __init__, so
this still works when the package is broken and would raise)."""
try:
spec = importlib.util.find_spec("llama_cpp")
if spec and spec.submodule_search_locations:
root = Path(next(iter(spec.submodule_search_locations)))
for cand in ("lib", "libs"):
p = root / cand
if p.is_dir():
return p
return root
except Exception:
pass
return None
# ── the diagnostic itself ────────────────────────────────────────────
def _probe_import():
"""Try to import llama_cpp with console output suppressed.
Returns (module_or_None, error_or_None). Never raises. A healthy
install returns the module; ImportError means "not installed"; any
other exception (typically RuntimeError from a failed ctypes DLL
load) means "installed but broken".
"""
try:
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
import llama_cpp as mod
return mod, None
except Exception as e:
return None, e
def _broken_diagnostics(error: str) -> dict:
"""Gather extra clues about WHY an installed-but-broken llama-cpp-python
fails: which DLL failed, which CUDA runtime the wheel needs, and which
CUDA runtime DLLs exist on this PC."""
out = {"failed_dll": "", "needs_cuda": "", "found_cuda": ""}
m = re.search(r"'([^']*\.dll)'", error)
if m:
out["failed_dll"] = m.group(1)
lib_dir = _find_lib_dir()
if lib_dir:
ggml_cuda = lib_dir / "ggml-cuda.dll"
if ggml_cuda.exists():
for dll in _pe_imported_dlls(ggml_cuda):
dm = re.match(r"cublas64_(\d+)\.dll", dll, re.IGNORECASE)
if dm:
out["needs_cuda"] = dm.group(1)
break
found = _cuda_runtime_dlls()
if found["cublas"]:
out["found_cuda"] = ", ".join(found["cublas"])
return out
def _compose_detail(info: dict) -> str:
"""Human-readable (English, technical) summary of the breakage — shown
inside the bilingual warning banner."""
parts = []
if info["needs_cuda"]:
parts.append(
f"this build needs the CUDA {info['needs_cuda']} runtime "
f"(cublas64_{info['needs_cuda']}.dll)"
)
if info["found_cuda"]:
parts.append(f"but only {info['found_cuda']} was found on this PC")
else:
parts.append("but no NVIDIA CUDA runtime DLLs were found on this PC")
cc = info["compute_capability"]
if cc:
try:
if float(cc) < 7.0:
gpu = f" '{info['gpu_name']}'" if info["gpu_name"] else ""
parts.append(
f"GPU{gpu} (compute capability {cc}, Pascal or older) is "
f"too old for the CUDA kernels in modern llama.cpp builds"
)
except ValueError:
pass
if not parts:
parts.append(info["error"][:300] if info["error"] else "package DLLs failed to load")
return "; ".join(parts)
@functools.lru_cache(maxsize=1)
def check_llama_cpp_health() -> dict:
"""Full launch-time health check of the llama-cpp-python install.
Result keys:
status 'ok' | 'broken' | 'not_installed' | 'unknown'
error raw import error string ('' when healthy)
failed_dll DLL named in the load failure ('' if none)
needs_cuda CUDA major the wheel's ggml-cuda.dll links against
found_cuda cublas64_*.dll files found on this PC
compute_capability GPU compute capability, e.g. '6.1' ('' if none)
gpu_name GPU display name ('' if none)
detail human-readable diagnosis ('' when healthy)
Never raises. 'not_installed' is a NORMAL state (the app falls back to
the llama-server / HuggingFace backends); only 'broken' needs a
user-facing warning.
"""
info = {
"status": "unknown",
"error": "",
"failed_dll": "",
"needs_cuda": "",
"found_cuda": "",
"compute_capability": _gpu_compute_capability(),
"gpu_name": _gpu_name(),
"detail": "",
}
mod, err = _probe_import()
if err is None:
info["status"] = "ok"
return info
info["error"] = str(err)[:500]
if isinstance(err, ImportError) and "No module named" in str(err):
info["status"] = "not_installed"
return info
info["status"] = "broken"
info.update(_broken_diagnostics(info["error"]))
info["detail"] = _compose_detail(info)
return info
def get_llama_cpp_health() -> dict:
"""Cached accessor used by the UI (and anything else that needs the
verdict more than once — switch_lang, banner visibility, etc.)."""
return check_llama_cpp_health()
# ── startup console line (mirrors the existing [llama.cpp] diagnostics) ──
_HEALTH = check_llama_cpp_health()
if _HEALTH["status"] == "broken":
print(f"[llama_health] WARNING: in-process GGUF disabled — {_HEALTH['detail']}")
elif _HEALTH["status"] == "ok":
gpu = _HEALTH["gpu_name"] or "no GPU detected"
cc = _HEALTH["compute_capability"] or "n/a"
print(f"[llama_health] OK — llama-cpp-python loads (GPU: {gpu}, "
f"compute capability: {cc}).")
elif _HEALTH["status"] == "not_installed":
print("[llama_health] llama-cpp-python is not installed — GGUF models "
"are available only via the llama-server backend until it is "
"installed from the Settings tab.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""local_server.py — Shared primitives for managing external server subprocesses(llama-server, whisper-server).
Both native backends launch an OpenAI-compatible HTTP server binary as asubprocess and manage it with the same mechanical moves: probe a free port,poll the health endpoint until the server answers, terminate cleanly onstop/restart (kill after a grace period), read the real console tail when alaunch fails, and never leave an orphaned process behind (atexit hook).
This module centralizes those mechanical parts so the two backends can'tdrift apart (e.g. one getting a port-probe bug the other doesn't). Eachbackend keeps only what is genuinely specific to it: the command line tolaunch, the health check, and the config dict that must match for reuse."""
import osimport socketimport subprocessimport sysimport timefrom typing import Optional
# Windows flag to suppress creating a console window for spawned subprocessesCREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0
# How many extra ports to probe past the preferred one before giving up._DEFAULT_PROBE_RANGE = 100
# TCP-connect health cache: (host, port) -> True once a server has been# seen healthy there. Avoids re-probing a known-good port on every turn._TCP_HEALTH_CACHE: dict = {}
def port_is_free(host: str, port: int) -> bool: """True when nothing is listening on (host, port) right now.
Uses a bind test (the accurate "can I listen here?" check) rather than a plain connect-refused test, so TIME_WAIT sockets don't false-negative. """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind((host, port)) return True except OSError: return False
def find_free_port(host: str, preferred: int, max_probe: int = _DEFAULT_PROBE_RANGE) -> int: """First free port at or after `preferred` (probing up to `max_probe` ports), else `preferred` itself — the launch will fail loudly if the port really is taken.""" port = preferred for _ in range(max_probe): if port_is_free(host, port): return port port += 1 return preferred
def tcp_health_ok(host: str, port: int, timeout: float = 2.0) -> bool: """Best-effort TCP connect check (some servers expose no /health route).
Results are cached per (host, port): once a port has answered, later checks short-circuit instead of re-probing on every chat turn. """ key = (host, port) if _TCP_HEALTH_CACHE.get(key): return True with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(timeout) try: s.connect((host, port)) _TCP_HEALTH_CACHE[key] = True return True except (OSError, ConnectionRefusedError): _TCP_HEALTH_CACHE.pop(key, None) return False
def clear_health_cache() -> None: """Forget every cached healthy port (call after stopping a server).""" _TCP_HEALTH_CACHE.clear()
def kill_stray_app_servers(name_tokens: tuple, exe_path: str, dir_signatures: tuple, exclude_pid=None) -> int: """Kill server processes the app itself launched that are no longer managed by the current process, and return how many were killed.
A previous app instance can leave its llama-server / whisper-server subprocess behind (crash, kill -9, taskkill of the parent, the MSIX update flow, …). That orphan keeps its GGUF model resident in VRAM and occupies its port, but THIS process never spawned it — so the normal stop-by-handle path (stop_subprocess on the managed Popen) can't see it. That's the "Free All VRAM still shows ~X% occupied after a restart" leak. This sweep finds such orphans by the app's OWN launch signature and terminates them:
- the process name contains one of `name_tokens` (e.g. 'llama-server'), AND - its executable path equals `exe_path` (the exact binary this app is configured to launch), OR its command line references a model file under one of `dir_signatures` (the app's model directories — the orphan keeps the app's own configured model dir in its `-m` arg).
Both signatures are specific to this app: a llama-server/whisper-server the user runs manually for other purposes (a different binary, a model outside the app's folders) is never touched. `exclude_pid` protects the currently-managed child(ren) — a single pid, or a tuple of pids (the chat AND embedding slots can both be alive; a slot's stop sweep must never reap its sibling). Never raises — inaccessible or vanished processes are skipped. """ killed = 0 try: import psutil except Exception: return killed if isinstance(exclude_pid, int): excluded_pids = {exclude_pid} else: excluded_pids = {p for p in (exclude_pid or ()) if p} norm = os.path.normcase exe_norm = norm(exe_path or "") sigs = [norm(s) for s in (dir_signatures or ()) if s] for proc in psutil.process_iter(["pid", "name", "exe", "cmdline"]): try: info = proc.info name = (info.get("name") or "").lower() if not any(tok.lower() in name for tok in name_tokens): continue pid = info.get("pid") if pid in excluded_pids: continue exe = norm(info.get("exe") or "") if exe_norm and exe == exe_norm: pass # the exact binary this app launches elif sigs: cmd = norm(" ".join(str(c) for c in (info.get("cmdline") or []))) if not any(s in cmd for s in sigs): continue else: continue proc.kill() killed += 1 except (psutil.NoSuchProcess, psutil.AccessDenied): continue except Exception: continue return killed
def stop_subprocess(proc: Optional[subprocess.Popen], tag: str = "") -> None: """Terminate a managed subprocess, escalating to kill after 10s.
Never raises — callers treat stop as best-effort cleanup (the app must always launch and degrade gracefully, per AGENTS.md). """ if proc is None: return try: proc.terminate() try: proc.wait(timeout=10) except subprocess.TimeoutExpired: proc.kill() except Exception: pass
def collect_process_tail(proc: Optional[subprocess.Popen], max_lines: int = 30) -> str: """Last `max_lines` of a process's captured stdout ('' on failure).
Used to surface the real console error when a server exits immediately instead of a bare "connection refused" a moment later. """ if proc is None or proc.stdout is None: return "" try: return "".join(proc.stdout.readlines()[-max_lines:]) except Exception: return ""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176"""backend/metadata_hardening.py — Runtime metadata hardening for frozen/MSIX environments.
In a PyInstaller frozen application or MSIX packaged deployment:1. Packages with '+' in their version strings (such as PyTorch's '2.6.0+cpu' or '2.4.0+cu121') cannot have their '.dist-info' directories packaged directly into MSIX because the Open Packaging Conventions (OPC / MakeAppx) standard forbids the '+' character in filenames and directory names.2. When libraries like 'accelerate' (imported via transformers/smolagents) call `importlib.metadata.version("torch")` or `importlib.metadata.distribution("torch")`, standard `importlib.metadata` raises `PackageNotFoundError: No package metadata was found for torch`.3. This import failure cascades inside transformers and smolagents to: `ModuleNotFoundError: Could not import module 'AutoModelForCausalLM'` `ModuleNotFoundError: Please install 'transformers' extra to use 'TransformersModel'`
This module provides `harden_metadata()` which installs a safe fallback hook into`importlib.metadata` (and the `importlib_metadata` backport if present). If packagemetadata is not found on disk, the hook inspects the imported / importable module's`__version__` and synthesizes the required Distribution metadata."""
from __future__ import annotations
import importlibimport importlib.metadataimport sysfrom typing import Any
class SyntheticDistribution(importlib.metadata.Distribution): """A lightweight synthetic Distribution object satisfying importlib.metadata when on-disk .dist-info / .egg-info directories are missing in frozen builds."""
def __init__(self, name: str, version_str: str) -> None: self._name = name self._ver = str(version_str) if version_str is not None else "0.0.0"
def read_text(self, filename: str) -> str | None: if filename == "METADATA": return ( f"Metadata-Version: 2.1\n" f"Name: {self._name}\n" f"Version: {self._ver}\n" f"Summary: Synthetic package metadata for {self._name}\n" ) return None
def locate_file(self, path: Any) -> Any: return path
@property def version(self) -> str: return self._ver
@property def name(self) -> str: return self._name
@property def entry_points(self) -> tuple: return ()
@property def files(self) -> None: return None
@property def requires(self) -> None: return None
@property def metadata(self) -> dict[str, str]: try: from email.message import EmailMessage msg = EmailMessage() msg["Name"] = self._name msg["Version"] = self._ver return msg except Exception: return {"Name": self._name, "Version": self._ver}
_METADATA_HARDENED = False_ORIG_DISTRIBUTION_FROM_NAME = None_ORIG_DISTRIBUTION_FN = None_ORIG_VERSION_FN = None_ORIG_METADATA_FN = None
def _find_module_version(name: str) -> str | None: """Check if the module is imported or importable and return its __version__.""" norm = name.replace("-", "_") mod = sys.modules.get(norm) if mod is None: try: mod = importlib.import_module(norm) except Exception: pass if mod is not None: v = getattr(mod, "__version__", None) if v is not None: return str(v) # Even if __version__ is not set, the module exists return "0.0.0" return None
def harden_metadata() -> None: """Patch importlib.metadata to synthesize Distribution objects for importable modules whose on-disk .dist-info was stripped or omitted in frozen builds.
Safe to call repeatedly — idempotent. """ global _METADATA_HARDENED global _ORIG_DISTRIBUTION_FROM_NAME, _ORIG_DISTRIBUTION_FN, _ORIG_VERSION_FN, _ORIG_METADATA_FN
if _METADATA_HARDENED: return
_ORIG_DISTRIBUTION_FROM_NAME = importlib.metadata.Distribution.from_name _ORIG_DISTRIBUTION_FN = importlib.metadata.distribution _ORIG_VERSION_FN = importlib.metadata.version _ORIG_METADATA_FN = importlib.metadata.metadata
def _safe_get_distribution(name: str): try: return _ORIG_DISTRIBUTION_FROM_NAME(name) except importlib.metadata.PackageNotFoundError: v = _find_module_version(name) if v is not None: return SyntheticDistribution(name, v) raise
@classmethod def _patched_from_name(cls, name: str): return _safe_get_distribution(name)
def _patched_distribution(distribution_name: str): return _safe_get_distribution(distribution_name)
def _patched_version(distribution_name: str) -> str: try: return _ORIG_VERSION_FN(distribution_name) except importlib.metadata.PackageNotFoundError: v = _find_module_version(distribution_name) if v is not None: return v raise
def _patched_metadata(distribution_name: str): try: return _ORIG_METADATA_FN(distribution_name) except importlib.metadata.PackageNotFoundError: v = _find_module_version(distribution_name) if v is not None: return SyntheticDistribution(distribution_name, v).metadata raise
importlib.metadata.Distribution.from_name = _patched_from_name importlib.metadata.distribution = _patched_distribution importlib.metadata.version = _patched_version importlib.metadata.metadata = _patched_metadata
# Also patch importlib_metadata if already imported if "importlib_metadata" in sys.modules: try: import importlib_metadata importlib_metadata.distribution = _patched_distribution importlib_metadata.version = _patched_version importlib_metadata.metadata = _patched_metadata if hasattr(importlib_metadata, "Distribution"): importlib_metadata.Distribution.from_name = _patched_from_name except Exception: pass
_METADATA_HARDENED = True12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""paths.py — Shared writable-directory resolution (the MSIX §3.5 fix).
A normal install runs with the app root writable, so user data andthird-party binaries live next to the app (./user_data, ./third_party).MSIX/Store installs land in C:\\Program Files\\WindowsApps\\... which isREAD-ONLY for the app — writing there fails at startup. In that caseboth directories are redirected under %LOCALAPPDATA%\\LocalAiLab\\ so thepackaged app still works from the Store (see §3.5 ofMICROSOFT_STORE_DEPLOYMENT.md).
Every module that resolves user_data/ or third_party/ MUST go throughuser_data_dir() / third_party_dir() here — never re-derive the paths(AGENTS.md anti-duplication rule). These are the single source of truthfor where user state and downloaded binaries live."""
import osimport sysfrom pathlib import Path
def _app_root() -> Path: """The folder the app is installed/run from.
- Source/dev runs: the repo root (where app.py / run_webview.py live). - PyInstaller-frozen runs: the folder containing LocalAiLab_App.exe. The spec sets contents_directory="internal", so sys._MEIPASS points at <app>/internal — its parent is the real app folder. """ if getattr(sys, "frozen", False): return Path(sys._MEIPASS).parent return Path(__file__).resolve().parent.parent
APP_ROOT = _app_root()
def _app_root_writable() -> bool: """True when the app root accepts writes (dev repo, loose dist folder, per-user install).
MSIX/Store installs under C:\\Program Files\\WindowsApps are ACL-protected read-only, so the probe fails there and user data is redirected to %LOCALAPPDATA%. A REAL write probe is used rather than os.access() because Windows access checks can lie for restricted tokens — the app must never assume a path is writable and then crash on its first real write (AGENTS.md: "the app MUST always launch"). """ probe = APP_ROOT / ".localailab_write_probe" try: probe.write_text("", encoding="ascii") probe.unlink() return True except OSError: return False
# Computed once at import — every consumer module derives its constants# from this single decision._APP_ROOT_WRITABLE = _app_root_writable()
def _localappdata_base() -> Path: base = os.environ.get("LOCALAPPDATA") if base: return Path(base) # LOCALAPPDATA is normally always set on Windows; this fallback keeps # the app launching on the rare system where it is missing. return Path.home() / "AppData" / "Local"
# %LOCALAPPDATA%\\LocalAiLab — the per-user writable home for a packaged# (MSIX / Program Files) install.LOCALAI_LAB_APP_DATA = _localappdata_base() / "LocalAiLab"
def user_data_dir() -> Path: """Writable root for user state: config, .env, ChromaDB, reports, visual index, GGUF downloads, ...""" if _APP_ROOT_WRITABLE: return APP_ROOT / "user_data" return LOCALAI_LAB_APP_DATA / "user_data"
def third_party_dir() -> Path: """Writable root for downloaded third-party binaries (llama-server, whisper-server, poppler).""" if _APP_ROOT_WRITABLE: return APP_ROOT / "third_party" return LOCALAI_LAB_APP_DATA / "third_party"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490"""report_tools.py — Gradio-free report/model-notice helpers.
These pure functions used to live in `ui/ui.py` (the Gradio UI, nowremoved). They are shared by the web API (backend/web_api.py), thein-process tests, and any consumer that needs report saving / clearing /deleting / opening without importing a UI framework. This module importsNOTHING Gradio-related.
Single source of truth for:- report path resolution + .docx / .txt writers (_answer_docx_path, _transcript_txt_path),- filename sanitization + dedupe (_sanitize_report_filename, _dedupe_report_path),- the reports tree sweep + per-file delete (_clear_old_reports, _list_report_files, _delete_report_file),- the OS "open folder" launcher (_open_folder_in_explorer, _open_reports_folder, _open_tab_reports_folder),- the "already downloaded?" model status notice (get_model_download_notice)."""
import osimport reimport subprocess as _subprocessimport sys as _sysfrom datetime import datetimefrom pathlib import Pathfrom typing import Optional
from backend import model_registry as mrfrom backend import modelsfrom backend.docx_export import markdown_text_to_docx
def _sanitize_report_filename(name, ext: str = ".docx") -> str: """Turn a user-typed report filename into a safe file STEM (no extension). Returns "" when the name is unusable (empty, or nothing survives sanitization) — the caller then falls back to the auto timestamped name.
Sanitization: strips Windows-forbidden filename characters (<>:"/\\|?* and control chars), trims leading/trailing dots and whitespace, caps the length (so the full path stays well under MAX_PATH), and drops a trailing `ext` (the caller's own extension — ".docx" for reports, ".txt" for transcripts — typed by the user, since the writer appends it itself). Path separators are removed, so a name can never escape the report folder. Windows reserved device names (CON/PRN/AUX/NUL/COM*/LPT*) are refused — creating them would fail on Windows, so falling back to the timestamp name is friendlier than a confusing "save failed". Unicode/Khmer filenames survive untouched. Never raises.""" try: if not name: return "" name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "", str(name)).strip() # Leading AND trailing dots/whitespace are stripped — Windows treats # a trailing dot as a directory marker and a leading dot as hidden. name = name.strip(". ").strip() if ext and name.lower().endswith(ext): name = name[:-len(ext)].strip(". ").strip() if name.upper() in {"CON", "PRN", "AUX", "NUL"} or ( name.upper().startswith("COM") and name[3:].isdigit() ) or (name.upper().startswith("LPT") and name[3:].isdigit()): return "" return name[:100] except Exception: return ""
def _dedupe_report_path(out_dir: Path, stem: str, ext: str = ".docx") -> Path: """Return `stem{ext}` — or `stem-2{ext}`, `stem-3{ext}`, … when that exact file already exists — so a custom filename save never silently overwrites a previous report/transcript (the auto timestamp names never collide; the dedupe only matters for user-typed names).""" candidate = out_dir / f"{stem}{ext}" if not candidate.exists(): return candidate i = 2 while (out_dir / f"{stem}-{i}{ext}").exists(): i += 1 return out_dir / f"{stem}-{i}{ext}"
def _answer_docx_path(markdown_text, tab_key: str, filename: str = "") -> Optional[str]: """Write report markdown to a .docx inside the tab's per-tab report folder (user_data/reports/<tab_folder>/ — see model_registry.REPORT_DIRS) via the shared backend.docx_export converter and return its path. Only ever called by the "💾 Save Report" buttons — reports are NEVER auto-saved.
The filename is optional: a non-empty `filename` (sanitized via _sanitize_report_filename, deduped against existing files) becomes the file's stem; an empty/unusable one falls back to the microsecond timestamped name. Returns None — never raises — when the source is empty/unusable, the tab key is unknown, or the converter can't produce a file (e.g. python-docx not installed), so a failed save can never crash the UI.""" try: if not markdown_text: return None out_dir = Path(mr.REPORT_DIRS[tab_key]) out_dir.mkdir(parents=True, exist_ok=True) stem = _sanitize_report_filename(filename) if stem: out_path = str(_dedupe_report_path(out_dir, stem)) else: # datetime (not time.strftime): %f microseconds isn't supported # by time.strftime on Windows and would raise. ts = datetime.now().strftime("%Y%m%d-%H%M%S-%f") out_path = str(out_dir / f"{tab_key}-{ts}.docx") return markdown_text_to_docx(markdown_text, out_path) except Exception: return None
def _transcript_txt_path(transcript, filename: str = "") -> Optional[str]: """Write a transcript to a .txt inside the STT report folder (user_data/reports/stt/) and return its path. Only ever called by the STT tab's "Save Transcript (.txt)" button — transcripts are NEVER auto-saved.
The optional `filename` (the STT tab's filename Textbox, shared with the Save Report button) becomes the file's stem when non-empty; an empty one falls back to the timestamped name. The file is saved as UTF-8 WITH BOM so Windows Notepad renders Khmer correctly on every Windows version (plain UTF-8 without BOM can show as mojibake on older Notepad). Returns None — never raises — when the transcript is empty/unusable, so the download stays hidden.""" try: if not transcript or not transcript.strip(): return None out_dir = Path(mr.REPORT_DIRS["stt"]) out_dir.mkdir(parents=True, exist_ok=True) stem = _sanitize_report_filename(filename, ".txt") if stem: out_path = _dedupe_report_path(out_dir, stem, ".txt") else: # datetime (not time.strftime): %f microseconds isn't supported # by time.strftime on Windows and would raise. ts = datetime.now().strftime("%Y%m%d-%H%M%S-%f") out_path = out_dir / f"stt-transcript-{ts}.txt" out_path.write_text(transcript, encoding="utf-8-sig") return str(out_path) except Exception: return None
def _clear_old_reports(days) -> tuple: """Delete report files older than `days` days from every per-tab folder under user_data/reports/ (model_registry.REPORT_DIRS — general_chat, rag, deep_research, vision, stt, data_analysis) and return (deleted_count, days_used).
Per-report ATTACHED FOLDERS (the data tab's user_data/reports/ data_analysis/<stem>/ folders holding the .docx + its charts) are swept too — their old report files are deleted and a subfolder emptied by the sweep is removed. The tab folders themselves are never deleted; missing dirs are skipped; a file that can't be inspected/unlinked is skipped (OSError swallowed) so a locked file never aborts the sweep. `days` is coerced (non-numeric → 30, < 1 → 1) and returned so the caller can echo the real threshold used in the confirmation message.""" try: days = int(days) except (TypeError, ValueError): days = 30 days = max(1, days) cutoff = datetime.now().timestamp() - days * 86400 total = 0 for folder in mr.REPORT_DIRS.values(): d = Path(folder) if not d.exists(): continue for f in d.iterdir(): try: if f.is_file() and f.stat().st_mtime < cutoff: f.unlink() total += 1 elif f.is_dir(): # A per-report attached folder: sweep its old report # artifacts too, then drop the folder once emptied. for g in f.iterdir(): try: if g.is_file() and g.stat().st_mtime < cutoff: g.unlink() total += 1 except OSError: pass try: if not any(f.iterdir()): f.rmdir() except OSError: pass except OSError: pass return total, days
def _open_folder_in_explorer(folder: str) -> tuple: """Ensure `folder` exists and open it in the OS file explorer.
Returns (ok: bool, error_message: str). The folder is created (parents included) so Explorer never opens a missing path. Uses os.startfile on Windows, `open` on macOS, and xdg-open elsewhere — the opener is the only place a platform difference is allowed.""" base = Path(folder) try: base.mkdir(parents=True, exist_ok=True) except OSError as e: return False, str(e) try: if _sys.platform == "win32": os.startfile(str(base)) elif _sys.platform == "darwin": _subprocess.Popen(["open", str(base)]) else: _subprocess.Popen(["xdg-open", str(base)]) except Exception as e: return False, str(e) return True, ""
def _open_reports_dir(base_dir=None): """Resolve — creating it if needed — the reports base directory.
Pure path resolution (no Explorer — use _open_reports_folder to open it). `base_dir` overrides the default user_data/reports root so callers/tests can point at an arbitrary root. Returns a Path (never raises, never None).""" base = Path(base_dir) if base_dir is not None else Path(mr.REPORT_BASE_DIR) try: base.mkdir(parents=True, exist_ok=True) except OSError: pass return base
_TAB_KEY_ALIASES = { "gen": "gen", "general": "gen", "general_chat": "gen", "rag": "rag", "dr": "dr", "deep_research": "dr", "vis": "vis", "vision": "vis", "stt": "stt", "data": "data", "data_analysis": "data",}
def _normalize_tab_key(tab_key: Optional[str]) -> Optional[str]: if not tab_key: return None k = str(tab_key).strip().lower() return _TAB_KEY_ALIASES.get(k, k if k in mr.REPORT_DIRS else None)
def _open_tab_reports_dir(tab_key: str, reports_dir=None): """Resolve — creating it if needed — ONE tab's own report folder (user_data/reports/<tab_folder>/) under the reports root.
Pure path resolution (no Explorer — use _open_tab_reports_folder to open it). The subfolder name comes from model_registry.REPORT_DIRS ('general_chat' for 'gen', 'deep_research' for 'dr', …); the folder is created on first use so Explorer never opens a missing path. Returns a Path — never raises. An unknown tab key degrades to a named subfolder under the reports root.""" norm_tab = _normalize_tab_key(tab_key) or tab_key reports = _open_reports_dir(reports_dir) configured = mr.REPORT_DIRS.get(norm_tab) if configured: folder = reports / Path(configured).name else: folder = reports / norm_tab try: folder.mkdir(parents=True, exist_ok=True) except OSError: pass return folder
def _open_reports_folder() -> tuple: """Open the reports BASE dir (user_data/reports) in the OS file explorer.
Thin wrapper over the shared _open_folder_in_explorer — see there for the (ok, error_message) contract. Used by the Settings / About '📁 Open Reports Folder' buttons.""" return _open_folder_in_explorer(str(_open_reports_dir()))
def _open_tab_reports_folder(tab_key: str) -> tuple: """Open ONE tab's own report folder (user_data/reports/<tab_folder>/ — see model_registry.REPORT_DIRS) in the OS file explorer.
Returns (ok: bool, error_message: str) — never raises. An unknown tab key degrades to (False, message) instead of crashing, and the folder is created on first use so Explorer never opens a missing path.""" norm_tab = _normalize_tab_key(tab_key) or tab_key if norm_tab not in mr.REPORT_DIRS: return False, f"unknown tab key: {tab_key}" return _open_folder_in_explorer(str(_open_tab_reports_dir(norm_tab)))
def open_reports_folder_for(tab_key: Optional[str] = None, specific_path: Optional[str] = None) -> tuple: """Open a specific report folder, or ONE tab's own report folder when `tab_key` is a known model_registry.REPORT_DIRS key (the per-tab "Open Reports Folder" buttons in the Svelte UI), otherwise the reports BASE dir (Settings / About / KB — tabs without a per-tab report folder).
Returns (ok, message, path) where `path` is the exact folder that was opened (or attempted). Never raises; an unknown/empty tab key falls back to the base dir so the button always opens something sensible.""" if specific_path: p = Path(specific_path) if p.is_file(): p = p.parent if p.is_dir(): ok, message = _open_folder_in_explorer(str(p)) return ok, message, str(p)
norm_tab = _normalize_tab_key(tab_key) if norm_tab and norm_tab in mr.REPORT_DIRS: folder_path = str(_open_tab_reports_dir(norm_tab)) ok, message = _open_tab_reports_folder(norm_tab) return ok, message, folder_path ok, message = _open_reports_folder() return ok, message, str(_open_reports_dir())
def _list_report_files() -> list: """Return the saved report files (relative posix paths under user_data/reports/, e.g. 'general_chat/chat-2026-08-09.docx' or the data tab's 'data_analysis/report-2026-08-09/report-2026-08-09.docx'), sorted by file modification time, NEWEST FIRST.
Missing per-tab folders are skipped; only regular files are listed (per-report attached folders — the data tab's <stem>/ subfolders — are descended one level so their .docx reports still show in the dropdown); a file that can't be inspected (OSError) is skipped. The mtime ordering puts the most recently saved report at the top of the delete dropdown (alphabetical order put e.g. 'rag-report.docx' above 'chat-…' no matter how old it was). The relative paths double as the dropdown's display labels AND values, and are the only thing the per-file delete handler ever touches — it resolves them back against REPORT_BASE_DIR with a traversal guard.""" base = Path(mr.REPORT_BASE_DIR) out = [] for folder in mr.REPORT_DIRS.values(): d = Path(folder) if not d.exists(): continue for f in d.iterdir(): try: if f.is_file(): out.append((f.stat().st_mtime, f.relative_to(base).as_posix())) elif f.is_dir(): for g in f.iterdir(): try: if g.is_file(): out.append((g.stat().st_mtime, g.relative_to(base).as_posix())) except (OSError, ValueError): pass except (OSError, ValueError): pass out.sort(key=lambda item: item[0], reverse=True) return [rel for _, rel in out]
def _delete_report_file(rel_path) -> tuple: """Delete a single saved report file given its path relative to user_data/reports/ and return (ok, error_message).
The relative path is resolved against REPORT_BASE_DIR and MUST stay inside it — a traversal attempt ("../", absolute path) is rejected and never touches anything outside the reports folder. A missing/locked file degrades to (False, message) instead of raising.""" if not rel_path: return False, "no file selected" base = Path(mr.REPORT_BASE_DIR).resolve() target = (base / rel_path).resolve() # base not in target.parents also rejects target == base ("."), which # the relative_to check alone would let through. if base not in target.parents: return False, "path escapes the reports folder" try: target.unlink() except OSError as e: return False, str(e) # Tidy: deleting a report inside a per-report attached folder (the data # tab's <stem>/ subfolder) removes the folder once it's emptied — never # the tab folder itself. parent = target.parent if parent != base and parent.is_dir(): try: if not any(parent.iterdir()): parent.rmdir() except OSError: pass return True, ""
def get_model_download_notice(provider_label: str, model_label: str, option_type: str = "llm", lang_key: str = "kh") -> str: """Returns a dynamic Markdown notice telling the user if the selected model is already downloaded/cached, local GGUF file, or remote API model.""" if not model_label: return ""
if option_type == "llm": options = mr.MODEL_OPTIONS provider_map = mr.LLM_PROVIDER_OPTIONS elif option_type == "vlm": options = mr.VLM_OPTIONS provider_map = mr.VLM_PROVIDER_OPTIONS elif option_type == "stt": options = mr.STT_OPTIONS provider_map = mr.STT_PROVIDER_OPTIONS elif option_type == "embed": options = mr.EMBED_OPTIONS provider_map = mr.EMBED_PROVIDER_OPTIONS else: options = mr.MODEL_OPTIONS provider_map = mr.LLM_PROVIDER_OPTIONS
model_id = options.get(model_label, model_label) provider_id = provider_map.get(provider_label, provider_label) if option_type == "stt" and provider_id in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON): # The whisper.cpp providers list DISCOVERED local files + GGUF STT # presets — NOT STT_OPTIONS (the local-HuggingFace list this # function defaulted to). A preset label therefore never resolved, # fell back to the raw label as id, and every downloaded whisper # model showed the generic "Server Backend Model" text instead of # its real ready/missing state. options = mr.get_model_options_for_provider(provider_id, "stt") model_id = options.get(model_label, model_label) # A GGUF STT preset id ('repo#ggml-base.bin') must become its # CONCRETE local path when the file is already downloaded — the ✅ # branch below stats the path directly, and the multi-root search # also covers models living in the downloader's fallback folder. local = mr._find_local_stt_file(model_id) if local: model_id = local is_khmer = (lang_key == "kh")
if provider_id == mr.PROVIDER_HF_API: if is_khmer: return f"☁️ **ម៉ូដែល HF Inference API** (`{model_id}`): ដំណើរការលើ Hugging Face Cloud (មិនបាច់ទាញយកទៅម៉ាស៊ីនទេ)" return f"☁️ **HF Inference API Model** (`{model_id}`): Runs on Hugging Face Cloud (No local download required)." elif provider_id == mr.PROVIDER_LITELLM: if is_khmer: return f"🔗 **ម៉ូដែល LiteLLM Provider** (`{model_id}`): តភ្ជាប់ទៅកាន់ Remote API Endpoint" return f"🔗 **LiteLLM Provider Model** (`{model_id}`): Routes to remote API endpoint." elif provider_id == mr.PROVIDER_SERVER: if os.path.isfile(model_id): try: size_gb = os.path.getsize(model_id) / (1024 ** 3) if is_khmer: return f"✅ **ឯកសារ GGUF ក្នុងម៉ាស៊ីន រួចរាល់** (`{os.path.basename(model_id)}`, {size_gb:.2f} GB លើថាស)" return f"✅ **Local GGUF File Ready** (`{os.path.basename(model_id)}`, {size_gb:.2f} GB on disk)." except Exception: if is_khmer: return f"✅ **ឯកសារ GGUF ក្នុងម៉ាស៊ីន រួចរាល់**: `{model_id}`" return f"✅ **Local GGUF File Ready**: `{model_id}`" elif str(model_id).lower().endswith((".gguf", ".ggml", ".bin")): if is_khmer: return f"⚠️ **រកមិនឃើញឯកសារ GGUF ក្នុងម៉ាស៊ីនទេ**: `{model_id}`" return f"⚠️ **Local GGUF File Missing**: `{model_id}`" else: if is_khmer: return f"🖥️ **ម៉ូដែល Server Backend**: `{model_id}`" return f"🖥️ **Server Backend Model**: `{model_id}`"
# Local HuggingFace / GGUF local file check if models.is_model_cached(model_id): if is_khmer: return f"✅ **បានទាញយក និងរក្សាទុកក្នុងម៉ាស៊ីនរួចរាល់**: `{model_id}`" return f"✅ **Already Downloaded & Cached Locally**: `{model_id}`" else: size_gb = models.get_download_size_gb(model_id) if is_khmer: size_str = f"ប្រហែល ~{size_gb:.1f} GB" if size_gb else "មិនដឹងទំហំ" if size_gb is not None and size_gb >= 20: return ( f"🚨 **ម៉ូដែលទំហំធំ ({size_str})**: `{model_id}` នឹងទាញយក ({size_str}) ពេលប្រើលើកដំបូង — " f"ការទាញយកអាចចំណាយពេលយូរ។ សូមប្រាកដថាអ្នកមានការតភ្ជាប់អ៊ីនធឺណិត។" ) return f"📥 **មិនទាន់បានទាញយកទេ**: `{model_id}` នឹងទាញយក ({size_str}) ពេលប្រើលើកដំបូង" size_str = f"~{size_gb:.1f} GB" if size_gb else "unknown size" if size_gb is not None and size_gb >= 20: return ( f"🚨 **Large Model ({size_str})**: `{model_id}` will download ({size_str}) on first use — " f"this may take a long time depending on your internet speed." ) return f"📥 **Not Downloaded Yet**: `{model_id}` will download ({size_str}) on first load."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231"""Shared Windows stdio hardening.
On Windows, when the app is launched in certain ways (a GUI-subsystemlauncher like LocalAiLab.exe, pywebview, an MSIX full-trust package, or ahidden console), `sys.stdout` is NOT None — it is a real stream objectwhose underlying OS handle has already been closed or was never valid.`print()` then raises:
OSError: [WinError 6] The handle is invalid
mid-run — e.g. the `[Model] Starting/reusing llama-server …` log line in`get_llm` killed a whole chat turn this way. The old guards only checked`sys.stdout is None`, which misses this case entirely, and`stream.reconfigure()` only changes the encoder — it never touches thebroken handle.
This module is the SINGLE source of truth for making stdout/stderr safe:every entry point (app.py, run_webview.py, backend/web_api.py, and thePyInstaller frozen-boot runtime hook) must go through `harden_stdio()`,which: 1. probes each stream's underlying OS handle (`fileno()` + `os.fstat`), 2. replaces None / handle-broken streams with a UTF-8 devnull writer, and 3. forces UTF-8 + errors=replace on surviving real streams."""
import ioimport osimport reimport sysimport threading
def _null_stream(): return open(os.devnull, "w", encoding="utf-8", errors="replace")
def _stream_handle_is_broken(stream) -> bool: """True when `stream` is None or its underlying OS handle is closed / invalid (a write would raise OSError [WinError 6]).
In-memory streams (StringIO, pytest capture, mock TextIOWrapper) have no real handle at all — they are treated as healthy so test harnesses and library code that swap in fake streams keep working. """ if stream is None: return True try: fd = stream.fileno() except (io.UnsupportedOperation, AttributeError, ValueError): # No real file descriptor (in-memory / fake stream) — writable. return False except Exception: # fileno() itself exploded — assume the handle is unusable. return True try: os.fstat(fd) return False except Exception: # The descriptor exists but its handle is closed/invalid (WinError 6). return True
def harden_stdio(): """Make sys.stdout / sys.stderr safe to print to.
Replaces None or broken-handle streams with a UTF-8 devnull writer (so `print()` never raises OSError [WinError 6]) and forces UTF-8 + errors=replace on surviving real streams (so emoji / Khmer output never raises UnicodeEncodeError on a cp1252 console either).
Safe to call repeatedly / from multiple entry points — idempotent: a stream already pointing at devnull keeps working. """ for name in ("stdout", "stderr"): stream = getattr(sys, name, None) if _stream_handle_is_broken(stream): setattr(sys, name, _null_stream()) continue try: stream.reconfigure(encoding="utf-8", errors="replace") except Exception: pass
# ── Global CREATE_NO_WINDOW monkeypatch ──────────────────────────────────# On Windows, any subprocess call without the CREATE_NO_WINDOW flag# (0x08000000) creates a visible console window that flashes on screen.# Third-party libraries (pdf2image → pdftoppm.exe, sentence_transformers,# transformers, poppler, etc.) don't set this flag, so their subprocess# calls cause terminal windows to flicker during embedding, indexing,# and model loading. This monkeypatch wraps subprocess.Popen and# subprocess.run to inject CREATE_NO_WINDOW automatically._SUBPROCESS_PATCHED = False
def harden_subprocesses(): """Monkeypatch subprocess.Popen and subprocess.run on Windows so every child process is launched without a visible console window.
Safe to call repeatedly — idempotent (patches once). """ global _SUBPROCESS_PATCHED if _SUBPROCESS_PATCHED: return if sys.platform != "win32": return
import subprocess as _sp _CREATE_NO_WINDOW = getattr(_sp, "CREATE_NO_WINDOW", 0x08000000) _orig_popen = _sp.Popen.__init__ _orig_run = _sp.run
def _patched_popen_init(self, *args, **kwargs): flags = kwargs.get("creationflags", 0) if not (flags & _CREATE_NO_WINDOW): kwargs["creationflags"] = flags | _CREATE_NO_WINDOW return _orig_popen(self, *args, **kwargs)
def _patched_run(*args, **kwargs): flags = kwargs.get("creationflags", 0) if not (flags & _CREATE_NO_WINDOW): kwargs["creationflags"] = flags | _CREATE_NO_WINDOW return _orig_run(*args, **kwargs)
_sp.Popen.__init__ = _patched_popen_init _sp.run = _patched_run _SUBPROCESS_PATCHED = True
# The app's own status prints all carry a bracketed tag (``[Model]``,# ``[RAG]`` (embeddings/ChromaDB), ``[llama-server]``, ``[GeneralAgent]``,# ``[memory]`` …). Only those are# captured for streaming to the UI — library/third-party output (and the# occasional stray non-tagged print) is left on the terminal and never# streamed into a chat bubble._TAGGED_LINE_RE = re.compile(r"^\[[A-Za-z][^\]]*\]")
class ThreadStdoutTee(io.TextIOBase): """Wrap sys.stdout so the app's own ``[Tag]``-prefixed status prints from ONE thread are captured for streaming (e.g. into the chat UI) while ALL output still reaches the real stream — the terminal keeps working.
``attach()`` marks the current thread as the capture thread; ``drain()`` returns and clears the complete tagged lines it has written since the last drain. Output from every OTHER thread passes through untouched (chat runs execute on daemon threads, and concurrent runs must never cross-wire their logs). ``restore()`` puts sys.stdout back — but only if it is still THIS tee, so a tee a later concurrent run installed on top is never clobbered. """
def __init__(self, wrapped, warn_predicate=None): super().__init__() self._wrapped = wrapped self._tid = None self._lock = threading.Lock() self._partial = "" self._lines = [] # Optional: a callable(line) -> bool that additionally captures # otherwise-untagged lines (e.g. model-load warnings like the ColPali # ``UNEXPECTED``/``MISSING`` weight report, which the chat's stream # would skip but the KB tab wants surfaced as live progress). self._warn_predicate = warn_predicate
def attach(self): """Mark the calling thread as the capture thread (resets the buffer).""" tid = threading.get_ident() with self._lock: self._tid = tid self._partial = "" self._lines = []
def detach(self): """Stop capturing; buffered lines stay readable via drain().""" with self._lock: self._tid = None
@property def capturing(self) -> bool: return self._tid is not None
def drain(self, flush_partial: bool = False): """Return and clear the captured complete tagged lines. With ``flush_partial`` a trailing line without a newline is returned too (call when the run ends so the final line is never lost). Lines buffered before detach() stay readable.""" with self._lock: out = self._lines self._lines = [] if flush_partial and self._partial: out = out + [self._partial] self._partial = "" return out
def write(self, s): tid = threading.get_ident() if tid == self._tid: with self._lock: self._partial += s if "\n" in self._partial: parts = self._partial.split("\n") self._partial = parts.pop() for p in parts: if _TAGGED_LINE_RE.match(p) or ( self._warn_predicate and self._warn_predicate(p) ): self._lines.append(p) try: return self._wrapped.write(s) except Exception: return len(s or "")
def flush(self): try: return self._wrapped.flush() except Exception: return None
def restore(self): """Put sys.stdout back to the wrapped stream — but ONLY if it is still this tee (a newer tee may have been installed on top).""" if sys.stdout is self: sys.stdout = self._wrapped
def __getattr__(self, name): # Delegate every other attribute (encoding, fileno, isatty, # reconfigure, …) to the wrapped stream so libraries that poke at # sys.stdout keep working. return getattr(self._wrapped, name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""
torchaudio_health.py — Launch-time health diagnostic for the torchaudio
native package and the torch/torchaudio build-tag mismatch.
WHY THIS EXISTS
---------------
torchaudio is a compiled C-extension package whose wheels are build-tagged
for a specific torch build: a ``+cpu`` wheel links against CPU-only torch,
while a ``+cu128`` wheel needs torch's CUDA runtime DLLs
(torch_cuda.dll / c10_cuda.dll) that the CPU build does not ship. Installing
a CUDA torchaudio wheel on top of a CPU-only torch install — which happens
when pip resolves torchaudio from the default PyPI index after torch was
installed from the CPU index — makes ``import torchaudio`` fail at import
time with ``OSError: Could not load this library: ...libtorchaudio.pyd``.
Nothing in the app uses torchaudio directly, but byaldi (visual PDF RAG)
pulls in transformers, whose ``loss_rnnt`` module imports torchaudio
unconditionally — and an unguarded import chain used to kill app startup.
The app must never crash because of that; it must launch, detect the
problem, and tell the user clearly (see the bilingual warning banner in
the Settings tab, built from get_torchaudio_health()).
DESIGN RULES (see AGENTS.md "Hardware Diversity & Native GPU Packages")
-----------------------------------------------------------------------
* This module NEVER imports torchaudio at module level.
* Every probe is wrapped so a failure returns a diagnostic dict instead
of raising — importing torchaudio_health must always succeed.
* The result is computed once per process and cached.
* All functions are best-effort: any internal failure degrades to a
conservative verdict (e.g. "unknown") rather than a crash.
"""
import contextlib
import functools
import importlib.metadata
import importlib.util
import io
import re
def _probe_import():
"""Try to import torchaudio with console output suppressed.
Returns (module_or_None, error_or_None). Never raises. A healthy
install returns the module; ImportError with 'No module named' means
'not installed'; any other exception (typically OSError from a failed
ctypes DLL load) means 'installed but broken'.
"""
try:
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
import torchaudio as mod
return mod, None
except Exception as e:
return None, e
def _is_installed() -> bool:
"""True when the torchaudio package exists on disk. importlib.util.
find_spec does NOT execute the package __init__, so this still works
when the package is broken and would raise at import time."""
try:
return importlib.util.find_spec("torchaudio") is not None
except Exception:
return False
def _torch_info() -> dict:
"""Installed torch version + build tag, best-effort."""
out = {"version": "", "build_tag": ""}
try:
import torch
out["version"] = getattr(torch, "__version__", "") or ""
m = re.search(r"\+([a-z0-9.]+)$", out["version"], re.IGNORECASE)
out["build_tag"] = m.group(1).lower() if m else ""
except Exception:
pass
return out
def _torchaudio_version() -> str:
"""Installed torchaudio wheel version read from dist metadata (never
imports the package). Includes the build tag, e.g. '2.11.0+cu128'."""
try:
return importlib.metadata.version("torchaudio") or ""
except Exception:
return ""
def _broken_diagnostics(error: str) -> dict:
"""Clues about WHY an installed-but-broken torchaudio fails: which DLL
failed, the torch build tag, the torchaudio build tag, and whether the
two form the classic CPU-torch / CUDA-torchaudio mismatch."""
out = {"failed_dll": "", "torch_version": "", "torch_build": "",
"torchaudio_version": "", "torchaudio_build": "", "mismatch": False}
# The real OSError is usually unquoted ("Could not load this library:
# D:\...\libtorchaudio.pyd"); ctypes' FileNotFoundError variant wraps it
# in single quotes. Match either form.
m = re.search(r"[^'\s]*\.pyd", error)
if m:
out["failed_dll"] = m.group(0)
t = _torch_info()
out["torch_version"] = t["version"]
out["torch_build"] = t["build_tag"]
ta = _torchaudio_version()
out["torchaudio_version"] = ta
m2 = re.search(r"\+([a-z0-9.]+)$", ta, re.IGNORECASE)
out["torchaudio_build"] = m2.group(1).lower() if m2 else ""
torch_cpu = "cpu" in out["torch_build"] or out["torch_build"] == ""
out["mismatch"] = bool(torch_cpu and out["torchaudio_build"].startswith("cu"))
return out
def _compose_detail(info: dict) -> str:
"""Human-readable (English, technical) summary — shown inside the
bilingual warning banner. Like llama_health's {detail}, this stays
English in BOTH languages on purpose (do not translate)."""
if info["mismatch"]:
ver = info["torch_version"] or "<your torch version>+cpu"
return (
f"torch is {info['torch_version'] or 'installed'} (CPU-only build) "
f"but the installed torchaudio is {info['torchaudio_version']} "
f"(a CUDA build) — the CUDA wheel needs torch's CUDA runtime DLLs, "
f"which the CPU build doesn't ship, so it can't load "
f"({info['failed_dll'] or 'libtorchaudio.pyd'}). Fix: install the "
f"CPU build of torchaudio matching your torch version: "
f'pip install "torchaudio=={ver}" '
f"--index-url https://download.pytorch.org/whl/cpu"
)
if info["failed_dll"]:
return (
f"{info['failed_dll']} failed to load. Visual PDF RAG (byaldi) "
f"will be unavailable until torchaudio is reinstalled with a build "
f"matching your torch install "
f"({info['torch_version'] or 'torch'})."
)
return (info.get("error") or "torchaudio's native library failed to load")[:300]
@functools.lru_cache(maxsize=1)
def check_torchaudio_health() -> dict:
"""Full launch-time health check of the torchaudio install.
Result keys:
status 'ok' | 'broken' | 'not_installed' | 'unknown'
error raw import error string ('' when healthy)
failed_dll DLL/.pyd named in the load failure ('' if none)
torch_version installed torch version, e.g. '2.11.0+cpu'
torchaudio_version installed torchaudio wheel version (from metadata)
torch_build torch build tag, e.g. 'cpu' ('' if none)
torchaudio_build torchaudio build tag, e.g. 'cu128' ('' if none)
mismatch True when torch is CPU-only but torchaudio is CUDA
detail human-readable diagnosis ('' when healthy)
Never raises. 'not_installed' is a NORMAL state (visual RAG simply
isn't available, and the app handles that); only 'broken' needs a
user-facing warning.
"""
info = {
"status": "unknown", "error": "", "failed_dll": "",
"torch_version": "", "torchaudio_version": "",
"torch_build": "", "torchaudio_build": "",
"mismatch": False, "detail": "",
}
if not _is_installed():
info["status"] = "not_installed"
return info
mod, err = _probe_import()
if err is None:
info["status"] = "ok"
return info
info["status"] = "broken"
info["error"] = str(err)[:500]
info.update(_broken_diagnostics(info["error"]))
info["detail"] = _compose_detail(info)
return info
def get_torchaudio_health() -> dict:
"""Cached accessor used by the UI (banner visibility, switch_lang)."""
return check_torchaudio_health()
# ── startup console line (mirrors llama_health's) ────────────────────
_HEALTH = check_torchaudio_health()
if _HEALTH["status"] == "broken":
print(f"[torchaudio_health] WARNING: torchaudio is installed but BROKEN — "
f"visual PDF RAG (byaldi) will not load. {_HEALTH['detail']}")
elif _HEALTH["status"] == "ok":
print("[torchaudio_health] OK — torchaudio imports cleanly.")
elif _HEALTH["status"] == "not_installed":
print("[torchaudio_health] torchaudio is not installed — visual PDF RAG "
"is unavailable (optional feature).")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""
user_config.py — Tiny persisted-settings store (survives app restarts).
Currently stores the GGUF model folder path (so the user only has to
type/scan it once) and the UI language (so the app restarts in the user's
last-chosen Khmer or English UI).
"""
import json
from pathlib import Path
from backend.paths import user_data_dir
USER_DATA_DIR = user_data_dir()
USER_CONFIG_PATH = USER_DATA_DIR / "user_config.json"
def load_user_config() -> dict:
try:
if USER_CONFIG_PATH.exists():
return json.loads(USER_CONFIG_PATH.read_text(encoding="utf-8"))
except Exception as e:
print(f"[Config] Could not read '{USER_CONFIG_PATH}': {e}")
return {}
def save_user_config(updates: dict) -> None:
try:
USER_DATA_DIR.mkdir(parents=True, exist_ok=True)
data = load_user_config()
data.update(updates)
USER_CONFIG_PATH.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
USER_CONFIG.update(updates)
except Exception as e:
print(f"[Config] Could not write '{USER_CONFIG_PATH}': {e}")
# Loaded once at import time; individual values are re-read via
# load_user_config() when freshness matters (there's only ever one process
# writing this file, so a module-level snapshot is fine for startup use).
USER_CONFIG = load_user_config()
DEFAULT_LANG = "kh"
def get_saved_lang() -> str:
"""The persisted UI language ('kh' or 'en'); defaults to Khmer when the
user has never changed it or the stored value is invalid."""
lang = USER_CONFIG.get("lang", DEFAULT_LANG)
return "kh" if lang != "en" else "en"
def set_saved_lang(lang: str) -> None:
"""Persist the UI language choice ('kh' or 'en') for the next launch."""
save_user_config({"lang": "kh" if lang != "en" else "en"})
def is_first_run() -> bool:
"""True until the user has seen (and dismissed) the first-run onboarding
— the Settings-tab landing + popup shown on the very first launch.
Persisted under the 'first_run_done' key, so it shows exactly once and
never again on later launches."""
return not USER_CONFIG.get("first_run_done", False)
def mark_first_run_done() -> None:
"""Persist that the first-run onboarding has been seen so it never
shows again (idempotent — the UI calls this when the popup is
dismissed)."""
save_user_config({"first_run_done": True})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""
whisper_cpp_backend.py — Optional whisper.cpp server backend for
Speech-to-Text, alongside the local HuggingFace (transformers/Whisper)
pipeline used elsewhere in the app.
A single mode is supported:
1. External process — the app launches (or reuses an already‑running)
`whisper-server` executable (https://github.com/ggerganov/whisper.cpp)
and talks to it over its OpenAI‑compatible HTTP API
(`POST /v1/audio/transcriptions`).
The server process is started lazily on first use and kept alive across
turns until the model or a config change triggers a restart.
"""
import atexit
import os
import shlex
import subprocess
import time
from pathlib import Path
from typing import Optional
from backend import user_config
from backend.local_server import (
CREATE_NO_WINDOW,
clear_health_cache,
collect_process_tail,
find_free_port,
port_is_free,
stop_subprocess,
tcp_health_ok,
)
try:
WHISPER_CPP_AVAILABLE = True
except ImportError:
WHISPER_CPP_AVAILABLE = False
# ──────────────────────────────────────────────────────────────────
# whisper-server executable path — NOT hardcoded. Resolution order:
# 1. WHISPER_CPP_SERVER_EXE environment variable (per‑launch override)
# 2. Persisted setting from user_config.json
# 3. Empty (feature off) if neither is set
# ──────────────────────────────────────────────────────────────────
WHISPER_CPP_SERVER_EXE_PATH = (
os.environ.get("WHISPER_CPP_SERVER_EXE", "").strip()
or str(user_config.USER_CONFIG.get("whisper_cpp_server_exe", "")).strip()
)
WHISPER_CPP_SERVER_EXTRA_ARGS = str(
user_config.USER_CONFIG.get("whisper_cpp_server_extra_args", "")
).strip()
WHISPER_SERVER_HOST = "127.0.0.1"
WHISPER_SERVER_DEFAULT_PORT = 8082
_MODEL_DIR = ( # same GGUF folder llama_backend uses — set together via
# rescan_gguf_models()/Settings; initialized from the SAME
# persisted config key so a restarted app rediscovers the
# user's whisper models without a manual re-scan.
os.environ.get("WHISPER_CPP_MODEL_DIR", "").strip()
or str(user_config.USER_CONFIG.get("gguf_model_dir", "")).strip()
)
_whisper_server_proc = None
_whisper_server_config = {} # {"model_path": ..., "port": ...}
def get_whisper_model_dir() -> str:
"""The folder discover_whisper_models() scans — the same GGUF folder
llama_backend uses (both are set together via Settings' model-dir
picker). Empty when no folder is configured."""
return _MODEL_DIR
def set_whisper_server_exe_path(path: str) -> None:
global WHISPER_CPP_SERVER_EXE_PATH
path = (path or "").strip()
WHISPER_CPP_SERVER_EXE_PATH = path
user_config.save_user_config({"whisper_cpp_server_exe": path})
def set_whisper_server_extra_args(args_str: str) -> None:
global WHISPER_CPP_SERVER_EXTRA_ARGS
WHISPER_CPP_SERVER_EXTRA_ARGS = (args_str or "").strip()
user_config.save_user_config({"whisper_cpp_server_extra_args": WHISPER_CPP_SERVER_EXTRA_ARGS})
def set_whisper_model_dir(folder_path: str) -> None:
global _MODEL_DIR
_MODEL_DIR = (folder_path or "").strip()
def discover_whisper_models(folder: Optional[str] = None) -> dict:
"""Scan `folder` for whisper.cpp model files (.ggml or .bin) and
return {label: path} entries.
Falls back to the current _MODEL_DIR if `folder` is not given.
"""
folder = folder if folder is not None else _MODEL_DIR
if not folder:
return {}
p = Path(folder)
if not p.exists():
return {}
found = {}
for f in sorted(p.rglob("*")):
if f.suffix.lower() in (".ggml", ".bin", ".gguf"):
size_mb = f.stat().st_size / (1024 ** 2)
label = f"🎤 {f.stem} (~{size_mb:.0f} MB | whisper.cpp)"
found[label] = str(f)
return found
# ── Server lifecycle ──────────────────────────────────────────────
def is_whisper_server_running() -> bool:
"""Best-effort: is the managed whisper-server subprocess currently
alive? Mirrors llama_backend.is_llama_server_running() — used by the
"Free All VRAM" handler to stop the server even when no Python model
wrapper is cached."""
return (_whisper_server_proc is not None
and _whisper_server_proc.poll() is None)
def stop_whisper_server() -> int:
"""Terminate the managed whisper-server subprocess (if one is running)
AND reap orphaned whisper-server processes a PREVIOUS app instance left
behind, returning how many processes were stopped (0 = nothing running).
Mirrors llama_backend.stop_llama_server()'s orphan sweep: a dead app
instance's whisper-server keeps its model resident in VRAM with no
Python wrapper left to trigger the stop. Matching is by the app's OWN
launch signature — the configured exe path, or a model path under the
app's whisper model dir (see
local_server.kill_stray_app_servers)."""
global _whisper_server_proc, _whisper_server_config
managed_pid = _whisper_server_proc.pid if _whisper_server_proc is not None else None
stopped = 0
if _whisper_server_proc is not None:
print("[whisper-server] Stopping subprocess …")
stop_subprocess(_whisper_server_proc, tag="whisper-server")
stopped += 1
_whisper_server_proc = None
_whisper_server_config = {}
clear_health_cache()
from backend.local_server import kill_stray_app_servers
stray = kill_stray_app_servers(
("whisper-server",),
WHISPER_CPP_SERVER_EXE_PATH,
(_MODEL_DIR,),
exclude_pid=managed_pid,
)
if stray:
print(f"[whisper-server] Reaped {stray} orphaned whisper-server "
f"process(es) from a previous app instance.")
stopped += stray
return stopped
atexit.register(stop_whisper_server)
def get_or_start_whisper_server(model_path: str,
port: Optional[int] = None,
startup_timeout: int = 60) -> str:
"""Ensure a whisper-server process is running with this exact model,
launching/relaunching it if needed, and return its base URL."""
global _whisper_server_proc, _whisper_server_config
if not WHISPER_CPP_SERVER_EXE_PATH:
raise RuntimeError(
"No whisper-server executable is configured. Set its path in the "
"'🖥️ whisper.cpp Server Path' box in the UI (or the "
"WHISPER_CPP_SERVER_EXE environment variable)."
)
exe = Path(WHISPER_CPP_SERVER_EXE_PATH)
if not exe.exists():
raise RuntimeError(
f"whisper-server executable not found at '{exe}'."
)
target_port = port or WHISPER_SERVER_DEFAULT_PORT
wanted = {"model_path": model_path, "port": target_port}
if (_whisper_server_proc is not None and _whisper_server_proc.poll() is None
and _whisper_server_config.get("model_path") == wanted["model_path"]
and tcp_health_ok(WHISPER_SERVER_HOST, _whisper_server_config.get("port", target_port))):
return f"http://{WHISPER_SERVER_HOST}:{_whisper_server_config['port']}"
stop_whisper_server()
if not port_is_free(WHISPER_SERVER_HOST, target_port):
target_port = find_free_port(WHISPER_SERVER_HOST, target_port)
wanted["port"] = target_port
cmd = [
str(exe),
"-m", model_path,
"--host", WHISPER_SERVER_HOST,
"--port", str(target_port),
]
if WHISPER_CPP_SERVER_EXTRA_ARGS:
cmd.extend(shlex.split(WHISPER_CPP_SERVER_EXTRA_ARGS))
print(f"[whisper-server] Launching: {' '.join(cmd)}")
_whisper_server_proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
creationflags=CREATE_NO_WINDOW,
)
_whisper_server_config = wanted
deadline = time.time() + startup_timeout
while time.time() < deadline:
if _whisper_server_proc.poll() is not None:
tail = collect_process_tail(_whisper_server_proc, max_lines=20)
_whisper_server_proc = None
_whisper_server_config = {}
raise RuntimeError(
f"whisper-server exited immediately. Last output:\n{tail}"
)
if tcp_health_ok(WHISPER_SERVER_HOST, target_port):
print(f"[whisper-server] Ready — http://{WHISPER_SERVER_HOST}:{target_port}")
return f"http://{WHISPER_SERVER_HOST}:{target_port}"
time.sleep(0.5)
stop_whisper_server()
raise RuntimeError(
f"whisper-server did not become reachable within {startup_timeout}s."
)
# ── WhisperServerModel ────────────────────────────────────────────
class WhisperServerModel:
"""Transcribes audio by POSTing to a running whisper-server's
/v1/audio/transcriptions endpoint (OpenAI-compatible API)."""
def __init__(self, base_url: str, model_path: str, timeout: int = 120):
self.model_id = model_path
self.model_path = model_path
self.base_url = base_url.rstrip("/")
self.timeout = timeout
def transcribe(self, audio_path: str, language: Optional[str] = None) -> str:
import requests
url = f"{self.base_url}/v1/audio/transcriptions"
with open(audio_path, "rb") as f:
files = {"file": (Path(audio_path).name, f, "audio/wav")}
data = {"model": self.model_path}
if language and language != "auto":
data["language"] = language
resp = requests.post(url, files=files, data=data, timeout=self.timeout)
resp.raise_for_status()
result = resp.json()
return result.get("text", "")1234567891011121314151617181920212223242526272829303132333435363738394041# -- Core Agent & Search ----------------------------------------------smolagents[transformers,toolkit,audio]>=1.8.0ddgs>=9.0.0wikipedia-api>=0.8.0
# -- Vector Store & Embeddings ---------------------------------------chromadb>=0.5.0sentence-transformers>=3.0.0
# -- LLM & Inference -------------------------------------------------transformers>=4.48.0accelerate>=0.30.0requests>=2.31.0huggingface_hub>=0.28.0
# -- Vision & Audio --------------------------------------------------qwen-vl-utils>=0.0.8Pillow>=10.0.0soundfile>=0.12.1librosa>=0.10.0scipy>=1.9.0
# -- Document Processing ---------------------------------------------pdfplumber>=0.11.0python-docx>=1.1.0pdf2image>=1.17.0datasets>=2.20.0
# -- Data Analysis ---------------------------------------------------pandas>=2.0.0numpy>=1.26.0matplotlib>=3.8.0openpyxl>=3.1.0
# -- Web Backend & Server --------------------------------------------fastapi>=0.110.0uvicorn[standard]>=0.27.0python-multipart>=0.0.9pydantic>=2.0.0python-dotenv>=1.0.0filelock<3.171# ui package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229"""branding.py — LocalAiLab branding (logo, app name/version) and thebilingual ℹ️ About tab content."""
import base64from pathlib import Path
_LOGO_PATH = Path(__file__).parent / "image" / "logo.jpg"
def _load_logo_b64() -> str: try: data = _LOGO_PATH.read_bytes() return base64.b64encode(data).decode("utf-8") except Exception: return ""
DEVELOPER_LOGO_B64 = _load_logo_b64()DEVELOPER_NAME = "LocalAiLab"APP_NAME_EN = "LocalAiLab Assistant"APP_NAME_KH = "ជំនួយការ LocalAiLab"APP_VERSION = "1.0.0"
# ──────────────────────────────────────────────────────────────────# About tab — always shown bilingually (Khmer first, English below),# independent of the language dropdown. Kept as static strings so it# stays accurate to the current tab order / feature set at a glance.# ──────────────────────────────────────────────────────────────────def about_content_kh(device: str, version: str) -> str: return f"""### 🔖 {APP_NAME_KH} — កំណែ {version}
ជំនួយការ AI LocalAiLab ដែលដំណើរការនៅលើកុំព្យូទ័ររបស់អ្នកផ្ទាល់ ពហុភាសា (ខ្មែរ/អង់គ្លេស) និងពហុម៉ូដាល — ការសន្ទនាទូទៅ វិភាគឯកសារតាមរយៈ RAG ស្រាវជ្រាវស៊ីជម្រៅ យល់ដឹងរូបភាព (Vision)បំលែងសំឡេងទៅជាអក្សរ (STT) វិភាគទិន្នន័យ CSV/Excel ដោយ AI Agent និងគ្រប់គ្រងមូលដ្ឋានចំណេះដឹង — ដំណើរការទាំងស្រុងនៅលើកុំព្យូទ័ររបស់អ្នកដោយប្រើម៉ូដែល HuggingFace (transformers) ឬម៉ូដែលមូលដ្ឋាន GGUF តាមរយៈ llama.cpp / llama-server។ គ្រប់ផ្ទាំងសន្ទនាអាចរក្សាទុកចម្លើយជារបាយការណ៍ Word (.docx) បានភ្លាមៗ។ បង្កើតដោយ LocalAiLab។
---
### 🆕 អ្វីដែលថ្មីក្នុងកំណែ {version}
> *(ការអាប់ដេតក្រោយ GA — tool-calling លំនាំដើម, ស្ថាបត្យកម្ម Manager + Worker, ជ្រើសរើស Embedding តាមផ្នែករឹង, ការបង្កើនល្បឿន និង Web UI ទំនើប)*
- **🛠️ Tool Calling ជាលំនាំដើមសម្រាប់រាល់ Agent**៖ គ្រប់ផ្ទាំង agentic (ទូទៅ / RAG / ស្រាវជ្រាវស៊ីជម្រៅ) បង្កើតជា `ToolCallingAgent` លើគ្រប់ម៉ូដែល រួមទាំង GGUF មូលដ្ឋាន។ ការណែនាំរបស់ agent ប្រើការហៅឧបករណ៍ផ្ទាល់ (`web_search_agent(task=...)`, `final_answer(...)`) យ៉ាងរលូន។- **🧑💼 Data Analysis ដំណើរការ Manager + Worker**៖ ផ្ទាំងវិភាគទិន្នន័យដំណើរការដោយ `ToolCallingAgent` គ្រប់គ្រង ដែលបំបែកសំណួរជាកិច្ចការរង ហើយប្រគល់ឱ្យ sub-agent `data_worker` (`CodeAgent`) អនុវត្តការគណនា Python (pandas/matplotlib) — របាយការណ៍បង្កើតពីលេខពិត មិនដែលប្រឌិតឡើយ។- **📊 របាយការណ៍ និងក្រាហ្វិក Data Analysis ក្នុងថតតែមួយ**៖ រាល់ការវិភាគទិន្នន័យបង្កើតថតរបាយការណ៍ដាច់ដោយឡែក (`user_data/reports/data_analysis/report-YYYY-MM-DD-HHMMSS/`) ដោយរក្សាទុកក្រាហ្វិកទាំងអស់ (.png) ទៅក្នុងថតនោះ។ នៅពេលនាំចេញជា Word (.docx) ឯកសារត្រូវបានរក្សាទុកក្នុងថតតែមួយជាមួយក្រាហ្វិក ហើយប៊ូតុង "📁 បើកថតរបាយការណ៍" បើកចំថតនោះភ្លាមៗ។- **📊 បំពេញទិន្នន័យបាត់ (Missing-Data Completion)**៖ ឧបករណ៍ថ្មី `complete_missing_data` បំពេញក្រឡាទទេក្នុងទិន្នន័យ (.csv/.xlsx) តាមរូបមន្តផ្ទាល់ (rules), តាមទំនាក់ទំនងឈ្មោះជួរឈរ (ប្រាក់ខែសុទ្ធ = ប្រាក់ខែគោល + ប្រាក់បន្ថែម − ពន្ធ) និងការប៉ាន់ស្មានស្ថិតិ — គាំទ្រ CSV គ្រប់ទម្រង់ និងលេខខ្មែរ។- **🛡️ ការផ្សាយទិន្នន័យ WebSocket សុវត្ថិភាព (Surrogate-Safe Streaming)**៖ ការពារបញ្ហា `UnicodeEncodeError` លើរាល់ការផ្សាយទិន្នន័យ WebSocket ក្នុងការសន្ទនា STT និងការវិភាគទិន្នន័យ ដោយលុបបំបាត់ lone Unicode surrogates ដោយស្វ័យប្រវត្តិ។- **🧹 ការសម្អាត Scratchpad & Deliberation Preamble**៖ ដកចេញនូវការគិតផ្ទៃក្នុង (internal deliberation / scratchpad) របស់ម៉ូដែលមុននឹងបង្ហាញរបាយការណ៍ Markdown ឬចម្លើយចុងក្រោយ។- **🔗 ជ្រើសរើស Embedding ដោយដឹងផ្នែករឹង**៖ ChromaDB បង្កើត collection ដាច់ដោយឡែកតាមទំហំ dimension (BAAI/bge-m3, Qwen3-Embedding-4B, Jina Embeddings v4, Multilingual-E5, GGUF embedding server) អាចប្តូរម៉ូដែល embedding ដោយមិនបាត់បង់ ឬខូចទិន្នន័យចាស់។- **🖼️ RAG ពហុម៉ូដាល & Visual Page Search**៖ sub-agent `knowledge_searcher` មានឧបករណ៍ `visual_retriever` (ColPali/ColSmolVLM/ColQwen2) សម្រាប់ទាញរូបភាពទំព័រពីឯកសារស្កេន ឬ PDF ដែលមានក្រាហ្វិក — ផ្ទៀងផ្ទាត់ចម្លើយជាមួយរូបភាពដោយប្រើម៉ូដែលដដែល ដោយមិនផ្ទុក VLM ទីពីរចូល VRAM។- **🔬 ស្រាវជ្រាវស៊ីជម្រៅ (Deep Research)**៖ Agent គ្រប់គ្រង + Search sub-agent បំបែកសំណួរ រៀបចំផែនការឡើងវិញ ស្វែងរកតាមអ៊ីនធឺណិត (DuckDuckGo / Playwright headless browser) និងចងក្រងជារបាយការណ៍ Markdown ពិស្តារ។- **🎙️ STT បំបាត់សំឡេងរំខាន & ម៉ូដែលខ្មែរ**៖ បំលែងសំឡេងជាអក្សរដោយ Whisper (រួមទាំងម៉ូដែលខ្មែរ) មានមុខងារមើលជាមុននៃការបំបាត់សំឡេងរំខាន (Noise Reduction Preview) និងវិភាគទៅជារបាយការណ៍ Word។- **🔧 ការកំណត់បង្កើនល្បឿនផ្នែករឹង (Hardware Acceleration)**៖ គ្រប់គ្រង llama-server (KV-cache quantization: q8_0/q4_0/f16/bf16, threads, tensor-split, draft model speculative decoding, mlock/mmap) និង PyTorch (torch.compile modes, bfloat16) នៅក្នុងផ្ទាំង ⚙️ ការកំណត់។- **🚫 គ្មាន Gradio ទៀតទេ (Svelte + FastAPI តែប៉ុណ្ណោះ)**៖ UI ចាស់របស់ Gradio (`ui/ui.py`) ត្រូវបានលុបចេញទាំងស្រុង — កម្មវិធីនេះឥឡូវគឺ 100% ជា **Svelte 5** web UI (`ui/web/`) ដែលបម្រើដោយ **FastAPI** backend (`backend/web_api.py`) នៅក្នុងបង្អួច pywebview។ គ្មាន Gradio នៅកន្លែងណាទេ: កូដប្រភព អាស្រ័យភាព (dependencies) ឬកម្មវិធីដំឡើង។- **💾 រក្សាទុករបាយការណ៍ជា Word (.docx)**៖ គ្រប់ផ្ទាំងសន្ទនា (ទូទៅ / RAG / ស្រាវជ្រាវស៊ីជម្រៅ / ចក្ខុវិស័យ / STT / វិភាគទិន្នន័យ) អាចរក្សាទុកចម្លើយចុងក្រោយជាឯកសារ Word (.docx) ទៅក្នុងថត `user_data/reports/<ផ្ទាំង>/` តាមតម្រូវការ។- **📁 ការគ្រប់គ្រងថតរបាយការណ៍**៖ ប៊ូតុង "បើកថតរបាយការណ៍" នៅលើផ្ទាំងការកំណត់ និងអំពី បើក `user_data/reports` ក្នុង File Explorer ភ្លាមៗ ព្រមទាំងជម្រើស "សម្អាតរបាយការណ៍ចាស់"។- **🗣️ ចម្លើយធ្វើតាមភាសាចំណុចប្រទាក់**៖ គ្រប��ចម្លើយលើគ្រប់ផ្ទាំងឆ្លើយជាភាសាដូចចំណុចប្រទាក់ (ខ្មែរ ↔ អង់គ្លេស) លើគ្រប់ backend (GGUF, llama-server, HF Inference API, transformers)។- **💥 Free All VRAM + ស្ថានភាព CPU/RAM/VRAM ជាប់នៅ Sidebar**៖ បង្ហាញការប្រើប្រាស់ធនធានផ្ទាល់ និងប៊ូតុងបញ្ចេញ VRAM លើគ្រប់ផ្ទាំង។- **📥 ប្រអប់ជម្រើសដំឡើងដោយដឹងផ្នែករឹង**៖ ប៊ូតុងដំឡើង llama-cpp-python / llama-server / whisper-server / PyTorch បង្ហាញរបាយការណ៍ផ្នែករឹង និងជម្រើសដំឡើងដែលសមស្របបំផុតសម្រាប់កុំព្យូទ័ររបស់អ្នក។- **📥 ការទាញយកម៉ូដែល Live Progress**៖ របាយការណ៍ដំណើរការទាញយកម៉ូដែល HuggingFace បង្ហាញឋិតិវន្តភ្លាមៗ (ភាគរយ, ល្បឿន MB/s, ទំហំដែលបានទាញយក) ជំនួសឱ្យឋិតិវន្ត ០% ដែលឋិតថេរ។- **🛡️ ការជួសជុល TransformersModel ក្នុង MSIX/PyInstaller**៖ កំហុស "Please install transformers extra" ដែលកើតឡើងនៅពេល torch metadata បាត់ក្នុងកញ្ចប់ frozen ឥឡូវត្រូវបានចាប់យកដោយច្បាស់លាស់ និងបង្ហាញសារណែនាំដែលអាចអនុវត្តបាន។- **🔒 ឯកោទិន្នន័យអ្នកប្រើប្រាស់ (`user_data/`)**៖ រាល់ការកំណត់, API keys, ChromaDB vectors, Visual indexes និងរបាយការណ៍ទាំងអស់ ស្ថិតក្នុង `user_data/` ដាច់ដោយឡែកពីកូដកម្មវិធី។
---
## ⌨️ ផ្លូវកាត់ក្តារចុច
| ផ្លូវកាត់ | សកម្មភាព ||---|---|| `Alt+Delete` / `Alt+Backspace` | សម្អាតការសន្ទនា / លទ្ធផលបច្ចុប្បន្ន (សួរបញ្ជាក់ ប្រសិនបើការសន្ទនាវែង) — ផ្ទាំងសន្ទនា និងផ្ទាំងវិភាគទិន្នន័យ || `Alt+D` | ផ្ទាំង STT៖ បើកការមើលជាមុនបំបាត់សំឡេងរំខាន (មុន/ក្រោយ) || `Alt+T` | ផ្ទាំង STT៖ បំបាត់សំឡេងរំខាន + បំលែងជាអក្សរភ្លាមៗ (រួមទាំងរបាយការណ៍) || `Alt+Shift+T` | ផ្ទាំង STT៖ ផ្តោតទៅជម្រើសកម្លាំងបំបាត់សំឡេងរំខាន |
---
## ផ្ទាំងកម្មវិធីទាំង ៩ (App Tabs)
| # | ផ្ទាំង | ការពិពណ៌នា ||---|---|---|| 1 | ⚙️ **ការកំណត់** | គ្រប់គ្រង API keys, provider settings, llama-server/whisper-server paths, ការបង្កើនល្បឿនផ្នែករឹង និងការទាញយកសមាសធាតុ || 2 | 💬 **ការសន្ទនាទូទៅ** | ការសន្ទនាផ្ទាល់ជាមួយ LLM / ToolCallingAgent ជាមួយជម្រើសស្វែងរកតាមអ៊ីនធឺណិត — អាចរក្សាទុកចម្លើយជា Word || 3 | 📚 **ការសន្ទនា RAG** | ទាញយកពីមូលដ្ឋានចំណេះដឹងជាមុន រួមទាំងការស្វែងរកទំព័ររូបភាព (Visual Search) — អាចរក្សាទុកចម្លើយជា Word || 4 | 🔬 **ស្រាវជ្រាវស៊ីជម្រៅ** | Agent គ្រប់គ្រង + agent ស្វែងរកតាមអ៊ីនធឺណិត — បំបែកសំណួរ រៀបចំផែនការឡើងវិញ ស្វែងរកជាបន្តបន្ទាប់ រួចសរសេររបាយការណ៍ Markdown ពិស្តារ || 5 | 🖼️ **ការសន្ទនាចក្ខុវិស័យ** | យល់ដឹងរូបភាព ដោយផ្អែកលើរូបភាពដែលបានបង្ហោះតែប៉ុណ្ណោះ — អាចរក្សាទុកចម្លើយជា Word || 6 | 🎙️ **និយាយទៅជាអក្សរ** | បំលែងសំឡេងជាអក្សរ ដោយប្រើ Whisper (រួមទាំងភា��ាខ្មែរ) ជាមួយការបំបាត់សំឡេងរំខាន — វិភាគទៅជារបាយការណ៍ Word || 7 | 📊 **វិភាគទិន្នន័យ** | Manager + CodeAgent វិភាគ CSV/Excel បំពេញទិន្នន័យបាត់ បង្កើតក្រាហ្វិក និងរបាយការណ៍ Word តាម workflow ជំនាញ || 8 | 📂 **មូលដ្ឋានចំណេះដឹង** | បង្ហោះ (PDF / TXT / MD / DOCX) គ្រប់គ្រងឯកសារ ចាត់ថ្នាក់តាម Theme និងគ្រប់គ្រង Visual Index || 9 | ℹ️ **អំពីកម្មវិធី** | ព័ត៌មានកំណែ ស្ថាបត្យកម្ម បរិយាកាសកញ្ចប់ និងការគ្រប់គ្រងថតរបាយការណ៍ |
---
## ស្ថាបត្យកម្ម
| សមាសធាតុ | លម្អិត ||---|---|| LLM | ម៉ូដែល HuggingFace (Gemma-4 / Qwen3.6 / GLM-4.7-Flash) **ឬ** ម៉ូដែល GGUF មូលដ្ឋានតាមរយៈ llama.cpp/llama-server **ឬ** HF Inference API / LiteLLM || Vision LLM | SmolVLM / Qwen2.5-VL / Qwen3-VL / GGUF mmproj pairs || Speech-to-Text | Whisper (tiny/base/small/large-v3, ម៉ូដែលខ្មែរ Whisper-small ខ្មែរ) **ឬ** whisper.cpp server || Embedding | BAAI/bge-m3, Qwen3-Embedding-4B, Jina Embeddings v4, Multilingual-E5 **ឬ** GGUF embedding server || Vector store | ChromaDB (`./user_data/chroma_db/`) — បំបែក collection តាមទំហំ dimension || Visual Index | ColSmolVLM / ColQwen2 (`./user_data/visual_index/`) សម្រាប់ឯកសារស្កេន និងក្រាហ្វិក || Word export | python-docx (`./user_data/reports/<ផ្ទាំង>/`) — គាំទ្រគ្រប់ផ្ទាំង || 3rd-party tools | Poppler PDF binaries (`./third_party/poppler/`), llama-server, whisper-server || UI | Svelte 5 Web UI (Dark Mode និងក្ដារលាយពណ៌ terracotta កក់ក្តៅ) |
---
## 🔒 សន្តិសុខ និងភាពឯកជន (Security & Privacy)
- **🏠 ដំណើរការក្នុងម៉ាស៊ីន ១០០% (Local-First Processing)**៖ រាល់ការសន្ទនា ការបញ្ចូលឯកសារ ការបង្ហោះរូបភាព ការបំលែងសំឡេង ការវិភាគទិន្នន័យ និង vector index ដំណើរការទាំងស្រុងលើផ្នែករឹងកុំព្យូទ័ររបស់អ្នក (GPU/CPU) នៅពេលប្រើម៉ូដែលមូលដ្ឋាន។ គ្មានទិន្នន័យ ឬ telemetry ណាមួយត្រូវបានបញ្ជូនទៅ server ខាងក្រៅឡើយ។- **📂 ឯកោទិន្នន័យក្នុង `user_data/`**៖ រាល់ការកំណត់ផ្ទាល់ខ្លួន, API keys, ChromaDB vectors, Visual index និងរបាយការណ៍ទាំងអស់ ស្ថិតក្នុងថត `user_data/` តែមួយគត់ — ដាច់ដោយឡែកពីប្រព័ន្ធប្រតិបត្តិការ និងកូដកម្មវិធី។- **🌐 សេវាពពកជាជម្រើសរបស់អ្នក (Optional Cloud Services)**៖ ប្រសិនបើអ្នកជ្រើសរើសប្រើ remote inference (ដូចជា HuggingFace Inference API, LiteLLM) ឬការស្វែងរកតាមអ៊ីនធឺណិត (DuckDuckGo/Playwright) មានតែសំណួរដែលអ្នកស្នើសុំផ្ទាល់ប៉ុណ្ណោះដែលត្រូវបានផ្ញើទៅកាន់ endpoint នោះតាមរយៈ HTTPS ដែលមានសុវត្ថិភាព។ API keys ទាំងអស់រក្សាទុកក្នុងម៉ាស៊ីនរបស់អ្នកជានិច្ច។- **🛡️ សុវត្ថិភាពក្នុងការដំណើរការកូដ (Sandboxed Execution)**៖ ផ្ទាំង Data Analysis ដំណើរការកូដ Python ក្នុងការគណនាទិន្នន័យក្នុងបរិយាកាស sandbox ក្នុងស្រុក ដែលមានដែនកំណត់ពេលវេលា (execution timeout) និងការការពារសុវត្ថិភាពប្រព័ន្ធ។
---
## ល្បឿនរំពឹងទុក ({device})
| កិច្ចការ | ពេលវេលា ||---|---|| បញ្ចូលឯកសារ | ១០–៦០ វិ || ឆ្លើយបែប General / RAG | ១–៣០ វិ || ឆ្លើយបែប Vision | ៣០ វ��� – ២ នាទី |"""
def about_content_en(device: str, version: str) -> str: return f"""### 🔖 {APP_NAME_EN} — Version {version}
A local, bilingual (Khmer/English), multi-modal AI assistant — general chat, document RAG, deep research, vision chat, speech-to-text,AI-driven CSV/Excel data analysis, and knowledge base management — running entirely on your own machine, using eitherHuggingFace (transformers) models, local GGUF models via llama.cpp / llama-server, or remote Inference APIs. Built by LocalAiLab.
---
### 🆕 What's New in Version {version}
> *(post-GA updates — tool-calling default, Manager + Worker architecture, hardware-aware embedding ladder, acceleration controls, modern Web UI)*
- **🛠️ Tool Calling is the Default for Every Agent**: every agentic tab (General / RAG / Deep Research) builds as `ToolCallingAgent` on every model, local GGUFs included. Agent instructions use native tool calls (`web_search_agent(task=...)`, `final_answer(...)`) reliably.- **🧑💼 Data Analysis Runs as Manager + Worker**: the Data tab orchestrates through a `ToolCallingAgent` manager that breaks your question into sub-tasks and delegates each to the `data_worker` sub-agent (`CodeAgent`) executing Python (pandas/matplotlib) — reports are built from real computed numbers, never fabricated ones.- **📊 Data Analysis Report & Chart Co-Location**: Every analysis run generates a dedicated timestamped folder (`user_data/reports/data_analysis/report-YYYY-MM-DD-HHMMSS/`) where all generated PNG charts are stored. Exporting to Word (.docx) saves the document in the same folder alongside all graphs, and "Open Reports Folder" opens that exact subfolder.- **📊 Missing-Data Completion for Any File**: the new `complete_missing_data` tool fills blank cells in any dataset (.csv/.xlsx) — via your explicit formulas (`rules={...}`), auto-derived column relationships (net = base + bonus − tax), and statistical estimation. Supports multiple CSV delimiters and Khmer numerals.- **🛡️ Surrogate-Safe WebSocket Streaming**: Prevents `UnicodeEncodeError` across all WebSocket streams in Chat, STT, and Data Analysis by sanitizing lone Unicode surrogates.- **🧹 Internal Deliberation Preamble Stripping**: Automatically removes internal model scratchpads/meta-deliberations from STT reports, RAG answers, and chat bubbles before rendering.- **🔗 Hardware-Aware Embedding Selection**: ChromaDB isolates collections per embedding dimension (BAAI/bge-m3, Qwen3-Embedding-4B, Jina Embeddings v4, Multilingual-E5, GGUF embedding server), allowing seamless model switching without index corruption.- **🖼️ Multimodal Agentic RAG & Visual Page Search**: the RAG `knowledge_searcher` sub-agent holds a `visual_retriever` tool (ColPali/ColSmolVLM/ColQwen2) alongside text retrieval — scanned documents and chart-heavy PDFs are grounded against page images using the same model without loading a second VLM into VRAM.- **🔬 Deep Research Overhaul**: Manager agent + search sub-agent decomposes complex queries, re-plans iteratively, performs live web searches (DuckDuckGo / Playwright headless browser), and synthesizes comprehensive Markdown reports.- **🎙️ STT Noise Reduction Preview & Khmer Models**: Audio transcription via Whisper (multilingual + Khmer-tuned models) with a live Noise Reduction Preview (spectral gating) and Word report generation.- **🔧 Hardware Acceleration Controls**: Fine-grained settings for llama-server (KV-cache quantization: q8_0/q4_0/f16/bf16, threads, tensor-split, draft model speculative decoding, mlock/mmap) and PyTorch (torch.compile modes, bfloat16) in the ⚙️ Settings tab.- **🚫 Fully Gradio-Free (Svelte + FastAPI Only)**: the old Gradio UI (`ui/ui.py`) is removed entirely — the app is now 100% the custom **Svelte 5** web UI (`ui/web/`) served by the **FastAPI** backend (`backend/web_api.py`) inside the native pywebview window. No Gradio anywhere: source, dependencies, or installer.- **💾 "Save Report" Buttons for Word (.docx)**: Every chat tab (General / RAG / Deep Research / Vision / STT / Data Analysis) saves the latest answer to a Word (.docx) file on demand in `user_data/reports/<tab>/`.- **📁 Report Folder Management**: "Open Reports Folder" on Settings and About opens `user_data/reports` in your file explorer; "Clear Old Reports" cleans files older than N days.- **🗣️ UI-Language Consistency**: every answer on every tab matches the active UI language (Khmer ↔ English) across all backends (GGUF, llama-server, HF Inference API, transformers).- **💥 Sidebar-Pinned Free All VRAM + CPU/RAM/VRAM readout**: live hardware monitor chips and Free All VRAM button accessible from every tab.- **📥 Hardware-Aware Install Dialog Popups**: Install buttons for llama-cpp-python, llama-server, whisper-server, and PyTorch show hardware diagnostics and pre-select the optimal build for your machine.- **📥 Live Model Download Progress**: HuggingFace model downloads now show real-time progress (percentage, speed in MB/s, downloaded/total MB) instead of being stuck at 0%.- **🛡️ MSIX/PyInstaller Frozen Build Fix**: the "Please install transformers extra" crash when torch metadata is missing in packaged builds is now caught and surfaces a clear, actionable message pointing to the Settings tab or llama.cpp provider.- **🔒 Isolated User Data (`user_data/`)**: All configurations, API keys, ChromaDB vectors, Visual indexes, and reports strictly reside under `user_data/`.
---
## ⌨️ Keyboard Shortcuts
| Shortcut | Action ||---|---|| `Alt+Delete` / `Alt+Backspace` | Clear the current conversation / results (asks for confirmation on long conversations) — chat tabs and Data Analysis || `Alt+D` | STT tab: open the Reduce Noise preview (before/after comparison) || `Alt+T` | STT tab: reduce noise + transcribe in one step (report included) || `Alt+Shift+T` | STT tab: focus the noise-reduction strength picker |
---
## App Tabs
| # | Tab | Description ||---|---|---|| 1 | ⚙️ **Settings** | Manage API keys, provider settings, llama-server/whisper-server paths, hardware acceleration, component downloads, and system diagnostics || 2 | 💬 **General Chat** | Direct LLM / ToolCallingAgent conversation with optional live web search — answers saveable to Word || 3 | 📚 **RAG Chat** | Retrieves from the knowledge base first (text + visual page search), then answers — answers saveable to Word || 4 | 🔬 **Deep Research** | Manager agent + web-search sub-agent — breaks down questions, re-plans iteratively, and synthesizes structured reports — saveable to Word || 5 | 🖼️ **Vision Chat** | Image understanding from uploaded images — answers saveable to Word || 6 | 🎙️ **Speech to Text** | Transcribe audio into text using Whisper (including Khmer models) with noise reduction — analyze into Word reports || 7 | 📊 **Data Analysis** | Manager + CodeAgent worker analyzes CSV/Excel, completes missing data, creates charts, and generates Word reports || 8 | 📂 **Knowledge Base** | Upload (PDF / TXT / MD / DOCX), manage documents, organize by themes/subthemes, and index page images || 9 | ℹ️ **About** | Version info, architecture, environment diagnostics, and reports folder management |
---
## Architecture
| Component | Detail ||---|---|| LLM | HuggingFace models (Gemma-4 / Qwen3.6 / GLM-4.7-Flash) **or** local GGUF models via llama.cpp/llama-server **or** HF Inference API / LiteLLM || Vision LLM | SmolVLM / Qwen2.5-VL / Qwen3-VL / GGUF mmproj pairs || Speech-to-Text | Whisper (tiny/base/small/large-v3, Khmer-tuned Whisper models) **or** whisper.cpp server || Embedding | BAAI/bge-m3, Qwen3-Embedding-4B, Jina Embeddings v4, Multilingual-E5 **or** GGUF embedding server || Vector store | ChromaDB (`./user_data/chroma_db/`) — dimension-isolated collections || Visual Index | ColSmolVLM / ColQwen2 (`./user_data/visual_index/`) for scanned pages and charts || Word export | python-docx (`./user_data/reports/<tab>/`) — available on all tabs || 3rd-party tools | Poppler PDF binaries (`./third_party/poppler/`), llama-server, whisper-server || UI | Svelte 5 web UI (Dark Mode & Claude warm terracotta palette) |
---
## 🔒 Security & Privacy Notice
- **🏠 100% Local Processing (Privacy by Design)**: All chat conversations, uploaded documents, images, audio recordings, data analysis, and vector embeddings are processed entirely on your local hardware (GPU/CPU) when using local models. Zero user data, telemetry, or prompts are sent to external servers or third-party cloud providers.- **📂 Isolated User Storage (`user_data/`)**: All your configurations, API keys, ChromaDB vectors, Visual indexes, and exported reports reside exclusively in the `user_data/` directory (or `%LOCALAPPDATA%\\LocalAiLab\\` in store/packaged installations) — strictly separated from application binaries.- **🌐 Optional Remote Endpoints**: When you explicitly choose remote inference providers (HuggingFace Inference API, LiteLLM) or enable web search (DuckDuckGo / Playwright), only the specific queries for those requests are transmitted over secure HTTPS connections. API keys remain stored locally.- **🛡️ Sandboxed Code Execution**: The Data Analysis agent runs Python code for data processing in a secured local sandbox with strict execution timeouts and memory limits, protecting your system.
---
## Expected speed ({device})
| Task | Time ||---|---|| Index a document | 10–60 s || General / RAG answer | 1–30 s || Vision answer | 30 s – 2 min |
> 💡 GGUF (llama.cpp) models are auto-discovered from whatever folder you configure (the "📁 GGUF Model Folder" box, or the `LLAMA_CPP_MODEL_DIR` environment variable) and appear in the same model dropdown as the HuggingFace models."""1.chat{flex:1;min-height:0;display:flex;flex-direction:column}.chat-collapser{flex:0 0 auto;align-self:center;border:1px solid var(--line);background:transparent;color:var(--ink-soft);border-radius:999px;padding:3px 14px;margin:6px auto 4px;font:inherit;font-size:11.5px;font-weight:600;cursor:pointer;transition:border-color .12s ease,color .12s ease}.chat-collapser:hover{border-color:var(--accent);color:var(--accent-ink)}.inputbar{border-top:1px solid var(--line);background:var(--bg-elev);padding:14px 26px 16px}.inputbar-inner{max-width:860px;margin:0 auto}.tool-btn{border:1px solid var(--line);background:transparent;color:var(--ink-soft);border-radius:var(--radius-sm);padding:5px 11px;font-size:12.5px;transition:border-color .12s ease,color .12s ease}.tool-btn:hover{border-color:var(--accent);color:var(--accent-ink)}.model-notice-bar{flex:0 0 auto;display:flex;align-items:center;gap:8px;padding:6px 20px;margin:0 20px 2px;border-radius:var(--radius-sm);background:var(--bg-elev);border:1px solid var(--line);font-size:12.5px;color:var(--ink-soft);overflow:hidden}.model-notice-bar.downloading{border-color:var(--accent);background:color-mix(in srgb,var(--accent) 8%,var(--bg-elev));animation:notice-pulse 1.8s ease-in-out infinite}.model-notice-icon{flex:0 0 auto;font-size:14px;line-height:1}.model-notice-icon.spin{animation:spin 1.2s linear infinite}.model-notice-text{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:500}.model-notice-progress-bar{flex:0 0 80px;height:4px;border-radius:2px;background:var(--line);overflow:hidden}.model-notice-progress-fill{display:block;height:100%;border-radius:2px;background:var(--accent);animation:progress-indeterminate 1.5s ease-in-out infinite}@keyframes notice-pulse{0%,to{opacity:1}50%{opacity:.7}}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes progress-indeterminate{0%{width:0%;margin-left:0%}50%{width:60%;margin-left:20%}to{width:0%;margin-left:100%}}.model-notice-bar.large-warning{border-color:#d97706;background:color-mix(in srgb,#d97706 10%,var(--bg-elev));padding:8px 20px;gap:10px;align-items:flex-start}.model-notice-bar.large-warning .model-notice-icon{font-size:18px;margin-top:1px}.model-notice-body{display:flex;flex-direction:column;gap:2px;min-width:0}.model-notice-title{font-weight:700;font-size:13px;color:#92400e}.model-notice-bar.large-warning .model-notice-text{white-space:normal;font-size:12.5px}.model-notice-hint{font-size:11.5px;color:var(--ink-soft);opacity:.85}:global(html.dark) .model-notice-bar.large-warning{border-color:#f59e0b;background:color-mix(in srgb,#f59e0b 8%,var(--bg-elev))}:global(html.dark) .model-notice-title{color:#fbbf24}.dl-btn{flex:0 0 auto;border:1px solid var(--accent);background:var(--accent);color:#fff;border-radius:var(--radius-sm);padding:4px 12px;font:inherit;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap;transition:opacity .15s ease}.dl-btn:hover{opacity:.85}.dl-btn.busy{background:var(--accent);border-color:var(--accent);cursor:default;animation:notice-pulse 1.8s ease-in-out infinite}.dl-btn.done{background:#16a34a;border-color:#16a34a;cursor:default}.dl-btn.error{background:#dc2626;border-color:#dc2626;cursor:default;max-width:160px;overflow:hidden;text-overflow:ellipsis}.dl-progress{flex:0 0 auto;font-size:11.5px;color:var(--accent-ink);font-weight:500;white-space:nowrap}.model-notice-bar.large-warning{display:flex;align-items:flex-start;gap:10px}.model-notice-bar.large-warning .dl-btn{margin-top:2px}.disk-warn{display:block;font-size:12px;font-weight:600;color:#dc2626;margin-top:2px}.disk-ok{display:block;font-size:11.5px;color:var(--ink-soft);opacity:.75;margin-top:1px}.dl-btn.disk-blocked{background:#9ca3af;border-color:#9ca3af;cursor:not-allowed;opacity:.6}.model-notice-bar[role=status] .model-notice-body{flex:1;min-width:0}.model-notice-bar[role=status] .model-notice-body .model-notice-text{white-space:normal}.kb-notice{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-bottom:10px;padding:6px 12px;border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--bg-soft);font-size:12.5px;color:var(--ink)}.kb-notice span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.kb-link{border:none;background:transparent;color:var(--accent);font-family:inherit;font-size:12.5px;cursor:pointer;padding:2px 4px;white-space:nowrap}.kb-link:hover{text-decoration:underline;color:var(--accent-deep)}.theme-row{display:flex;gap:10px;margin-bottom:10px;flex-wrap:wrap}.data-model-tip{margin:0 0 10px;padding:6px 10px;border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--bg-soft);color:var(--ink-soft);font-size:12px;line-height:1.45}.mini-field{display:flex;align-items:center;gap:8px;border:1px solid var(--line);background:var(--bg-soft);border-radius:var(--radius-sm);padding:4px 10px}.mini-field span{font-size:12px;color:var(--ink-faint);white-space:nowrap}.mini-field input{border:none;outline:none;background:transparent;color:var(--ink);font-family:inherit;font-size:13px;width:130px}.mini-field input::placeholder{color:var(--ink-faint)}.mini-field input[type=number]{width:64px}.mini-field select.mini-select{border:none;outline:none;background:transparent;color:var(--ink);font-family:inherit;font-size:13px;max-width:220px;cursor:pointer}.mini-field select.mini-select option{background:var(--bg-soft, #1e1e1e);color:var(--ink, #eee)}.image-row{display:flex;align-items:center;gap:10px;margin-bottom:10px;flex-wrap:wrap}.rag-files{display:flex;flex-wrap:wrap;gap:6px;margin:-2px 0 10px}.file-chip{max-width:240px}.file-chip-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.chip-x{border:none;outline:none;background:transparent;color:var(--ink-faint);font-size:12px;line-height:1;cursor:pointer;padding:2px;border-radius:4px}.chip-x:hover,.chip-x:focus-visible{color:var(--danger, #b4453a);background:#ffffff14}.upload-chip{cursor:pointer;user-select:none}.upload-chip:hover{border-color:var(--accent);color:var(--accent-ink)}.img-preview{position:relative;display:inline-flex}.img-preview img{height:44px;width:auto;max-width:160px;border-radius:var(--radius-sm);border:1px solid var(--line);object-fit:cover;background:var(--bg-soft)}.img-remove{position:absolute;top:-7px;right:-7px;width:18px;height:18px;border:none;border-radius:50%;background:var(--accent);color:#fff;font-size:12px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 1px 4px #00000040}.img-remove:hover{background:var(--accent-deep)}.file-chip{display:inline-flex;align-items:center;gap:6px;max-width:220px;overflow:hidden;font-size:.8rem;border:1px solid var(--line);border-radius:var(--radius-sm);padding:3px 6px 3px 8px;background:var(--bg-elev);color:var(--ink)}.file-chip .file-remove{border:none;background:transparent;color:var(--ink-faint);cursor:pointer;font-size:.9rem;line-height:1;padding:0 2px}.file-chip .file-remove:hover{color:var(--err)}.data-out-row{align-items:center;gap:8px;flex-wrap:wrap}.data-out-btn{border:1px solid var(--line);background:var(--bg-elev);color:var(--ink);border-radius:999px;padding:4px 12px;font-size:12px;cursor:pointer;white-space:nowrap}.data-out-btn:hover{border-color:var(--accent)}.data-out-path{font-size:11px;color:var(--ink-soft);word-break:break-all;user-select:all}.messages{flex:1;min-height:0;overflow-y:auto;padding:26px 0 12px}.messages-inner{max-width:860px;margin:0 auto;padding:0 26px;display:flex;flex-direction:column;gap:18px}.msg{display:flex;align-items:flex-start;gap:6px}.msg-user{justify-content:flex-end}.user-bubble{background:var(--accent-soft);color:var(--ink);border:1px solid color-mix(in srgb,var(--accent) 30%,var(--line));border-radius:var(--radius) var(--radius) 4px var(--radius);padding:10px 15px;max-width:78%;white-space:pre-wrap;word-break:break-word;box-shadow:var(--shadow-sm);user-select:text}.msg-ai{justify-content:flex-start}.ai-bubble{max-width:100%;min-width:0}.rich{min-width:0;word-break:break-word;user-select:text}.msg-copy-btn{flex:0 0 auto;width:26px;height:26px;margin-top:4px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--ink-faint);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;opacity:.55;transition:opacity .12s ease,color .12s ease,border-color .12s ease,background .12s ease}.msg:hover .msg-copy-btn,.msg-copy-btn:focus-visible{opacity:1}.msg-copy-btn:hover{color:var(--accent-ink);border-color:var(--line);background:var(--bg-elev)}.msg-copy-btn.copied{color:var(--ok);opacity:1}.rich>:first-child{margin-top:0}.rich>:last-child{margin-bottom:0}.msg-ai.live .rich:after{content:"";display:inline-block;width:8px;height:15px;margin-left:3px;vertical-align:-2px;border-radius:2px;background:var(--accent);animation:blink .9s steps(2,start) infinite}@keyframes blink{50%{opacity:0}}.think-pulse{display:inline-flex;align-items:center;gap:8px;color:var(--ink-soft);font-size:13.5px}.think-pulse .dots span{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-right:4px;animation:dotpulse 1.2s ease-in-out infinite}.think-pulse .dots span:nth-child(2){animation-delay:.15s}.think-pulse .dots span:nth-child(3){animation-delay:.3s}@keyframes dotpulse{0%,to{opacity:.3;transform:translateY(0)}50%{opacity:1;transform:translateY(-3px)}}.active-status-card{background:transparent;border:none;border-radius:0;padding:4px 0;box-shadow:none;display:flex;flex-direction:column;gap:6px;min-width:0;max-width:100%;position:relative}.active-status-card:before{display:none}.status-header{display:flex;align-items:center;gap:8px}.status-pulse-dot{width:8px;height:8px;border-radius:50%;background:var(--accent);box-shadow:0 0 #d97757b3;animation:pulse-ring 1.8s cubic-bezier(.4,0,.6,1) infinite;flex-shrink:0}@keyframes pulse-ring{0%{box-shadow:0 0 #d97757b3}70%{box-shadow:0 0 0 8px #d9775700}to{box-shadow:0 0 #d9775700}}.status-title{font-weight:600;font-size:13.5px;color:var(--ink);flex:1}.status-timer{font-size:12px;font-family:var(--font-code);color:var(--ink-faint);background:var(--bg-soft);padding:2px 7px;border-radius:10px;border:1px solid var(--line)}.status-detail{font-size:12.5px;color:var(--ink-soft);line-height:1.4}.status-slow-hint{font-size:12px;line-height:1.35;color:#b45309;background:#fef3c7;border:1px solid #fde68a;border-radius:6px;padding:6px 10px;margin-top:4px}:global([data-theme=dark]) .status-slow-hint{color:#fbbf24;background:#f59e0b26;border-color:#f59e0b4d}.model-dl-progress-card{background:var(--bg-soft, #f8f6f0);border:1px solid var(--line, #e7e0d3);border-left:4px solid var(--accent, #d97757);border-radius:8px;padding:10px 14px;margin-top:6px;display:flex;flex-direction:column;gap:8px}.model-dl-progress-header{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;font-weight:600;color:var(--ink, #3f332b)}.model-dl-progress-track{width:100%;height:8px;background:var(--bg, #ffffff);border-radius:4px;overflow:hidden;border:1px solid var(--line, #e7e0d3);position:relative}.model-dl-progress-fill{height:100%;background:linear-gradient(90deg,var(--accent, #d97757),#e06d44);border-radius:4px;transition:width .3s ease;min-width:6px}.model-dl-progress-fill.indeterminate{width:40%!important;animation:dl-indeterminate 1.5s infinite linear}@keyframes dl-indeterminate{0%{transform:translate(-100%)}to{transform:translate(300%)}}.rich h1,.rich h2,.rich h3{font-family:var(--font-display);line-height:1.3;margin:1.2em 0 .5em}.rich h1{font-size:1.45em}.rich h2{font-size:1.25em}.rich h3{font-size:1.1em}.rich p{margin:.6em 0}.rich ul,.rich ol{margin:.6em 0;padding-left:1.4em}.rich li{margin:.2em 0}.rich a{color:var(--accent-deep);text-decoration:none;border-bottom:1px solid color-mix(in srgb,var(--accent) 40%,transparent);transition:border-color .12s ease}.rich a:hover{border-bottom-color:var(--accent)}.rich code{font-family:var(--font-code);font-size:.9em;background:var(--bg-soft);border:1px solid var(--line);border-radius:5px;padding:1px 5px}.rich pre{background:var(--code-bg);color:var(--code-ink);border:1px solid var(--code-line);border-radius:var(--radius-sm);padding:12px 14px;overflow-x:auto;margin:.8em 0}.rich pre code{background:none;border:none;padding:0;color:inherit;font-size:.86em;line-height:1.5}.rich blockquote{margin:.8em 0;padding:2px 14px;border-left:3px solid var(--accent);color:var(--ink-soft);background:var(--bg-soft);border-radius:0 var(--radius-sm) var(--radius-sm) 0}.rich table{border-collapse:collapse;margin:.8em 0;width:100%;font-size:.92em}.rich th,.rich td{border:1px solid var(--line-strong);padding:6px 10px;text-align:left}.rich th{background:var(--bg-soft);font-weight:600}.rich tr:nth-child(2n) td{background:color-mix(in srgb,var(--bg-soft) 55%,transparent)}.rich hr{border:none;border-top:1px solid var(--line);margin:1.2em 0}.think-block{border:1px solid var(--amber-line);background:var(--amber-bg);border-radius:var(--radius);margin:0 0 10px;overflow:hidden}.think-summary{list-style:none;cursor:pointer;padding:10px 14px;display:flex;align-items:center;gap:8px;user-select:none}.think-summary::-webkit-details-marker{display:none}.think-summary:before{content:"▸";color:var(--amber-ink);transition:transform .15s ease;font-size:12px}.think-block[open] .think-summary:before{transform:rotate(90deg)}.think-badge{font-weight:600;color:var(--amber-ink);font-size:13.5px}.think-hint{color:var(--ink-faint);font-size:11.5px;margin-left:auto}.think-body{padding:2px 16px 12px;color:var(--ink);border-top:1px dashed var(--amber-line)}.final-answer-block{border:none;background:transparent;border-radius:0;overflow:visible;box-shadow:none;margin:0;padding:0}.answer-header-badge{display:none}.answer-body{padding:0}.agent-step-details{border:1px solid var(--line);background:var(--bg-soft);border-radius:var(--radius);margin:0 0 8px;overflow:hidden}.agent-step-summary{list-style:none;cursor:pointer;padding:9px 14px;display:flex;align-items:center;gap:8px;font-size:13.5px;color:var(--ink-soft);user-select:none}.agent-step-summary::-webkit-details-marker{display:none}.agent-step-summary:before{content:"▸";color:var(--accent);font-size:12px;transition:transform .15s ease}.agent-step-details[open] .agent-step-summary:before{transform:rotate(90deg)}.agent-log-block{border-top:1px solid var(--line);padding:10px 14px 12px;font-size:13.5px}.plan-header,.tool-header,.obs-header,.err-header{font-weight:600;font-size:12.5px;margin-bottom:6px;letter-spacing:.2px}.plan-header{color:var(--amber-ink)}.tool-header{color:var(--accent-ink)}.obs-header{color:var(--ink-soft)}.err-header{color:var(--err)}.agent-plan-box{background:var(--amber-bg);border:1px solid var(--amber-line);border-radius:var(--radius-sm);padding:10px 12px;margin-bottom:6px}.agent-thought-box{background:var(--bg-elev);border:1px solid var(--line);border-radius:var(--radius-sm);padding:10px 12px;margin-bottom:6px}.agent-tool-box{background:var(--bg-elev);border:1px solid var(--line);border-left:3px solid var(--accent);border-radius:var(--radius-sm);padding:10px 12px;margin-bottom:6px}.agent-obs-box{background:var(--code-bg);color:var(--code-ink);border-radius:var(--radius-sm);padding:10px 12px;margin-bottom:6px}.agent-err-box{background:color-mix(in srgb,var(--err) 9%,var(--bg-elev));border:1px solid color-mix(in srgb,var(--err) 35%,var(--line));border-radius:var(--radius-sm);padding:10px 12px;color:var(--err);margin-bottom:6px}.obs-code{margin:0;font-family:var(--font-code);font-size:12px;line-height:1.5;white-space:pre-wrap;word-break:break-word;color:inherit;background:none;border:none;padding:0}.abort-badge{display:inline-block;background:color-mix(in srgb,var(--amber-ink) 12%,transparent);color:var(--amber-ink);border:1px solid var(--amber-line);border-radius:999px;padding:4px 12px;font-size:12.5px;font-weight:600;margin:8px 0}.sources-block{border:1px dashed var(--line-strong);background:var(--bg-soft);border-radius:var(--radius-sm);padding:10px 14px;margin:10px 0 6px;font-size:13.5px}.response-footer{margin-top:10px;padding-top:8px;border-top:1px dashed var(--line);color:var(--ink-faint);font-size:11.5px}.empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;color:var(--ink-faint);text-align:center;padding:0 30px}.empty-mark{width:76px;height:76px;border-radius:26px;background:linear-gradient(135deg,var(--accent-soft),var(--bg-soft));border:1px solid var(--line);display:flex;align-items:center;justify-content:center;font-size:34px;box-shadow:var(--shadow-sm)}.empty-title{color:var(--ink-soft);font-size:16px;font-weight:600}.chart-gallery{margin-top:14px;padding:14px;border:1px solid var(--line);border-radius:14px;background:var(--bg-soft)}.chart-gallery-title{font-weight:700;font-size:13.5px;letter-spacing:.2px;color:var(--ink);margin-bottom:12px}.chart-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:14px}.chart-card{margin:0;border:1px solid var(--line);border-radius:12px;overflow:hidden;background:var(--bg-elev);box-shadow:var(--shadow-sm);cursor:zoom-in;transition:transform .15s ease,box-shadow .15s ease,border-color .15s ease}.chart-card:hover{transform:translateY(-2px);box-shadow:0 8px 24px #0000001f;border-color:color-mix(in srgb,var(--accent) 45%,var(--line))}.chart-card img{display:block;width:100%;height:auto;background:#fff}.chart-card figcaption{padding:8px 10px;font-size:11.5px;font-weight:600;color:var(--ink-soft);word-break:break-word;border-top:1px solid var(--line)}.chart-lightbox{position:fixed;inset:0;z-index:200;background:#0a0806c7;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:34px;cursor:zoom-out;animation:lightbox-in .14s ease}@keyframes lightbox-in{0%{opacity:0}to{opacity:1}}.chart-lightbox img{max-width:min(92vw,1280px);max-height:80vh;width:auto;height:auto;border-radius:10px;box-shadow:0 14px 60px #0000008c;background:#fff;cursor:default}.lightbox-caption{color:#ffffffeb;font-size:13.5px;max-width:80vw;text-align:center;word-break:break-word;user-select:text}.lightbox-close{position:absolute;top:18px;right:22px;width:38px;height:38px;border:1px solid rgba(255,255,255,.25);border-radius:50%;background:#ffffff1f;color:#fff;font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .12s ease,transform .08s ease}.lightbox-close:hover{background:#ffffff40;transform:scale(1.06)}.run-lines{margin-top:8px;padding-top:8px;border-top:1px dashed color-mix(in srgb,var(--accent) 35%,var(--line));display:flex;flex-direction:column;gap:3px;max-height:150px;overflow-y:auto}.run-line{font-family:Cascadia Code,Consolas,Courier New,monospace;font-size:11.5px;line-height:1.5;color:var(--ink-soft);white-space:pre-wrap;word-break:break-all;user-select:text}.live-text-block{font-size:14px;line-height:1.45;color:var(--ink);white-space:pre-wrap;word-break:break-word;user-select:text;max-width:760px;background:color-mix(in srgb,var(--accent) 4%,transparent);border-radius:10px;padding:8px 12px;margin:-8px -12px -2px;animation:live-breathe 2.4s ease-in-out infinite}.live-text-block p{margin:.15em 0}.live-text-block>:first-child{margin-top:0}.live-text-block>:last-child{margin-bottom:0}.live-text-block h1,.live-text-block h2,.live-text-block h3,.live-text-block ul,.live-text-block ol,.live-text-block blockquote,.live-text-block pre,.live-text-block table,.live-text-block hr{margin:.25em 0}.live-text-block li{margin:.08em 0}.live-text-block ul,.live-text-block ol{padding-left:1.2em}@keyframes live-breathe{0%,to{box-shadow:0 0 color-mix(in srgb,var(--accent) 0%,transparent)}50%{box-shadow:0 0 14px color-mix(in srgb,var(--accent) 22%,transparent)}}.live-streaming-head{display:flex;align-items:center;gap:8px;margin:2px 0 6px}.live-streaming-label{font-size:12px;font-weight:600;color:var(--accent-ink);letter-spacing:.2px}.composer{display:flex;align-items:flex-end;gap:10px;border:1.5px solid var(--line-strong);background:var(--bg-input);border-radius:var(--radius-lg);padding:10px 12px;transition:border-color .15s ease,box-shadow .15s ease}.composer:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 18%,transparent)}.composer textarea{flex:1;border:none;outline:none;resize:none;background:transparent;color:var(--ink);font-family:inherit;font-size:15px;line-height:1.5;max-height:180px;min-height:24px;padding:4px 2px}.composer textarea::placeholder{color:var(--ink-faint)}.send-btn{border:none;background:linear-gradient(135deg,var(--accent),var(--accent-deep));color:#fff;border-radius:12px;min-width:44px;height:40px;font-size:15px;display:flex;align-items:center;justify-content:center;gap:6px;padding:0 14px;font-weight:600;transition:filter .12s ease,transform .08s ease}.send-btn:hover{filter:brightness(1.06)}.send-btn:active{transform:scale(.97)}.send-btn:disabled{opacity:.45;cursor:not-allowed}.send-btn.stop{background:var(--err)}.send-btn .send-label{font-size:13.5px}.minisel{position:relative;display:inline-flex;align-items:center}.minisel-trigger{display:inline-flex;align-items:center;gap:8px;border:none;outline:none;background:transparent;color:var(--ink);font-family:inherit;font-size:13px;max-width:220px;cursor:pointer;padding:2px 0;text-align:left}.minisel-val{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.minisel-caret{color:var(--ink-faint);font-size:10px;flex:none}.minisel-trigger:hover .minisel-caret,.minisel-trigger:focus-visible .minisel-caret{color:var(--ink)}.minisel-menu{position:absolute;left:0;top:calc(100% + 6px);z-index:1100;min-width:100%;max-width:320px;max-height:220px;overflow-y:auto;margin:0;padding:4px;list-style:none;background:var(--bg-soft, #1f1f1f);border:1px solid var(--line, #333);border-radius:var(--radius-sm, 8px);box-shadow:0 6px 20px #00000059}.minisel-menu.up{top:auto;bottom:calc(100% + 6px)}.minisel-menu li{display:block}.minisel-opt{display:block;width:100%;border:none;outline:none;background:transparent;color:var(--ink, #eee);font-family:inherit;font-size:13px;text-align:left;cursor:pointer;padding:6px 10px;border-radius:6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.minisel-opt:hover,.minisel-opt:focus-visible,.minisel-opt[aria-selected=true]{background:var(--bg-hover, rgba(255, 255, 255, .08))}.minisel-check{display:inline-block;width:14px;margin-right:4px;color:var(--accent, #d97757);font-weight:700;visibility:hidden}.minisel-opt.checked .minisel-check{visibility:visible}.minisel-create{border-top:1px solid var(--line, #333);margin-top:4px;padding-top:4px}.minisel-create-input{display:block;width:100%;box-sizing:border-box;border:1px solid var(--line, #333);outline:none;background:var(--bg-soft, #1f1f1f);color:var(--ink, #eee);font-family:inherit;font-size:13px;border-radius:6px;padding:6px 10px}.minisel-create-input:focus{border-color:var(--accent, #d97757)}.card-sub.svelte-1x22jrg{font-size:.85rem;font-weight:700;color:var(--text-strong, #3f332b);margin:12px 0 8px}.llm-model-notice.svelte-1x22jrg{margin:10px 0 2px;font-size:12.5px;line-height:1.5;color:var(--text-mid, #6b5f52)}.llm-model-notice.svelte-1x22jrg p{margin:0}.recorder-row.svelte-1x22jrg{display:flex;align-items:center;gap:10px;margin:10px 0 4px;flex-wrap:wrap}.rec-timer.svelte-1x22jrg{font-variant-numeric:tabular-nums;font-weight:600;color:var(--text-strong, #3f332b)}.audio-box.svelte-1x22jrg{margin:8px 0}.audio-box.svelte-1x22jrg audio:where(.svelte-1x22jrg){width:100%;height:40px}.trim-row.svelte-1x22jrg{display:flex;align-items:flex-end;gap:10px;margin:10px 0;flex-wrap:wrap}.trim-wave.svelte-1x22jrg{margin-top:4px}.trim-label.svelte-1x22jrg{font-size:.85rem;font-weight:600;align-self:center;color:var(--text-strong, #3f332b)}.field-sm.svelte-1x22jrg{min-width:110px}.trim-row.svelte-1x22jrg input[type=range]:where(.svelte-1x22jrg){width:100%;background:transparent;border:none;border-radius:0;padding:0;box-shadow:none;accent-color:var(--accent, #2f7d5a)}.field-grow.svelte-1x22jrg{flex:1;min-width:180px}.preview-box.svelte-1x22jrg{margin:12px 0;padding:12px;border:1px solid var(--line, rgba(128, 120, 110, .25));border-radius:14px;background:var(--bg-elev, #ffffff)}.preview-head.svelte-1x22jrg{display:flex;align-items:baseline;justify-content:space-between;gap:10px;margin-bottom:10px;flex-wrap:wrap}.preview-title.svelte-1x22jrg{font-weight:700;color:var(--text-strong, #3f332b)}.preview-name.svelte-1x22jrg{font-size:.8rem;color:var(--text-soft, #8a7a68);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.preview-grid.svelte-1x22jrg{display:grid;grid-template-columns:1fr 1fr;gap:10px}.preview-col.svelte-1x22jrg{min-width:0}.preview-label.svelte-1x22jrg{font-size:.78rem;font-weight:600;margin-bottom:4px;color:var(--text-soft, #8a7a68)}.wave-canvas.svelte-1x22jrg{width:100%;height:64px;border-radius:8px;background:var(--bg-soft, rgba(0, 0, 0, .04))}.preview-play.svelte-1x22jrg{margin-top:12px}.preview-play-label.svelte-1x22jrg{display:block;font-size:.78rem;font-weight:600;margin-bottom:4px;color:var(--text-soft, #8a7a68)}.preview-play.svelte-1x22jrg audio:where(.svelte-1x22jrg){width:100%;height:40px}.preview-actions.svelte-1x22jrg{display:flex;gap:10px;margin-top:12px;flex-wrap:wrap}.live-transcript.svelte-1x22jrg{margin:8px 0;padding:10px 14px;border:1px solid var(--accent, #2f7d5a);border-radius:12px;background:var(--bg-elev, #f8f6f3);animation:svelte-1x22jrg-live-pulse 1.5s ease-in-out infinite}.live-dot.svelte-1x22jrg{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent, #2f7d5a);margin-right:6px;animation:svelte-1x22jrg-live-blink 1s ease-in-out infinite}.live-label.svelte-1x22jrg{font-size:.8rem;font-weight:700;color:var(--accent, #2f7d5a);vertical-align:middle}.live-text.svelte-1x22jrg{margin-top:6px;font-size:.95rem;line-height:1.5;color:var(--text-strong, #3f332b);white-space:pre-wrap;word-break:break-word}@keyframes svelte-1x22jrg-live-blink{0%,to{opacity:1}50%{opacity:.3}}@keyframes svelte-1x22jrg-live-pulse{0%,to{border-color:var(--accent, #2f7d5a)}50%{border-color:color-mix(in srgb,var(--accent, #2f7d5a) 40%,transparent)}}.llcpp-overlay{position:fixed;inset:0;z-index:10010;background:#00000073;display:flex;align-items:center;justify-content:center;padding:16px}.llcpp-box{background:var(--bg-elev, #ffffff);border:1px solid var(--card-border, #e7e0d3);border-left:5px solid var(--primary-600, #d97757);border-radius:var(--radius, 14px);padding:22px 24px;max-width:520px;width:100%;box-shadow:0 16px 48px #0000004d;animation:llcpp-pop .22s ease-out}@keyframes llcpp-pop{0%{opacity:0;transform:scale(.94)}to{opacity:1;transform:scale(1)}}.llcpp-title{font-family:var(--font-display, Georgia, "Times New Roman", serif);font-size:1.15rem;font-weight:700;color:var(--text-strong, #000000);margin-bottom:12px}.llcpp-detect{color:var(--text-strong, #000000);font-size:.85rem;line-height:1.6;padding:10px 12px;background:var(--amber-bg, #fbf0dc);border:1px solid var(--amber-line, #eed9b0);border-radius:var(--radius-sm, 8px);margin-bottom:12px}.llcpp-pick{color:var(--text-strong, #000000);font-size:.9rem;font-weight:600;margin-bottom:10px}.llcpp-opts{display:flex;flex-direction:column;gap:8px;margin-bottom:18px;max-height:260px;overflow-y:auto}.llcpp-loading,.llcpp-err{color:var(--text-dim, #4a4a4a);padding:8px 0 16px}.llcpp-err{color:var(--danger, #b4453a)}.llcpp-opt{display:flex;align-items:flex-start;gap:10px;padding:9px 11px;border:1px solid var(--card-border, #e7e0d3);border-radius:var(--radius-sm, 8px);cursor:pointer;transition:border-color .15s ease,background .15s ease}.llcpp-opt:hover{border-color:var(--primary-600, #d97757)}.llcpp-opt.sel{border-color:var(--primary-600, #d97757);background:color-mix(in srgb,var(--primary-600, #d97757) 8%,transparent)}.llcpp-opt.unavail{opacity:.55;cursor:not-allowed}.llcpp-opt input[type=radio]{margin-top:3px;accent-color:var(--primary-600, #d97757)}.llcpp-opt-main{display:flex;flex-direction:column;gap:3px}.llcpp-opt-label{font-size:.9rem;font-weight:600;color:var(--text-strong, #000000)}.llcpp-rec{margin-left:6px;font-size:.75rem;font-weight:700;color:var(--primary-700, #b05a36)}.llcpp-na{margin-left:6px;font-size:.75rem;font-weight:600;color:var(--text-dim, #4a4a4a)}.llcpp-opt-reason{font-size:.8rem;line-height:1.45;color:var(--text-dim, #4a4a4a)}.llcpp-actions{display:flex;justify-content:flex-end;gap:10px}.llcpp-cancel{border:1px solid var(--card-border, #e7e0d3);background:transparent;color:var(--text-strong, #000000);border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.llcpp-cancel:hover{filter:brightness(1.05)}.llcpp-ok{border:1px solid var(--primary-600, #d97757);background:var(--primary-600, #d97757);color:#fff;border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.llcpp-ok:hover{filter:brightness(1.05)}.llcpp-drag-handle{cursor:grab;user-select:none}.llcpp-drag-handle:active,.llcpp-box.dragging .llcpp-drag-handle{cursor:grabbing}.llsrv-overlay{position:fixed;inset:0;z-index:10010;background:#00000073;display:flex;align-items:center;justify-content:center;padding:16px}.llsrv-box{background:var(--bg-elev, #ffffff);border:1px solid var(--card-border, #e7e0d3);border-left:5px solid var(--primary-600, #d97757);border-radius:var(--radius, 14px);padding:22px 24px;max-width:520px;width:100%;box-shadow:0 16px 48px #0000004d;animation:llsrv-pop .22s ease-out}@keyframes llsrv-pop{0%{opacity:0;transform:scale(.94)}to{opacity:1;transform:scale(1)}}.llsrv-title{font-family:var(--font-display, Georgia, "Times New Roman", serif);font-size:1.15rem;font-weight:700;color:var(--text-strong, #000000);margin-bottom:12px}.llsrv-detect{color:var(--text-strong, #000000);font-size:.85rem;line-height:1.6;padding:10px 12px;background:var(--amber-bg, #fbf0dc);border:1px solid var(--amber-line, #eed9b0);border-radius:var(--radius-sm, 8px);margin-bottom:12px}.llsrv-pick{color:var(--text-strong, #000000);font-size:.9rem;font-weight:600;margin-bottom:10px}.llsrv-opts{display:flex;flex-direction:column;gap:8px;margin-bottom:18px;max-height:260px;overflow-y:auto}.llsrv-loading,.llsrv-err{color:var(--text-dim, #4a4a4a);padding:8px 0 16px}.llsrv-err{color:var(--danger, #b4453a)}.llsrv-opt{display:flex;align-items:flex-start;gap:10px;padding:9px 11px;border:1px solid var(--card-border, #e7e0d3);border-radius:var(--radius-sm, 8px);cursor:pointer;transition:border-color .15s ease,background .15s ease}.llsrv-opt:hover{border-color:var(--primary-600, #d97757)}.llsrv-opt.sel{border-color:var(--primary-600, #d97757);background:color-mix(in srgb,var(--primary-600, #d97757) 8%,transparent)}.llsrv-opt.unavail{opacity:.55;cursor:not-allowed}.llsrv-opt input[type=radio]{margin-top:3px;accent-color:var(--primary-600, #d97757)}.llsrv-opt-main{display:flex;flex-direction:column;gap:3px}.llsrv-opt-label{font-size:.9rem;font-weight:600;color:var(--text-strong, #000000)}.llsrv-rec{margin-left:6px;font-size:.75rem;font-weight:700;color:var(--primary-700, #b05a36)}.llsrv-na{margin-left:6px;font-size:.75rem;font-weight:600;color:var(--text-dim, #4a4a4a)}.llsrv-opt-reason{font-size:.8rem;line-height:1.45;color:var(--text-dim, #4a4a4a)}.llsrv-actions{display:flex;justify-content:flex-end;gap:10px}.llsrv-cancel{border:1px solid var(--card-border, #e7e0d3);background:transparent;color:var(--text-strong, #000000);border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.llsrv-cancel:hover{filter:brightness(1.05)}.llsrv-ok{border:1px solid var(--primary-600, #d97757);background:var(--primary-600, #d97757);color:#fff;border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.llsrv-ok:hover{filter:brightness(1.05)}.llsrv-drag-handle{cursor:grab;user-select:none}.llsrv-drag-handle:active,.llsrv-box.dragging .llsrv-drag-handle{cursor:grabbing}.wsrv-overlay{position:fixed;inset:0;z-index:10010;background:#00000073;display:flex;align-items:center;justify-content:center;padding:16px}.wsrv-box{background:var(--bg-elev, #ffffff);border:1px solid var(--card-border, #e7e0d3);border-left:5px solid var(--primary-600, #d97757);border-radius:var(--radius, 14px);padding:22px 24px;max-width:520px;width:100%;box-shadow:0 16px 48px #0000004d;animation:wsrv-pop .22s ease-out}@keyframes wsrv-pop{0%{opacity:0;transform:scale(.94)}to{opacity:1;transform:scale(1)}}.wsrv-title{font-family:var(--font-display, Georgia, "Times New Roman", serif);font-size:1.15rem;font-weight:700;color:var(--text-strong, #000000);margin-bottom:12px}.wsrv-detect{color:var(--text-strong, #000000);font-size:.85rem;line-height:1.6;padding:10px 12px;background:var(--amber-bg, #fbf0dc);border:1px solid var(--amber-line, #eed9b0);border-radius:var(--radius-sm, 8px);margin-bottom:12px}.wsrv-pick{color:var(--text-strong, #000000);font-size:.9rem;font-weight:600;margin-bottom:10px}.wsrv-opts{display:flex;flex-direction:column;gap:8px;margin-bottom:18px;max-height:260px;overflow-y:auto}.wsrv-loading,.wsrv-err{color:var(--text-dim, #4a4a4a);padding:8px 0 16px}.wsrv-err{color:var(--danger, #b4453a)}.wsrv-opt{display:flex;align-items:flex-start;gap:10px;padding:9px 11px;border:1px solid var(--card-border, #e7e0d3);border-radius:var(--radius-sm, 8px);cursor:pointer;transition:border-color .15s ease,background .15s ease}.wsrv-opt:hover{border-color:var(--primary-600, #d97757)}.wsrv-opt.sel{border-color:var(--primary-600, #d97757);background:color-mix(in srgb,var(--primary-600, #d97757) 8%,transparent)}.wsrv-opt.unavail{opacity:.55;cursor:not-allowed}.wsrv-opt input[type=radio]{margin-top:3px;accent-color:var(--primary-600, #d97757)}.wsrv-opt-main{display:flex;flex-direction:column;gap:3px}.wsrv-opt-label{font-size:.9rem;font-weight:600;color:var(--text-strong, #000000)}.wsrv-rec{margin-left:6px;font-size:.75rem;font-weight:700;color:var(--primary-700, #b05a36)}.wsrv-na{margin-left:6px;font-size:.75rem;font-weight:600;color:var(--text-dim, #4a4a4a)}.wsrv-opt-reason{font-size:.8rem;line-height:1.45;color:var(--text-dim, #4a4a4a)}.wsrv-actions{display:flex;justify-content:flex-end;gap:10px}.wsrv-cancel{border:1px solid var(--card-border, #e7e0d3);background:transparent;color:var(--text-strong, #000000);border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.wsrv-cancel:hover{filter:brightness(1.05)}.wsrv-ok{border:1px solid var(--primary-600, #d97757);background:var(--primary-600, #d97757);color:#fff;border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.wsrv-ok:hover{filter:brightness(1.05)}.wsrv-drag-handle{cursor:grab;user-select:none}.wsrv-drag-handle:active,.wsrv-box.dragging .wsrv-drag-handle{cursor:grabbing}.ptch-overlay{position:fixed;inset:0;z-index:10010;background:#00000073;display:flex;align-items:center;justify-content:center;padding:16px}.ptch-box{background:var(--bg-elev, #ffffff);border:1px solid var(--card-border, #e7e0d3);border-left:5px solid var(--primary-600, #d97757);border-radius:var(--radius, 14px);padding:22px 24px;max-width:520px;width:100%;box-shadow:0 16px 48px #0000004d;animation:ptch-pop .22s ease-out}@keyframes ptch-pop{0%{opacity:0;transform:scale(.94)}to{opacity:1;transform:scale(1)}}.ptch-title{font-family:var(--font-display, Georgia, "Times New Roman", serif);font-size:1.15rem;font-weight:700;color:var(--text-strong, #000000);margin-bottom:12px}.ptch-detect{color:var(--text-strong, #000000);font-size:.85rem;line-height:1.6;padding:10px 12px;background:var(--amber-bg, #fbf0dc);border:1px solid var(--amber-line, #eed9b0);border-radius:var(--radius-sm, 8px);margin-bottom:12px}.ptch-pick{color:var(--text-strong, #000000);font-size:.9rem;font-weight:600;margin-bottom:10px}.ptch-opts{display:flex;flex-direction:column;gap:8px;margin-bottom:18px;max-height:260px;overflow-y:auto}.ptch-loading,.ptch-err{color:var(--text-dim, #4a4a4a);padding:8px 0 16px}.ptch-err{color:var(--danger, #b4453a)}.ptch-opt{display:flex;align-items:flex-start;gap:10px;padding:9px 11px;border:1px solid var(--card-border, #e7e0d3);border-radius:var(--radius-sm, 8px);cursor:pointer;transition:border-color .15s ease,background .15s ease}.ptch-opt:hover{border-color:var(--primary-600, #d97757)}.ptch-opt.sel{border-color:var(--primary-600, #d97757);background:color-mix(in srgb,var(--primary-600, #d97757) 8%,transparent)}.ptch-opt.unavail{opacity:.55;cursor:not-allowed}.ptch-opt input[type=radio]{margin-top:3px;accent-color:var(--primary-600, #d97757)}.ptch-opt-main{display:flex;flex-direction:column;gap:3px}.ptch-opt-label{font-size:.9rem;font-weight:600;color:var(--text-strong, #000000)}.ptch-rec{margin-left:6px;font-size:.75rem;font-weight:700;color:var(--primary-700, #b05a36)}.ptch-na{margin-left:6px;font-size:.75rem;font-weight:600;color:var(--text-dim, #4a4a4a)}.ptch-opt-reason{font-size:.8rem;line-height:1.45;color:var(--text-dim, #4a4a4a)}.ptch-actions{display:flex;justify-content:flex-end;gap:10px}.ptch-cancel{border:1px solid var(--card-border, #e7e0d3);background:transparent;color:var(--text-strong, #000000);border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.ptch-cancel:hover{filter:brightness(1.05)}.ptch-ok{border:1px solid var(--primary-600, #d97757);background:var(--primary-600, #d97757);color:#fff;border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}.ptch-ok:hover{filter:brightness(1.05)}.ptch-drag-handle{cursor:grab;user-select:none}.ptch-drag-handle:active,.ptch-box.dragging .ptch-drag-handle{cursor:grabbing}.dlcfm-overlay{position:fixed;inset:0;z-index:10010;background:#00000073;display:flex;align-items:center;justify-content:center;padding:16px}.dlcfm-box{background:var(--bg-elev, #ffffff);border:1px solid var(--card-border, #e7e0d3);border-left:5px solid var(--primary-600, #d97757);border-radius:var(--radius, 14px);padding:22px 24px;max-width:440px;width:100%;box-shadow:0 12px 32px #0000002e;position:relative}.dlcfm-title{font-size:1.08em;font-weight:700;margin-bottom:12px;color:var(--text-strong, #3f332b)}.dlcfm-body{font-size:.92em;line-height:1.55;color:var(--text, #5a5248);margin-bottom:18px}.dlcfm-body b{color:var(--text-strong, #3f332b)}.dlcfm-actions{display:flex;gap:10px;justify-content:flex-end}.dlcfm-cancel,.dlcfm-confirm{padding:7px 18px;border-radius:var(--radius, 10px);font-size:.9em;font-weight:600;cursor:pointer;border:1px solid var(--card-border, #e7e0d3);transition:background .15s,opacity .15s;user-select:auto}.dlcfm-drag-handle{cursor:grab;user-select:none}.dlcfm-drag-handle:active,.dlcfm-box.dragging .dlcfm-drag-handle{cursor:grabbing}.dlcfm-cancel{background:var(--bg-elev, #f5f0e8);color:var(--text, #5a5248)}.dlcfm-cancel:hover{background:var(--card-bg, #ede8de)}.dlcfm-confirm{background:var(--primary-600, #d97757);color:#fff;border-color:var(--primary-600, #d97757)}.dlcfm-confirm:hover{background:var(--primary-700, #c2633f)}.feedback-container{display:flex;flex-direction:column;gap:14px;max-width:900px;margin:0 auto;width:100%}.feedback-target-chip{display:inline-flex;align-items:center;gap:8px;padding:8px 14px;background:var(--surface-2, rgba(230, 220, 205, .4));border:1px solid var(--border-soft, #dfd7cb);border-radius:20px;font-weight:600;font-size:.9rem;color:var(--text-strong, #3f332b);align-self:flex-start}.feedback-target-email{color:var(--accent, #2f7d5a);font-family:monospace;letter-spacing:.02em}.feedback-type-group{display:flex;flex-wrap:wrap;gap:8px;margin-top:4px}.feedback-type-btn{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;font-size:.85rem;font-weight:500;border-radius:8px;border:1px solid var(--card-border, #e7e0d3);background:var(--card-bg, #fffdf9);color:var(--text-main, #333);cursor:pointer;transition:all .15s ease-in-out}.feedback-type-btn:hover{background:var(--surface-2, rgba(230, 220, 205, .4));border-color:var(--accent, #2f7d5a)}.feedback-type-btn.active{background:var(--accent, #2f7d5a);color:#fff;border-color:var(--accent, #2f7d5a);box-shadow:0 1px 3px #2f7d5a4d}.feedback-textarea{width:100%;min-height:140px;padding:10px 12px;font-family:inherit;font-size:.9rem;line-height:1.5;border:1px solid var(--card-border, #e7e0d3);border-radius:8px;background:var(--input-bg, #fff);color:var(--text-main, #333);resize:vertical;box-sizing:border-box}.feedback-textarea:focus,.feedback-input:focus{outline:none;border-color:var(--accent, #2f7d5a);box-shadow:0 0 0 2px #2f7d5a26}.feedback-input{width:100%;padding:8px 12px;font-family:inherit;font-size:.9rem;border:1px solid var(--card-border, #e7e0d3);border-radius:8px;background:var(--input-bg, #fff);color:var(--text-main, #333);box-sizing:border-box}.feedback-diag-box{background:var(--surface-2, rgba(230, 220, 205, .3));border:1px solid var(--border-soft, #dfd7cb);border-radius:8px;padding:10px 14px}.feedback-diag-box summary{cursor:pointer;font-weight:600;font-size:.85rem;color:var(--text-dim, #555)}.feedback-diag-pre{margin-top:8px;padding:10px;background:var(--code-bg, #2b2b2b);color:var(--code-text, #f0f0f0);border-radius:6px;font-family:monospace;font-size:.8rem;white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto}.feedback-contact-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}.feedback-contact-card{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;background:var(--surface-2, rgba(230, 220, 205, .25));border:1px solid var(--border-soft, #dfd7cb);border-radius:10px;text-decoration:none;color:inherit;transition:background .15s ease-in-out}.feedback-contact-card:hover{background:var(--surface-2, rgba(230, 220, 205, .5))}.feedback-contact-info{display:flex;flex-direction:column;gap:2px}.feedback-contact-label{font-size:.75rem;color:var(--text-dim, #666);font-weight:600;text-transform:uppercase}.feedback-contact-val{font-size:.88rem;font-weight:600;color:var(--text-strong, #222)}.dl-popup-overlay.svelte-flxoo7{position:fixed;bottom:24px;right:24px;z-index:2000;pointer-events:none}.dl-popup-box.svelte-flxoo7{pointer-events:auto;min-width:320px;max-width:440px;user-select:none;padding:16px 18px;border-radius:14px;background:var(--card-bg, #f5f0e8);border:1px solid var(--primary-300, #f0b49e);box-shadow:0 8px 32px #0000002e,0 2px 8px #e08a6a26;animation:svelte-flxoo7-dl-slide-in .3s ease-out}@keyframes svelte-flxoo7-dl-slide-in{0%{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}.dl-popup-header.svelte-flxoo7{display:flex;align-items:center;gap:8px;margin-bottom:8px}.dl-popup-icon.svelte-flxoo7{font-size:1.2rem}.dl-popup-title.svelte-flxoo7{font-size:.85rem;font-weight:700;color:var(--text-strong, #3f332b)}.dl-popup-model.svelte-flxoo7{font-size:.8rem;color:var(--text-muted, #8a7e72);margin-bottom:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-popup-track.svelte-flxoo7{height:8px;background:var(--card-border, #e7e0d3);border-radius:4px;overflow:hidden;margin-bottom:8px}.dl-popup-fill.svelte-flxoo7{height:100%;background:linear-gradient(90deg,var(--primary-500, #e08a6a),var(--primary-600, #d97757));border-radius:4px;transition:width .3s ease}.dl-popup-stats.svelte-flxoo7{display:flex;align-items:center;gap:8px;font-size:.78rem}.dl-popup-pct.svelte-flxoo7{font-weight:700;color:var(--primary-600, #d97757)}.dl-popup-mb.svelte-flxoo7{color:var(--text-strong, #222);font-weight:600}.dl-popup-speed.svelte-flxoo7{color:var(--primary-600, #d97757);font-weight:600}.dl-popup-status.svelte-flxoo7{font-size:.75rem;color:var(--text-muted, #888);margin-top:4px}.dl-popup-complete.svelte-flxoo7{font-size:.82rem;font-weight:600;color:#2d8a4e;padding:4px 0}.dl-popup-error.svelte-flxoo7{font-size:.82rem;font-weight:600;color:#b4453a;padding:4px 0}.dl-popup-drag-handle.svelte-flxoo7{cursor:grab}.dl-popup-drag-handle.svelte-flxoo7:active{cursor:grabbing}.dl-popup-cancel.svelte-flxoo7{margin-left:auto;user-select:auto;padding:4px 12px;border-radius:8px;border:1px solid var(--primary-300, #f0b49e);background:var(--primary-500, #e08a6a);color:#fff;font-size:.75rem;font-weight:700;cursor:pointer;transition:background .2s ease,transform .1s ease}.dl-popup-cancel.svelte-flxoo7:hover{background:var(--primary-600, #d97757)}.dl-popup-cancel.svelte-flxoo7:active{transform:scale(.96)}.dl-popup-box.dragging.svelte-flxoo7 .dl-popup-header:where(.svelte-flxoo7){cursor:grabbing}.dl-popup-cancelled.svelte-flxoo7{font-size:.82rem;font-weight:600;color:#8a6d3b;padding:4px 0}.lal-tooltip{position:fixed;z-index:1000;max-width:340px;padding:7px 12px;border-radius:8px;background:#2c241b;color:#f6eee1;border:1px solid #4a3b2b;border-top:2px solid var(--accent, #d97757);box-shadow:0 10px 26px #2c241b59,0 2px 6px #2c241b2e;font-size:12.5px;line-height:1.5;pointer-events:none;opacity:0;transform:translateY(4px) scale(.97);transition:opacity .12s ease,transform .12s ease;word-break:break-word}.lal-tooltip.open{opacity:1;transform:translateY(0) scale(1)}.lal-tooltip:after{content:"";position:absolute;left:var(--ax, 50%);width:9px;height:9px;margin-left:-4.5px;background:#2c241b;transform:rotate(45deg)}.lal-tooltip.above:after{bottom:-5px;border-right:1px solid #4a3b2b;border-bottom:1px solid #4a3b2b}.lal-tooltip.below:after{top:-5px;border-left:1px solid #4a3b2b;border-top:1px solid #4a3b2b}html.dark .lal-tooltip{background:#f4ead9;color:#2c241b;border-color:#d9c9ae;border-top-color:var(--accent, #e8936c);box-shadow:0 12px 30px #00000080,0 2px 8px #00000059}html.dark .lal-tooltip:after{background:#f4ead9}html.dark .lal-tooltip.above:after{border-right-color:#d9c9ae;border-bottom-color:#d9c9ae}html.dark .lal-tooltip.below:after{border-left-color:#d9c9ae;border-top-color:#d9c9ae}.firstrun-overlay{position:fixed;inset:0;z-index:10000;background:#00000073;display:flex;align-items:center;justify-content:center;padding:16px}.firstrun-box{background:var(--bg-elev, #ffffff);border:1px solid var(--card-border, #e7e0d3);border-left:5px solid var(--primary-600, #d97757);border-radius:var(--radius, 14px);padding:22px 24px;max-width:480px;width:100%;box-shadow:0 16px 48px #0000004d;animation:firstrun-pop .22s ease-out}@keyframes firstrun-pop{0%{opacity:0;transform:scale(.94)}to{opacity:1;transform:scale(1)}}.firstrun-title{font-family:var(--font-display, Georgia, "Times New Roman", serif);font-size:1.15rem;font-weight:700;color:var(--text-strong, #000000);margin-bottom:14px}.firstrun-lines{display:flex;flex-direction:column;gap:10px;margin-bottom:20px}.firstrun-line{color:var(--text-strong, #000000);font-size:.9rem;line-height:1.55}.firstrun-tip{color:var(--text-dim, #4a4a4a);padding:10px 12px;background:var(--amber-bg, #fbf0dc);border:1px solid var(--amber-line, #eed9b0);border-radius:var(--radius-sm, 8px)}.firstrun-actions{display:flex;justify-content:flex-end}.firstrun-ok{border:1px solid var(--primary-600, #d97757);background:var(--primary-600, #d97757);color:#fff;border-radius:10px;padding:9px 18px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease;user-select:auto}.firstrun-ok:hover{filter:brightness(1.05)}.firstrun-drag-handle{cursor:grab;user-select:none}.firstrun-drag-handle:active,.firstrun-box.dragging .firstrun-drag-handle{cursor:grabbing}:root{--bg: #faf9f5;--bg-elev: #ffffff;--bg-soft: #f3efe6;--bg-sidebar: #efeae0;--bg-input: #ffffff;--ink: #000000;--ink-soft: #4a4a4a;--ink-faint: #6f6f6f;--line: #e4dcd0;--line-strong: #d6ccbc;--accent: #d97757;--accent-deep: #c25e3f;--accent-soft: #f7e6dd;--accent-ink: #8a4427;--amber-bg: #fbf0dc;--amber-line: #eed9b0;--amber-ink: #8a5b1d;--ok: #4e7a57;--err: #b4453a;--code-bg: #2d261f;--code-ink: #f3e9dc;--code-line: #45392c;--shadow-sm: 0 1px 2px rgba(58, 47, 39, .06);--shadow-md: 0 10px 28px rgba(58, 47, 39, .12);--radius-sm: 8px;--radius: 14px;--radius-lg: 20px;--font-ui: "Segoe UI Variable Text", "Segoe UI", "Leelawadee UI", "Khmer OS Battambang", system-ui, -apple-system, sans-serif;--font-display: Georgia, "Times New Roman", serif;--font-code: "Cascadia Code", Consolas, "Courier New", monospace;--sidebar-w: 236px;--sidebar-w-collapsed: 68px;--header-h: 62px;--text-strong: #000000;--text-dim: #4a4a4a}html.dark{--bg: #1d1814;--bg-elev: #26201a;--bg-soft: #221c17;--bg-sidebar: #16120f;--bg-input: #2a231c;--ink: #ffffff;--ink-soft: #ffffff;--ink-faint: #ffffff;--line: #362e25;--line-strong: #46392d;--accent: #e8936c;--accent-deep: #f0a88a;--accent-soft: #3a2720;--accent-ink: #ffffff;--amber-bg: #33291b;--amber-line: #4a3c26;--amber-ink: #ffffff;--ok: #7faf88;--err: #e07a6e;--code-bg: #120e0b;--code-ink: #ffffff;--code-line: #2c251d;--shadow-sm: 0 1px 2px rgba(0, 0, 0, .25);--shadow-md: 0 10px 28px rgba(0, 0, 0, .35);--text-strong: #ffffff;--text-dim: #ffffff;--primary-500: #e8936c;--primary-600: #e8936c;--primary-700: #ffffff;--card-bg: #26201a;--card-border: #3d362c;--input-bg: #221e19;--console-bg: #1e1a15;--btn-bg: #383129}*{box-sizing:border-box}html,body{height:100%}body{margin:0;font-family:var(--font-ui);background:var(--bg);color:var(--ink);font-size:15px;line-height:1.55;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;overflow:hidden}button,select{font-family:inherit;cursor:pointer}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-thumb{background:var(--line-strong);border-radius:8px;border:2px solid transparent;background-clip:content-box}::-webkit-scrollbar-thumb:hover{background:var(--ink-faint);background-clip:content-box}::-webkit-scrollbar-track{background:transparent}.shell{display:flex;height:100vh}.sidebar{width:var(--sidebar-w);flex:0 0 var(--sidebar-w);background:var(--bg-sidebar);border-right:1px solid var(--line);display:flex;flex-direction:column;padding:18px 12px 14px;overflow:hidden;transition:width .18s ease,flex-basis .18s ease}.shell.collapsed .sidebar{width:var(--sidebar-w-collapsed);flex-basis:var(--sidebar-w-collapsed)}.shell.collapsed .sidebar .brand{justify-content:center;padding-inline:0}.shell.collapsed .sidebar .brand>div:last-child,.shell.collapsed .sidebar .tab-lb,.shell.collapsed .sidebar .sidebar-foot span:not(.offline-dot),.shell.collapsed .sidebar .sidebar-foot .yt-link{display:none}.shell.collapsed .sidebar .sidebar-stats .mem-chip{display:none}.shell.collapsed .sidebar .sidebar-stats{padding-inline:4px;align-items:center}.shell.collapsed .sidebar .sidebar-stats .vram-btn{padding:6px 8px}.shell.collapsed .sidebar .sidebar-stats .vram-btn-label{display:none}.shell.collapsed .sidebar .tab-btn,.shell.collapsed .sidebar .sidebar-foot{justify-content:center;padding-inline:0}.brand{display:flex;align-items:center;gap:10px;padding:2px 8px 16px;border-bottom:1px solid var(--line);margin-bottom:14px}.brand-mark{width:38px;height:38px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-deep));display:flex;align-items:center;justify-content:center;box-shadow:var(--shadow-sm);flex:0 0 auto;overflow:hidden}.brand-logo{width:100%;height:100%;display:block;object-fit:cover;border-radius:50%}.brand-name{font-family:var(--font-display);font-weight:700;font-size:17px;letter-spacing:.2px;line-height:1.15}.brand-title-row{display:flex;align-items:baseline;min-width:0}.brand-ver{margin-left:8px;padding:1px 7px;border:1px solid var(--line);border-radius:999px;background:var(--bg-soft);color:var(--ink-faint);font-family:var(--font-ui);font-size:10.5px;font-weight:600;letter-spacing:.1px;line-height:1.4;white-space:nowrap;min-width:0;overflow:hidden;text-overflow:ellipsis}.tabs{display:flex;flex-direction:column;gap:2px;overflow-y:auto;flex:1;min-height:0}.tab-btn{display:flex;align-items:center;gap:10px;width:100%;border:none;background:transparent;color:var(--ink-soft);text-align:left;padding:9px 10px;border-radius:var(--radius-sm);font-size:14px;transition:background .12s ease,color .12s ease}.tab-btn:hover{background:var(--bg-elev);color:var(--ink)}.tab-btn.active{background:var(--bg-elev);color:var(--ink);font-weight:600;box-shadow:var(--shadow-sm);position:relative}.tab-btn.active:before{content:"";position:absolute;left:-12px;top:8px;bottom:8px;width:3px;border-radius:0 3px 3px 0;background:var(--accent)}.tab-ic{font-size:16px;width:20px;text-align:center;flex:0 0 auto}.tab-lb{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.sidebar-foot{border-top:1px solid var(--line);padding:12px 8px 2px;font-size:11.5px;color:var(--ink-faint);display:flex;align-items:center;gap:6px}.offline-dot{width:7px;height:7px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px color-mix(in srgb,var(--ok) 18%,transparent)}.sidebar-foot .yt-link{display:inline-flex;align-items:center;gap:6px;color:var(--accent-ink);background:color-mix(in srgb,var(--accent) 12%,var(--bg-elev));border:1px solid color-mix(in srgb,var(--accent) 38%,var(--line));border-radius:999px;padding:4px 11px;font-size:12px;font-weight:600;text-decoration:none;line-height:1.2;min-width:0;max-width:190px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:background .12s ease,border-color .12s ease,color .12s ease}.sidebar-foot .yt-ic{font-size:11px;flex:0 0 auto}.sidebar-foot .yt-txt{overflow:hidden;text-overflow:ellipsis}.sidebar-foot .yt-link:hover{background:color-mix(in srgb,var(--accent) 20%,var(--bg-elev));border-color:var(--accent);color:var(--accent-ink)}.main{flex:1;min-width:0;display:flex;flex-direction:column}.header{position:relative;height:var(--header-h);flex:0 0 var(--header-h);border-bottom:1px solid var(--line);background:color-mix(in srgb,var(--bg-elev) 70%,transparent);backdrop-filter:blur(8px);display:flex;align-items:center;gap:10px;padding:0 18px}.header-title{font-family:var(--font-display);font-size:15px;font-weight:700;color:var(--ink);margin-right:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.header-actions{display:flex;align-items:center;gap:8px}.icon-btn{border:1px solid var(--line);background:var(--bg-elev);color:var(--ink-soft);border-radius:var(--radius-sm);width:34px;height:34px;font-size:15px;display:flex;align-items:center;justify-content:center;transition:border-color .12s ease,color .12s ease,background .12s ease}.icon-btn:hover{border-color:var(--accent);color:var(--accent-ink)}.icon-btn:disabled{opacity:.5;cursor:default;border-color:var(--line);color:var(--ink-soft)}.pill-select{appearance:none;border:1px solid var(--line);background:var(--bg-elev) url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%239c8c7c' stroke-width='1.6' fill='none' stroke-linecap='round'/%3E%3C/svg%3E") no-repeat right 10px center;color:var(--ink);border-radius:var(--radius-sm);padding:6px 26px 6px 10px;font-size:13px;max-width:210px;transition:border-color .12s ease}.pill-select:hover{border-color:var(--accent)}.model-status-chip{border:1px solid var(--accent-soft);background:var(--accent-soft);color:var(--accent-ink);border-radius:999px;padding:5px 12px;font-size:12px;font-weight:600;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:help;transition:border-color .12s ease,background .12s ease}.model-status-chip:hover{border-color:var(--accent)}.dark .model-status-chip{border-color:var(--accent-soft);background:color-mix(in srgb,var(--accent-soft) 45%,transparent)}.model-dl-badge{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--accent);background:var(--accent-soft);color:var(--accent-ink);border-radius:999px;padding:4px 12px;font-size:12px;font-weight:600;white-space:nowrap;animation:dl-pulse-border 1.5s infinite alternate}.model-dl-badge.done{border-color:#2e7d32;background:#2e7d321f;color:#2e7d32;animation:none}.model-dl-badge.error{border-color:#c62828;background:#c628281f;color:#c62828;animation:none}@keyframes dl-pulse-border{0%{border-color:var(--accent-soft)}to{border-color:var(--accent)}}.embed-active-info{display:inline-flex;align-items:center;gap:4px;font-size:12px;color:var(--text-muted);padding:4px 0}.embed-active-info strong{color:var(--text-strong);font-weight:600}.dark .rich a,.dark .upload-name{color:#fff}.vram-btn{display:inline-flex;align-items:center;gap:6px;border:1px solid color-mix(in srgb,var(--err) 38%,var(--line));background:color-mix(in srgb,var(--err) 9%,var(--bg-elev));color:var(--err);border-radius:999px;padding:5px 12px;font-size:12px;font-weight:600;white-space:nowrap;transition:border-color .12s ease,background .12s ease}.vram-btn:hover:not(:disabled){border-color:var(--err);background:color-mix(in srgb,var(--err) 15%,var(--bg-elev))}.vram-btn:disabled{opacity:.55;cursor:not-allowed}.sidebar-stats{display:flex;flex-direction:column;gap:6px;padding:10px 8px 12px;border-top:1px solid var(--line);margin-top:auto;position:relative}.mem-chip{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--bg-soft);color:var(--ink-soft);border-radius:999px;padding:5px 12px;font-size:12px;font-variant-numeric:tabular-nums;white-space:nowrap;user-select:text;cursor:help;transition:border-color .12s ease,color .12s ease}.mem-chip:hover{border-color:var(--accent);color:var(--accent-ink)}.sidebar-stats .mem-chip{display:flex;justify-content:space-between;gap:8px;width:100%}.mem-chip-label{font-weight:600;flex:0 0 auto}.sidebar-stats .mem-chip-val{min-width:0;overflow:hidden;text-overflow:ellipsis}.sidebar-stats .vram-btn{width:100%;justify-content:center;text-align:center;padding:6px 12px}.seg{display:inline-flex;border:1px solid var(--line);border-radius:var(--radius-sm);overflow:hidden;background:var(--bg-elev)}.seg button{border:none;background:transparent;color:var(--ink-soft);padding:6px 12px;font-size:13px;transition:background .12s ease,color .12s ease}.seg button.active{background:var(--accent-soft);color:var(--ink);font-weight:600}.dark .seg button.active{color:#fff}.busy-dot{width:9px;height:9px;border-radius:50%;background:var(--accent);animation:pulse 1s ease-in-out infinite}@keyframes pulse{0%,to{opacity:.35;transform:scale(.85)}50%{opacity:1;transform:scale(1.1)}}.content{flex:1;min-height:0;display:flex;flex-direction:column}.chip-row{display:flex;align-items:center;gap:8px;margin-bottom:10px;flex-wrap:wrap}.chip{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--bg-soft);color:var(--ink-soft);border-radius:999px;padding:4px 12px;font-size:12.5px;user-select:none;cursor:pointer;transition:border-color .12s ease,color .12s ease,background .12s ease}.chip.on{background:var(--accent-soft);border-color:color-mix(in srgb,var(--accent) 45%,var(--line));color:var(--accent-ink);font-weight:600}.chip input{display:none}.tool-row{display:flex;gap:8px;margin-top:10px;align-items:center}.save-group{display:flex;flex-direction:column;align-items:flex-start;gap:4px}.save-notice{font-size:.78rem;line-height:1.35;color:var(--ok, #4e7a57);max-width:340px;word-break:break-word}.save-notice.err{color:var(--err, #b4453a)}.tool-flash{margin-left:auto;font-size:12.5px;color:var(--ok)}.tool-flash.err{color:var(--err)}.settings-toast{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:9999;max-width:min(560px,calc(100vw - 48px));padding:16px 22px;border-radius:var(--radius, 14px);background:var(--bg-elev, #ffffff);border:1px solid var(--card-border, #e7e0d3);border-left:5px solid var(--ok, #4e7a57);box-shadow:0 16px 48px #00000047;color:var(--text-strong, #000000);font-size:.9rem;font-weight:600;line-height:1.5;text-align:center;word-break:break-word;animation:toast-pop .22s ease-out}@keyframes toast-pop{0%{opacity:0;transform:translate(-50%,-50%) scale(.92)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}.settings-toast.err{border-left-color:color-mix(in srgb,var(--err, #b4453a) 60%,var(--line, #e7e0d3));color:var(--err, #b4453a)}@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}}.tab-scroll{display:flex;flex-direction:column;gap:14px;height:100%;overflow-y:auto;padding:4px 2px 24px}.card{background:var(--card-bg, #fffdf9);border:1px solid var(--card-border, #e7e0d3);border-radius:14px;padding:16px 18px;display:flex;flex-direction:column;gap:12px;box-shadow:0 1px 2px #5f4a360d}.card-title{font-size:.95rem;font-weight:700;color:var(--text-strong, #3f332b);letter-spacing:.01em}.card-subtitle{font-size:.85rem;font-weight:700;color:var(--text-dim, #4a4a4a);letter-spacing:.01em;margin-top:2px}.field-row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end}.gen-settings{margin-top:10px;border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--bg-soft)}.gen-settings summary{cursor:pointer;list-style:none;padding:8px 12px;font-size:12.5px;color:var(--ink-soft);user-select:none;display:flex;align-items:center;gap:6px}.gen-settings summary::-webkit-details-marker{display:none}.gen-settings summary:before{content:"▸";font-size:11px;transition:transform .15s ease;color:var(--ink-faint)}.gen-settings[open] summary:before{transform:rotate(90deg)}.gen-settings summary:hover{color:var(--accent-ink)}.gen-settings-body{padding:10px 12px 12px;border-top:1px solid var(--line)}.gen-settings-body>:last-child{margin-bottom:0}.field-row-inline{flex-wrap:nowrap;gap:6px}.field-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px}.provider-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px;align-items:start}.provider-block{border:1px solid var(--card-border, #e7e0d3);border-radius:12px;background:var(--bg-soft, #faf6ee);padding:12px 14px;display:flex;flex-direction:column;gap:10px}.provider-title{font-size:.82rem;font-weight:700;color:var(--text-strong, #3f332b);border-bottom:1px dashed var(--card-border, #e7e0d3);padding-bottom:6px}.provider-fields{display:flex;flex-direction:column;gap:10px}.field{display:flex;flex-direction:column;gap:5px;flex:1;min-width:150px}.field-num{flex:0 1 120px}.select-wide{flex:2;min-width:200px}.field-label{font-size:.78rem;font-weight:600;color:var(--text-dim, #8a7a63)}.field input,.field select,.field textarea,.select-wide{width:100%;box-sizing:border-box;background:var(--input-bg, #fdfbf6);border:1px solid var(--card-border, #e7e0d3);border-radius:9px;padding:8px 10px;font:inherit;color:var(--text-strong, #3f332b);outline:none;transition:border-color .15s ease,box-shadow .15s ease}.field input:focus,.field select:focus,.field textarea:focus,.select-wide:focus{border-color:var(--primary-500, #d97757);box-shadow:0 0 0 3px color-mix(in srgb,var(--primary-500, #d97757) 15%,transparent)}.upload-area{display:flex;align-items:center;justify-content:center;gap:8px;padding:18px 12px;border:1.5px dashed var(--card-border, #e7e0d3);border-radius:12px;cursor:pointer;color:var(--text-dim, #8a7a63);font-size:.9rem;transition:border-color .15s ease,background .15s ease;text-align:center}.upload-area:hover{border-color:var(--primary-500, #d97757);background:#d977570f}.upload-name{color:var(--primary-600, #c96a49);font-weight:600}.btn{border:1px solid var(--card-border, #e7e0d3);background:var(--btn-bg, #f7f2e9);color:var(--text-strong, #3f332b);border-radius:10px;padding:8px 14px;font:inherit;font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease,transform .05s ease,box-shadow .15s ease}.btn:hover:not(:disabled){filter:brightness(.97);box-shadow:0 1px 4px #5f4a3626}.btn:active:not(:disabled){transform:translateY(1px)}.btn:disabled{opacity:.45;cursor:not-allowed}.btn-primary{background:var(--primary-600, #d97757);border-color:var(--primary-600, #d97757);color:#fff}.btn-primary:hover:not(:disabled){filter:brightness(1.05)}.btn-danger{background:#b4453a;border-color:#b4453a;color:#fff}.btn-sm{padding:6px 11px;font-size:.8rem}.console{margin:0;padding:12px;background:var(--console-bg, #f6f1e6);border:1px solid var(--card-border, #e7e0d3);border-radius:10px;font-family:Cascadia Mono,Consolas,monospace;font-size:.78rem;line-height:1.55;color:var(--text-strong, #3f332b);white-space:pre-wrap;word-break:break-word;max-height:260px;overflow-y:auto}.console.log{max-height:220px;color:#9db48b}.status-line{padding:8px 12px;border-radius:10px;background:#d977571a;color:var(--primary-700, #a5533a);font-size:.85rem;font-weight:600}.status-line.err{background:#c25e4a1f;color:var(--err)}.dl-progress{margin-top:8px;padding:10px 12px;border-radius:10px;background:var(--card-bg, #f5f0e8);border:1px solid var(--card-border, #e7e0d3)}.dl-progress-header{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:6px;gap:8px}.provider-subtabs{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px}.subtab-btn{padding:6px 12px;border-radius:8px;border:1px solid var(--card-border, #e7e0d3);background:var(--card-bg, #f5f0e8);color:var(--text-soft, #555);font-size:.8rem;font-weight:600;cursor:pointer;transition:all .15s ease;display:inline-flex;align-items:center;gap:5px}.subtab-btn:hover{background:var(--hover-bg, #ece5d8);color:var(--text-strong, #222)}.subtab-btn.active{background:var(--primary-500, #e08a6a);color:#fff;border-color:var(--primary-600, #d97757);box-shadow:0 1px 4px #d9775740}.model-mgmt-box{background:var(--console-bg, #f6f1e6);border:1px solid var(--card-border, #e7e0d3);border-radius:10px;padding:14px;display:flex;flex-direction:column;gap:12px}.model-meta-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.model-status-chip{display:inline-flex;align-items:center;gap:4px;font-size:.76rem;font-weight:600;padding:3px 8px;border-radius:6px;background:var(--card-bg, #f5f0e8);border:1px solid var(--card-border, #e7e0d3);color:var(--text-strong, #333)}.model-status-chip.ready{background:#26a65b1f;border-color:#26a65b4d;color:#27ae60}.model-status-chip.download{background:#e67e221f;border-color:#e67e224d;color:#d35400}.model-status-chip.cloud{background:#3498db1f;border-color:#3498db4d;color:#2980b9}.model-details-text{font-family:var(--font-mono, monospace);font-size:.75rem;color:var(--text-muted, #777);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.model-table{width:100%;border-collapse:collapse;font-size:.83rem}.model-table th,.model-table td{padding:10px 12px;text-align:left;border-bottom:1px solid var(--card-border, #e7e0d3);vertical-align:middle}.model-table th{background:var(--card-bg, #f5f0e8);font-weight:700;color:var(--text-dim, #8a7a63);font-size:.76rem;text-transform:uppercase;letter-spacing:.03em}.model-table tr:hover td{background:var(--hover-bg, rgba(236, 229, 216, .4))}.model-name-cell{display:flex;flex-direction:column;gap:2px}.model-name-title{font-weight:600;color:var(--text-strong, #333)}.model-name-id{font-family:var(--font-mono, monospace);font-size:.72rem;color:var(--text-muted, #888)}.action-btn-group{display:inline-flex;align-items:center;gap:6px}.model-dl-card{margin-top:12px;padding:12px 14px;border-radius:10px;background:var(--card-bg, #f5f0e8);border:1px solid var(--primary-300, #f0b49e);box-shadow:0 2px 8px #e08a6a1f}.dl-progress-meta{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:6px;font-size:.75rem;color:var(--text-soft, #555)}.dl-progress-meta .dl-size{font-weight:600;color:var(--text-strong, #222)}.dl-progress-meta .dl-speed{color:var(--primary-600, #d97757);font-weight:600}.dl-progress-meta .dl-status{color:var(--text-muted, #888);margin-left:auto}.dl-progress-label{font-size:.82rem;font-weight:600;color:var(--text-strong, #3f332b);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-progress-pct{font-size:.85rem;font-weight:700;color:var(--primary-600, #d97757);white-space:nowrap}.dl-progress-track{height:8px;background:var(--card-border, #e7e0d3);border-radius:4px;overflow:hidden}.dl-progress-bar{height:100%;background:linear-gradient(90deg,var(--primary-500, #e08a6a),var(--primary-600, #d97757));border-radius:4px;transition:width .3s ease}.dl-progress-size{margin-top:4px;font-size:.75rem;color:var(--text-muted, #8a7e72);text-align:right}.kb-log{margin-top:8px;padding:8px 12px;border-radius:10px;background:#3c3c5014;border:1px solid rgba(120,120,150,.18);max-height:240px;overflow:auto;font-family:var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);font-size:.78rem;line-height:1.45;color:var(--text-soft, #555);white-space:pre-wrap;word-break:break-word}.kb-log-line{padding:1px 0}.table-wrap{overflow-x:auto;border:1px solid var(--card-border, #e7e0d3);border-radius:10px}.doc-table{width:100%;border-collapse:collapse;font-size:.82rem}.doc-table th,.doc-table td{padding:8px 10px;text-align:left;border-bottom:1px solid var(--card-border, #e7e0d3);white-space:nowrap}.doc-table th{background:var(--console-bg, #f6f1e6);font-weight:700;color:var(--text-dim, #8a7a63);font-size:.75rem;text-transform:uppercase;letter-spacing:.04em}.doc-table tbody tr{cursor:pointer;transition:background .12s ease}.doc-table tbody tr:hover{background:#d977570f}.doc-table tbody tr.sel{background:#d9775729;box-shadow:inset 3px 0 0 var(--primary-500, #d97757)}.vis-cell{display:inline-flex;align-items:center;gap:8px;min-width:0}.vis-strip{display:inline-flex;flex-wrap:wrap;align-items:center;gap:4px;max-width:220px}.vis-thumb{width:40px;height:40px;object-fit:cover;border-radius:6px;border:1px solid var(--card-border, #e7e0d3);background:var(--card-bg, #fff);flex:none;cursor:zoom-in}.vis-thumb:hover{border-color:var(--primary-500, #d97757)}.chart-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px}.chart-item{width:100%;border:1px solid var(--card-border, #e7e0d3);border-radius:10px;background:var(--card-bg, #fff)}.report-box summary{cursor:pointer;font-weight:600;color:var(--primary-700, #a5533a);margin-bottom:8px}.report-box .rich.live:after{content:"";display:inline-block;width:8px;height:15px;margin-left:3px;vertical-align:-2px;border-radius:2px;background:var(--accent);animation:blink .9s steps(2,start) infinite}.report-preview{padding:14px;border:1px solid var(--card-border, #e7e0d3);border-radius:10px;background:var(--console-bg, #f6f1e6)}.reports-path{font-size:.8rem;color:var(--text-dim, #8a7a63);font-family:Cascadia Mono,Consolas,monospace;word-break:break-all}.empty-hint{color:var(--text-dim, #8a7a63);font-size:.85rem;padding:10px 0}.about-box .rich h1,.about-box .rich h2,.about-box .rich h3{color:var(--primary-700, #a5533a)}.tool-row.wrap{flex-wrap:wrap}123456789101112131415<!doctype html><html lang="kh"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="color-scheme" content="light dark" /> <title>LocalAiLab Assistant</title> <link rel="icon" type="image/png" href="./favicon.png" /> <script type="module" crossorigin src="./assets/index-CcfSqwDm.js"></script> <link rel="stylesheet" crossorigin href="./assets/index-CaFw1y7V.css"> </head> <body> <div id="app"></div> </body></html>.dockerignoreAdded+29
.gitattributes+2
DockerfileAdded+39
README.md+14-21
agents/__init__.pyAdded+1
agents/agent_factory.pyAdded+391
agents/agent_memory.pyAdded+661
agents/agent_streaming.pyAdded
agents/data_analysis.pyAdded
agents/deep_research_agent.pyAdded+807
agents/general_agent.pyAdded+896
agents/playwright_search_tool.pyAdded+1189
agents/rag_agent.pyAdded+823
app.pyAdded+76
backend/__init__.pyAdded+1
backend/audio_denoise.pyAdded+148
backend/chat.pyAdded+1512
backend/component_downloader.pyAdded+891
backend/docx_export.pyAdded+293
backend/gguf_models.csvAdded+39
backend/hardware.pyAdded+1794
backend/hf_api_models.csvAdded+128
backend/hf_models.csvAdded+32
backend/index_docs.pyAdded+94
backend/knowledge_base.pyAdded
backend/live_stream.pyAdded+109
backend/llama_backend.pyAdded
backend/llama_health.pyAdded+356
backend/local_server.pyAdded+184
backend/metadata_hardening.pyAdded+176
backend/model_registry.pyAdded
backend/models.pyAdded
backend/paths.pyAdded+91
backend/report_tools.pyAdded+490
backend/stdio_hardening.pyAdded+231
backend/torchaudio_health.pyAdded+193
backend/user_config.pyAdded+70
backend/web_api.pyAdded
backend/whisper_cpp_backend.pyAdded+261
requirements.txtAdded+41
ui/__init__.pyAdded+1
ui/branding.pyAdded+229
ui/i18n.pyAdded
ui/image/logo.icoAdded
Large File Pointer Details
- SHA256: 3f7c0e1e309e40b6bef543591290042f813094d0ead99e1dd4d1f960d2963787
- Pointer size: 131 Bytes
- Size of remote file: 141 kB
ui/image/logo.jpgAdded

Large File Pointer Details
- SHA256: fb78ba93320cca8130056fb19b588fcef9562fc237e999076c5aea193eab20fb
- Pointer size: 131 Bytes
- Size of remote file: 114 kB
ui/image/logo_round.pngAdded

ui/web/dist/assets/index-CaFw1y7V.cssAdded+1
ui/web/dist/assets/index-CcfSqwDm.jsAdded
ui/web/dist/favicon.pngAdded
ui/web/dist/index.htmlAdded+15