diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..9ae675596558d9a724e971f60e3f60a02ad75c64 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,29 @@ +.git +.venv +.venv-build +__pycache__ +*.pyc +*.pyo +*.pyd +.pytest_cache +.vscode +.vs +.idea +*.log +installer +tools +tests +Output +user_data/gguf_models +user_data/chroma_db +user_data/visual_index +user_data/msix_certificate +user_data/tutorial_* +user_data/exports +user_data/reports +user_data/old_files +user_data/my_hf/build_stage +third_party +*.exe +*.msix +*.iss diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..23b522764435b67e90bbb3ef388213dc7d9e5c42 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +ui/image/logo.ico filter=lfs diff=lfs merge=lfs -text +ui/image/logo.jpg filter=lfs diff=lfs merge=lfs -text diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8dc9f6fd801fa4070005783aeb46ba7d37ad0aa8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +FROM python:3.11-slim + +# Install system dependencies +RUN 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 user +USER user +ENV 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 requirements +COPY --chown=user:user requirements.txt $HOME/app/requirements.txt +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements.txt + +# Copy application source code +COPY --chown=user:user . $HOME/app + +# Ensure user_data directory is writable +RUN 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"] diff --git a/README.md b/README.md index ecad40767fb13f0e86a6dee7ecb3fe86f1e1c2f0..34925c8abcc8dd5958c87db681b45cdecf34c4a9 100644 --- a/README.md +++ b/README.md @@ -3,32 +3,25 @@ title: LocalAiLab Assistant emoji: 🤖 colorFrom: indigo colorTo: blue -sdk: static +sdk: docker +app_port: 7860 pinned: false license: mit -short_description: Khmer & English AI Assistant powered by LocalAiLab -tags: - - khmer - - ai-assistant - - svelte - - smolagents +short_description: Khmer & English AI Assistant powered by smolagents & Svelte --- # 🤖 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. +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 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. - ---- +## ✨ 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 -### 🌐 Direct Anonymous Access -You can access this application directly with zero platform chrome: -👉 **[https://localailb-assistant.hf.space](https://localailb-assistant.hf.space)** +## 🚀 Running on Hugging Face Spaces +This space is running as a custom Docker container with FastAPI serving the Svelte frontend on port `7860`. diff --git a/agents/__init__.py b/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ec7dea8d6c891ab2c98c95e03d3285f36c167c0 --- /dev/null +++ b/agents/__init__.py @@ -0,0 +1 @@ +# agents package diff --git a/agents/agent_factory.py b/agents/agent_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..5211aaa32dfc8f529c75d735845b2ae0057f0216 --- /dev/null +++ b/agents/agent_factory.py @@ -0,0 +1,391 @@ +""" +agent_factory.py — Shared smolagents agent-construction helpers. + +Every agentic tab in the app (General Chat, RAG Chat, Deep Research, Data +Analysis) builds its smolagents agent(s) with the same version-compat +dance: + + 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 ONE +place instead of four — see also AGENTS.md's "the app must always launch, +on any environment, and degrade gracefully" guidance. +""" + +import importlib.resources +import inspect +import re +from 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 before +accepting it and feeds a rejection back to the model for one more +attempt, so this guards answer quality at the source for every agentic +tab. 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("" 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) diff --git a/agents/agent_memory.py b/agents/agent_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..97d5168316ca42650f4a244bfa4551cf6c15578d --- /dev/null +++ b/agents/agent_memory.py @@ -0,0 +1,661 @@ +""" +agent_memory.py — Shared multi-turn memory helpers for every smolagents +CodeAgent 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 plain +Python list of TaskStep / ActionStep / PlanningStep objects. Two rules +from 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 used +to also serialize `agent.memory.steps` to JSON on disk so memory would +survive an app restart, not just a model swap within the same run — that +was NEVER part of smolagents' own memory model (smolagents doesn't ship +save/load for `agent.memory` at all — see the still-open +https://github.com/huggingface/smolagents/issues/1216), and hand-rolling +it 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's +gone the moment the model is switched, "Clear" is clicked, or the app +restarts — 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 correctly +and 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 of +throwing the oldest turns away when the conversation grows, it FIRST +measures the agent memory's token footprint against the model's context +window, and — only when it's about to overflow — asks the model itself to +condense the older turns into a short rolling summary that is prepended +to the system prompt (the most recent turns stay verbatim). This is the +"true" compaction approach (approach #4 in the standard context-window +playbook, with the token-usage trigger of #3), and it deliberately keeps +the exact same RAM-only lifecycle as everything else here: the summary +lives on the agent object (`agent._rolling_summary`), dies with it, and +is cleared by reset_memory() together with the steps. On any failure it +degrades to dropping the oldest turns — the old behaviour — so the chat +loop 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 False diff --git a/agents/agent_streaming.py b/agents/agent_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..fb326a099ffb5c2b3612fd3da0545ee5c040bc85 --- /dev/null +++ b/agents/agent_streaming.py @@ -0,0 +1,3288 @@ +""" +agent_streaming.py — Shared live step-streaming for every smolagents +CodeAgent-driven chat handler in this app (General Chat / RAG Chat / +Deep Research / Data Analysis — see chat.py / data_analysis.py). + +smolagents' own streamed UI (see smolagents' `gradio_ui.py` / +`stream_to_gradio()`) streams each ActionStep/PlanningStep live by +calling `agent.run(task, stream=True, ...)` and iterating the returned +generator, rather than blocking silently until the whole run finishes — +the LAST item that generator yields is the plain final answer itself +(not wrapped in a step object). This module adapts that exact pattern to +this app's own chat history shape (plain {"role", "content"} dicts +served over the web UI), so every agentic tab here +(chat.py's chat_general_agentic / chat_rag / chat_deep_research, and +data_analysis.py's run_data_analysis()) can show live progress instead +of a single frozen "thinking…" bubble for however long a multi-step run +takes. + +Public contract +---------------- +stream_agent_steps(agent, task, reset=True) is a generator yielding +(step_msg, is_final, final_output, diagnostics) 4-tuples: + + - While the run is still in progress: `step_msg` is a plain + {"role": "assistant", "content": "..."} dict describing the step + that just happened (or None if that particular step produced + nothing worth showing), `is_final` is False, `final_output` is + None, and `diagnostics` is None. Callers append step_msg to their + chat history and yield. + + - On the LAST item: `step_msg` is None, `is_final` is True, + `final_output` holds the agent's actual final answer (whatever a + plain, non-streaming `agent.run()` call would have returned), and + `diagnostics` is a SNAPSHOT dict {total_steps, + max_consecutive_errors, aborted, last_error, loop_detected, + loop_call} of that run's failure diagnostics (see the fail-fast + section below) — callers use this as the "real" + result to post-process (citations, formatting, etc.) instead of + trying to parse it back out of the step stream, and read their + failure hint straight from `diagnostics` (no get_last_run() call + needed after the loop). + +Every call site in this app follows the same loop shape: + + result = None + for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory): + if not is_final: + if step_msg is not None: + history.append(step_msg) + yield history, ... + continue + result = final_output + # diag now holds this run's diagnostics snapshot + +Version compatibility +---------------------- +Different smolagents releases expose live streaming slightly +differently. This module tries, in order: + + 1. `agent.run(task, reset=reset, stream=True)` — the standard way to + get a live generator of memory steps as they happen. Each yielded + item is either a memory-step object (ActionStep / PlanningStep / + ...) or, on the very last item, the final answer itself. + 2. If `stream=True` isn't accepted at all (raises TypeError — an + older smolagents without streaming support), falls back to a + single non-streaming `agent.run(task, reset=reset)` call and + yields just ONE (None, True, result, diagnostics) tuple — no live + steps, but the app still works exactly as it did before streaming + existed. + +Because the exact memory-step shape/attributes can also vary by +version, step formatting below is defensive: every attribute is read +with getattr(..., default) inside a try/except, so a field this +installed version doesn't have (or a totally unrecognized step type) +degrades to a shorter message — or is silently skipped — instead of +crashing the whole run. +""" + +import ast +import html +import json +import re +import threading +import traceback +from typing import Optional + +from ui import i18n + +# Best-effort import of smolagents' own memory-step classes, for a +# precise isinstance() check. Falls back to matching on the class NAME +# string (see _is_memory_step()) if this smolagents version has moved +# or renamed these — the same defensive fallback pattern general_agent.py +# / rag_agent.py already use for other smolagents version differences +# (e.g. the `code_block_tags` / `instructions` kwarg probing). +try: + from smolagents.memory import ActionStep, PlanningStep, TaskStep, SystemPromptStep + _MEMORY_STEP_TYPES = (ActionStep, PlanningStep, TaskStep, SystemPromptStep) +except ImportError: + _MEMORY_STEP_TYPES = () + +_MEMORY_STEP_CLASS_NAMES = ( + "ActionStep", "PlanningStep", "TaskStep", "SystemPromptStep", "FinalAnswerStep", +) + +# DeepSeek's native code fence: '<|DSML|python>…'. The +# '|' is the full-width vertical bar U+FF5C (DeepSeek chat/reasoner models +# emit this instead of the ASCII ```python fence), but ASCII '|' variants +# appear in the wild too, so both are tolerated — and the ASCII closing tag +# typically carries a LEADING pipe too ('|'), so an optional +# pipe before the closing '" + r"(.*?)" + r"\s*[\uFF5C|]?\s*", + re.DOTALL | re.IGNORECASE, +) + +# ── ReAct envelope recovery ──────────────────────────────────────────── +# llama.cpp's Gemma chat template renders smolagents tool calls as the +# classic ReAct envelope: +# +# Action: +# { +# "name": "final_answer", +# "arguments": { "answer": "..." } +# } +# +# The primary smolagents JSON parser handles CLEAN envelopes fine, but +# small local GGUFs frequently write UNESCAPED quotes inside the answer +# text (or unquoted JSON keys), which makes json.loads throw — and the +# smart fallback previously wrapped the WHOLE raw envelope into the final +# answer as plain text (the "Action: {…} JSON leak"). These helpers +# recover the real tool call from a malformed envelope instead. + + +def _tool_call_dict(name: str, arguments) -> dict: + """Normalize a recovered tool call into the shape smolagents expects.""" + return { + "name": name, + "arguments": arguments, + "action": name, + "action_input": arguments, + } + + +# ── Small-model schema-echo recovery ─────────────────────────────────── +# A small GGUF model sometimes echoes a tool's JSON-Schema declaration back +# as the VALUE of an argument instead of the actual value — e.g. +# +# web_search(query={'type': 'string', 'description': 'What is the +# capital of France?'}) +# +# where the description field carries what the model actually wanted to +# search for. Without recovery the tool receives a dict where a string is +# expected and the step hard-fails with an argument-type error, burning a +# whole slow generation (and, repeated, tripping the fail-fast abort). The +# helpers below unwrap schema-shaped values back into the real value the +# model meant. + + +def _looks_like_schema(value) -> bool: + """True when `value` is a dict that reads as a JSON-Schema declaration + (a 'type' key plus schema-ish metadata). Ordinary dict arguments + (retrieved chunks, API params, query results…) never match.""" + return ( + isinstance(value, dict) + and isinstance(value.get("type"), str) + and any(key in value for key in ("description", "title", "default", "properties")) + ) + + +def _unwrap_schema_value(value): + """Recover the intended value from a schema-shaped value. Small models + put the REAL content into the schema's description (the observed + shape), so description wins; a title is the next best string hint; + a default is an actual value too (any JSON type) but only as a LAST + resort — a schema echo with an empty default (e.g. DraftCodexSkillTool's + `skill_name` carries `"default": ""`) must never swallow the real + content sitting in the description. Non-schema values pass through + unchanged.""" + if not _looks_like_schema(value): + return value + for key in ("description", "title"): + v = value.get(key) + if isinstance(v, str) and v.strip(): + return v + v = value.get("default") + if v is not None: + return v + return value + + +def _normalize_schema_echo(arguments) -> dict: + """Undo a small model echoing a tool's JSON Schema as its arguments. + + Two shapes are handled: + 1. Whole-schema arguments — the ENTIRE arguments dict is a schema + object ({type: 'object', properties: {...}}); rebuild the real + arguments by unwrapping each property. + 2. Per-value schema echo — one argument's VALUE is a schema dict + (web_search(query={'type': 'string', 'description': '…'})). + + Anything not schema-shaped passes through untouched.""" + if not isinstance(arguments, dict): + return arguments + props = arguments.get("properties") + if ( + arguments.get("type") == "object" + and isinstance(props, dict) + and any(_looks_like_schema(v) for v in props.values()) + ): + return { + k: (_unwrap_schema_value(v) if isinstance(v, dict) else v) + for k, v in props.items() + } + out = dict(arguments) + for key in out: + out[key] = _unwrap_schema_value(out[key]) + return out + + +def _match_braces(text: str, start: int) -> Optional[str]: + """Return the balanced {...} block starting at text[start] (must be + '{'), or None if the block is unterminated (truncated model output).""" + depth = 0 + i = start + while i < len(text): + ch = text[i] + if ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + return text[start:i + 1] + i += 1 + return None + + +def _recover_answer_from_args(args_blob: str) -> Optional[dict]: + """Last-resort extraction of the 'answer' string from a malformed + arguments object. Tolerates unescaped inner quotes by taking everything + up to the LAST quote in the fragment — the corrupted inner quotes all + come BEFORE the real closing quote of the answer string.""" + m = re.search(r'''["']?answer["']?\s*:\s*["']''', args_blob) + if not m: + return None + tail = args_blob[m.end():] + close = tail.rfind('"') + if close == -1: + close = tail.rfind("'") + if close == -1: + return None + return {"answer": tail[:close].strip()} + + +def _parse_react_envelope(text: str) -> Optional[dict]: + """Best-effort recovery of a ReAct 'Action:' tool-call envelope whose + inner JSON the primary parser rejected. Returns a normalized tool-call + dict ({name, arguments, action, action_input}) or None if `text` is not + a recoverable envelope. + + The marker is searched ANYWHERE (the LAST 'Action:' line wins), not just + at the start of the text: a small model narrates first ('Final answer: + …'), leaks search-result fragments BEFORE the envelope, and smolagents' + own step log ('[Step 2: Duration …]') trails AFTER it — the observed + E2B final-output shape. Requiring the envelope at position 0 made all + of those leak the raw narration + envelope as the final answer.""" + m = None + for _m in re.finditer(r'(?ism)^\s*Action:?\s*(\{.*)$', text): + m = _m # keep the LAST 'Action:' marker — the final action + if m is None: + return None + blob = m.group(1).strip() + end = blob.rfind("}") + if end == -1: + return None + blob = blob[:end + 1].strip() + if not blob: + return None + + # 1. Clean JSON — the primary parser normally handles this before the + # fallback runs, but stay robust anyway. + try: + data = json.loads(blob, strict=False) + if isinstance(data, dict): + name = str(data.get("name") or data.get("action") or "final_answer") + arguments = data.get("arguments") + if arguments is None: + arguments = {"answer": data.get("answer", "")} + if isinstance(arguments, str): + arguments = {"answer": arguments} + return _tool_call_dict(name, arguments) + except Exception: + pass + + # 2. Bare "{tool_name: }" shape — Gemma's unquoted-key style, + # e.g. Action: {final_answer: "..."} + m_bare = re.match(r'^\{\s*([a-zA-Z0-9_]+)\s*:\s*(.*)\}\s*$', blob, re.DOTALL) + if m_bare: + name = m_bare.group(1).strip() + val = m_bare.group(2).strip() + try: + parsed = json.loads(val, strict=False) + except Exception: + parsed = None + if isinstance(parsed, dict): + return _tool_call_dict(name, parsed) + if val.lstrip().startswith("{"): + # Value is itself an object with (probably unquoted) keys — + # recover its 'answer' field the same way step 3 does. + recovered = _recover_answer_from_args(val) + if recovered: + return _tool_call_dict(name, recovered) + return _tool_call_dict(name, {"answer": val.strip('"\'')}) + + # 3. Malformed multi-key JSON — recover name and arguments separately. + name = None + m_name = re.search(r'''["']?name["']?\s*:\s*["']([^"']+)["']''', blob) + if m_name: + name = m_name.group(1).strip() + arguments = None + m_args = re.search(r'''["']?arguments["']?\s*:\s*(\{)''', blob) + if m_args: + args_blob = _match_braces(blob, m_args.start(1)) + if args_blob: + try: + arguments = json.loads(args_blob, strict=False) + except Exception: + arguments = _recover_answer_from_args(args_blob) + if name and arguments: + if isinstance(arguments, str): + arguments = {"answer": arguments} + return _tool_call_dict(name, arguments) + return None + + +_INVALID_CODE_CHAR_MAP = { + # Dashes and hyphens + "\u2010": "-", # hyphen + "\u2011": "-", # non-breaking hyphen + "\u2012": "-", # figure dash + "\u2013": "-", # en dash + "\u2014": "-", # em dash + "\u2015": "-", # horizontal bar + "\u2212": "-", # minus sign + # Quotation marks + "\u2018": "'", # left single quote + "\u2019": "'", # right single quote + "\u201a": "'", # single low-9 quotation mark + "\u201b": "'", # single high-reversed-9 quotation mark + "\u201c": '"', # left double quote + "\u201d": '"', # right double quote + "\u201e": '"', # double low-9 quotation mark + "\u201f": '"', # double high-reversed-9 quotation mark + "\u00ab": '"', # left-pointing double angle quotation mark + "\u00bb": '"', # right-pointing double angle quotation mark + "\u2039": "'", # single left-pointing angle quotation mark + "\u203a": "'", # single right-pointing angle quotation mark + # Punctuation & spaces + "\u2026": "...", # ellipsis + "\u00a0": " ", # non-breaking space + "\u202f": " ", # narrow no-break space + "\u2009": " ", # thin space + "\u2002": " ", # en space + "\u2003": " ", # em space + # Zero-width / control noise + "\u200b": "", # zero width space + "\u200c": "", # zero width non-joiner + "\u200d": "", # zero width joiner + "\ufeff": "", # zero width no-break space / BOM +} + + +def sanitize_python_text(text: str) -> str: + """Best-effort ASCII normalization of characters that CPython's + tokenizer REJECTS outright when they appear in generated code: + em/en dashes (a Gemma-style CodeAgent frequently copies a search + result title like '2026 FIFA World Cup — Wikipedia' straight into + its Python block), typographic quotes, ellipses, NBSP. Returns the + text unchanged when it contains nothing problematic. NEVER raises. + + This is NOT an attempt to fix genuinely broken Python — it only + replaces characters that are categorically invalid as tokens, so a + small model's "code" that is really just scraped prose degrades to + a parseable string instead of a hard 'Code parsing failed on line + N due to: SyntaxError: invalid character' step failure.""" + if not text or not any(ch in text for ch in _INVALID_CODE_CHAR_MAP): + return text + for ch, repl in _INVALID_CODE_CHAR_MAP.items(): + if ch in text: + text = text.replace(ch, repl) + return text + + +def _strip_code_xml_tags(text: str) -> str: + """Strip leaked tool-call XML tags (e.g. ``, + ``, `<|tool_call|>`, ``, ``, etc.) + that models (e.g. GLM-4.7-Flash, Qwen, Gemma) append or wrap around + Python code blocks or `final_answer(...)` calls. Returns the text + unchanged when no XML/tool tags are found. NEVER raises.""" + if not text or "<" not in text: + return text + # Strip trailing XML/tool-call tags (e.g. , ) + cleaned = re.sub(r"(?:\s*\s*)+$", "", text).rstrip() + # Strip leading XML/tool-call tags (e.g. ...) + cleaned = re.sub(r"^(?:\s*\s*)+", "", cleaned).lstrip() + return cleaned + + +# ── Windows-path escape recovery ───────────────────────────────────── +# A raw single-backslash Windows path (e.g. G:\...\uploads\...) inside a +# Python string literal is NOT valid source: '\u' in '\uploads' trips +# "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes +# ... truncated \uXXXX escape" (and '\l' / '\d' / octal digits silently +# corrupt the string value on some Python versions). This is the #1 +# reason a REAL code block — the Data Analysis manager delegating to +# data_worker with the dataset path — fails ast.parse() and the smart +# fallback mis-wraps the whole program as a "final answer" instead of +# running it. The fix doubles every backslash that is NOT an +# unambiguous, well-formed escape ('\\', quotes, valid \x/\u/\U/\N, +# line-continuation), so 'G:\...\uploads\...' becomes the valid literal +# 'G:\\...\\uploads\\...' with the SAME raw path value. Only ever a +# fallback for code that already failed to parse; valid escapes are +# preserved verbatim. +_VALID_STRING_ESCAPE_RE = re.compile( + r"\\[\\'\"]" + r"|\\x[0-9a-fA-F]{2}" + r"|\\u[0-9a-fA-F]{4}" + r"|\\U[0-9a-fA-F]{8}" + r"|\\N\{[^}]*\}" + r"|\\\r?\n" +) + + +def _neutralize_invalid_escapes(text: str) -> str: + """Double every backslash that is not part of an unambiguous valid + Python string escape, turning a raw Windows path into a valid string + literal with the same value. Well-formed escapes ('\\n', '\\t', '\\"', + '\\\\', '\\u0041', ...) pass through untouched. Returns the text + unchanged when there is nothing to fix. NEVER raises.""" + if not text or "\\" not in text: + return text + out = [] + i = 0 + n = len(text) + while i < n: + ch = text[i] + if ch != "\\": + out.append(ch) + i += 1 + continue + m = _VALID_STRING_ESCAPE_RE.match(text, i) + if m: + out.append(m.group(0)) + i = m.end() + else: + out.append("\\\\") + i += 1 + fixed = "".join(out) + return fixed if fixed != text else text + + +# ── DeepSeek DSML code-fence recovery ───────────────────────────────── +# DeepSeek-V4 / DeepSeek-R1 family models (HF Inference API) emit their +# Python code inside DeepSeek's OWN code fence instead of the ```python +# fence smolagents' CodeAgent expects: +# +# <|DSML|python> +# import pandas as pd +# df = pd.read_excel(path) +# print(df.shape) +# +# +# The fence markers use the full-width vertical bar '|' (U+FF5C), so +# smolagents' extract_code_from_text() (which looks for ```python) never +# matches, ast.parse() on the raw fence text fails, and the smart fallback +# used to wrap the WHOLE fence (markers + code) into final_answer("""…"""). +# On the Data Analysis tab that wrapped string then blows up with +# "SyntaxError: (unicode error) 'unicodeescape' … truncated \uXXXX escape" +# (a raw Windows path like G:\...\uploads\… inside the triple-quoted +# string) — the analysis never executes and the model burns its whole step +# budget retrying, then surrenders with raw code as the "final answer". +# Unwrapping the fence back to its inner code is the root-cause fix. + + +def _unwrap_dsml_fence(text: str): + """Extract Python code from a DeepSeek '<|DSML|python>…' + fence (tolerating ASCII '|' markers too). Returns the inner code, or + None when no DSML fence is present (so the caller falls through to the + other recovery paths).""" + if not text or "<" not in text: + return None + m = _DSML_FENCE_RE.search(text) + if not m: + return None + code = m.group(1).strip() + return code or None + + +# ── Qwen / Gemma native tool-call recovery ────────────────────────────── +# Qwen and Gemma-family local GGUFs frequently emit their OWN native tool +# call syntax instead of smolagents' ReAct envelope or a ```python fence: +# +# thought +# thought +# <|tool_call|>call:list_columns(file_path='G:\\...\\file.xlsx') +# +# Sometimes the call is even wrapped inside a final_answer("""…""") string +# (the model echoes the CodeAgent idiom it was trained on). On the +# CodeAgent path (Data Analysis) that wrapped shape is VALID Python, so +# smolagents' parse_code_blobs returns the leaked call as the final answer +# and the tool never runs — the model then wastes the next step narrating +# "Let me see the output of the list_columns call…" with no output to see, +# and eventually surrenders with raw code as the "final answer". The +# helpers below detect the native blocks and rewrite them into plain +# Python tool calls (a bare `tool(args)` expression resolves the tool in +# the executor and its result becomes the step's observation), or recover +# them as normalized tool-call dicts for the ToolCallingAgent JSON path. + +# The Qwen token renders as <|tool_call|> on BOTH sides (no closing +# slash), while Gemma-style output closes with — the pipe is +# optional on either side, so both shapes are tolerated. +_NATIVE_TOOL_CALL_RE = re.compile( + r"<\|?tool_call\|?>\s*(.*?)\s*<\|?/?tool_call\|?>", + re.DOTALL, +) + +# Gemma-family `call:` envelope closed by EITHER a ``-style +# tag or (the observed E4B shapes) a closing ``` code fence — see +# _rewrite_native_tool_calls. Two bodies, both of which the old +# _NATIVE_TOOL_CALL_RE (tag-closing-only) leaked: +# * `call:python\n` — the body is executable Python +# (assignment + print of a managed-agent / tool call); +# * `call:list_columns(file_path='…')` — a BARE call whose envelope is +# closed by a fence instead of a tag. +_CALL_BLOCK_RE = re.compile( + r"<\|?tool_call\|?>\s*call:([a-zA-Z0-9_]+)\s*(.*?)\s*(?:<\|?/?tool_call\|?>|```)", + re.DOTALL, +) + + +def _py_literal(value) -> str: + """Render a JSON-ish value as a valid Python literal expression + (JSON's true/false/null become True/False/None; Khmer strings stay + readable via ensure_ascii=False).""" + if isinstance(value, bool): + return "True" if value else "False" + if value is None: + return "None" + if isinstance(value, str): + return json.dumps(value, ensure_ascii=False) + if isinstance(value, (int, float)): + return repr(value) + if isinstance(value, dict): + return "{" + ", ".join( + f"{_py_literal(k)}: {_py_literal(v)}" for k, v in value.items() + ) + "}" + if isinstance(value, (list, tuple)): + return "[" + ", ".join(_py_literal(x) for x in value) + "]" + return json.dumps(value, ensure_ascii=False) + + +def _quote_unquoted_keys(text: str) -> str: + """Quote unquoted JSON-ish keys (Gemma's call:tool{key: value}) so the + blob becomes parseable JSON.""" + return re.sub(r"([\"']?)([a-zA-Z0-9_]+)([\"']?)\s*:", r'"\2":', text) + + +def _braces_to_dict(brace_args: str) -> Optional[dict]: + """Parse Gemma-style '{key: value, ...}' tool arguments into a dict: + strict JSON first, then single-quoted / unquoted keys, then a + last-resort regex pair split. Returns None when nothing parses.""" + if not brace_args.strip(): + return {} + for attempt in (brace_args, _quote_unquoted_keys(brace_args)): + try: + parsed = json.loads("{" + attempt + "}", strict=False) + if isinstance(parsed, dict): + return parsed + except Exception: + continue + pairs = re.findall(r"""["']?([a-zA-Z0-9_]+)["']?\s*:\s*(".*?"|'.*?'|[^,}]+)""", brace_args, re.DOTALL) + if not pairs: + return None + out = {} + for key, val in pairs: + out[key] = val.strip().strip('\"\'') + return out + + +def _parse_native_call(blob: str): + """Parse ONE native tool-call body into (name, args_text, args_dict): + - args_dict is a dict when the arguments were written in JSON-ish + braces form ({"file_path": "..."} or call:tool{key: 'val'}); + - args_text is the verbatim Python kwargs text when the model wrote + key='val' style inside parens (the observed Qwen shape). + Returns None when the body isn't a parseable native call.""" + blob = blob.strip() + if not blob: + return None + # GLM-4.7-Flash (the llama-server native tool-call format) appends a + # stray `` XML fragment AFTER the call's close paren, before + # the `` close tag (observed end-to-end: the manager's + # intended `data_worker(task='…')` delegation carried it, which broke + # the anchored `\s*$` parse below and leaked the whole envelope). Strip + # trailing tag-ish garbage so the call still parses cleanly. + blob = re.sub(r"(?:\s*)+$", "", blob).rstrip() + if not blob: + return None + if blob.startswith("{"): + try: + data = json.loads(blob, strict=False) + except Exception: + data = None + if not isinstance(data, dict): + return None + name = data.get("name") or data.get("action") + arguments = data.get("arguments") + if not name or not isinstance(arguments, dict): + return None + return (str(name), "", dict(arguments)) + m = re.match( + r"^(?:call\s*:\s*)?([a-zA-Z0-9_]+)\s*(?:\((.*)\)|\{(.*)\})\s*$", + blob, + re.DOTALL, + ) + if not m: + return None + name = m.group(1).strip() + brace_args = m.group(3) + if brace_args is not None: + args_dict = _braces_to_dict(brace_args) + if args_dict is None: + return None + return (name, "", args_dict) + args_text = (m.group(2) or "").strip() + # A JSON object inside the parens (call:tool({"key": "v"})) isn't the + # Python kwargs the tool expects — convert it to kwargs. + if args_text.startswith("{"): + try: + data = json.loads(args_text, strict=False) + if isinstance(data, dict): + return (name, "", dict(data)) + except Exception: + pass + return (name, args_text, None) + + +def _native_expr_parses(expr: str) -> bool: + try: + ast.parse(expr) + return True + except SyntaxError: + return False + + +def _native_call_to_python(blob: str) -> Optional[str]: + """Rewrite ONE native tool-call body into a plain Python expression + ('list_columns(file_path="...")') the CodeAgent executor can run. The + tools live in the executor's environment, so the bare call executes the + tool and its result becomes the step's observation. Returns None when + the body isn't a parseable native call.""" + parsed = _parse_native_call(blob) + if parsed is None: + return None + name, args_text, args_dict = parsed + if name == "final_answer": + # A native envelope that CALLS final_answer (Gemma-family + # `call:final_answer(report="...")` and the nested-inside-string + # variant) is a final-answer delivery, not a tool call. The + # FinalAnswerTool only accepts a POSITIONAL `answer` — a model that + # emits `final_answer(report="...")` (or answer=/text=) hard-fails + # with "unexpected keyword argument 'report'". Normalize the payload + # to the positional triple-quoted form so the report text survives. + payload = None + if args_dict is not None: + for val in args_dict.values(): + if isinstance(val, str): + payload = val + break + else: + m_kw = re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*(.*)$", args_text.strip(), re.DOTALL) + raw = m_kw.group(1) if m_kw else args_text.strip() + raw = raw.strip() + if raw.startswith('"""') and raw.endswith('"""'): + payload = raw[3:-3] + elif len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'": + payload = raw[1:-1] + else: + payload = raw + if payload is not None: + payload = sanitize_python_text(payload) + payload = _neutralize_invalid_escapes(payload) + escaped = payload.replace('"""', '\\"\\"\\"') + expr = f'final_answer("""{escaped}""")' + if _native_expr_parses(expr): + return expr + if args_dict is not None: + kwargs = ", ".join( + f"{key}={_py_literal(val)}" for key, val in args_dict.items() + ) + expr = f"{name}({kwargs})" + else: + # The parens form is Python-kwargs text (task='…'). Re-render it + # as a dict FIRST: the verbatim text can carry raw NEWLINES (the + # observed GLM-4.7-Flash delegation task spans several lines — a + # literal newline inside a '…' string is a SyntaxError), embedded + # quotes, and double-backslash Windows paths that a verbatim + # re-wrap can never survive. json.dumps escaping (via _py_literal) + # renders the SAME value as a valid literal. + kwargs_dict = _kwargs_text_to_dict(args_text) + if kwargs_dict is not None: + kwargs = ", ".join( + f"{key}={_py_literal(val)}" for key, val in kwargs_dict.items() + ) + expr = f"{name}({kwargs})" + if _native_expr_parses(expr): + return expr + expr = f"{name}({args_text})" + if not _native_expr_parses(expr): + # A raw Windows path (single backslashes, e.g. G:\user_data\...) + # is not valid Python source — '\u' trips a 'truncated \uXXXX' + # unicodeescape SyntaxError. Doubling the backslashes makes the + # string literal valid while keeping the SAME raw path value. + fixed_args = args_text.replace("\\", "\\\\") + expr = f"{name}({fixed_args})" + if not _native_expr_parses(expr): + return None + return expr + + +def _kwargs_text_to_dict(args_text: str) -> Optional[dict]: + """Parse Python-kwargs-style call arguments ('task="…", file_path="…"' + — with raw newlines, embedded quotes and Windows paths) into a dict of + string values, tolerantly: strict JSON first, then a regex pair split + (same pattern the ToolCallingAgent path uses). Returns None when + nothing parses. Values keep their exact bytes — the caller re-renders + them with proper Python-literal escaping.""" + if not args_text or not args_text.strip(): + return {} + try: + data = json.loads("{" + args_text + "}", strict=False) + if isinstance(data, dict): + return data + except Exception: + pass + pairs = re.findall( + r'([a-zA-Z0-9_]+)\s*[:=]\s*(".*?"|\'.*?\'|[^,}]+)', args_text, re.DOTALL + ) + if not pairs: + return None + out = {} + for key, val in pairs: + out[key] = val.strip().strip('\"\'') + return out + + +# Some models (Qwen3-4B-Q8_0 observed end-to-end) emit a `from tools +# import list_columns` line — the smolagents tutorial idiom for running +# tool calls. This sandbox exposes tools as PLAIN CALLABLES in the +# executor's static_tools (there is no `tools` module), so that import +# raises `InterpreterError: Module tools has no attribute list_columns` +# and the worker's step fails. The names ARE available bare, so stripping +# the import (and the equivalent `tools.list_columns(...)` attribute +# access) lets the code run — the same tool, reached the way the sandbox +# actually provides it. +_TOOLS_IMPORT_LINE_RE = re.compile(r"(?m)^[ \t]*from[ \t]+tools[ \t]+import[ \t]+[^\r\n]*$") +_TOOLS_ATTR_CALL_RE = re.compile(r"\btools\.([a-zA-Z_][a-zA-Z0-9_]*)\s*(\()") + + +def _normalize_tools_module_idiom(text: str) -> str: + """Rewrite the `from tools import X` / `tools.X(...)` idiom into plain + bare-name calls the sandbox's static_tools resolve. Pure text + normalization; never raises. Leaves every other import untouched.""" + if not text: + return text + text = _TOOLS_IMPORT_LINE_RE.sub("", text) + return _TOOLS_ATTR_CALL_RE.sub(r"\1\2", text) + + +def _unwrap_nested_final_answer(text: str) -> Optional[str]: + """Detect an INNER final_answer(...) call embedded inside an OUTER + final_answer wrapper string (the E2B manager shape observed end-to-end: + the model narrates its reasoning as a `final_answer` triple-quoted + string and then delivers the REAL report as a nested + `final_answer(report=...)` call before the closing fence/quote). The + outer call is VALID Python, so + the original parser returns the whole leaked narration as the final + answer (the leaked-code validator then rejects it). Extract the + innermost call and normalize it — the same kwargs-to-positional handling + _native_call_to_python applies — so the real report text survives. + Returns None when there is no nested call.""" + if not text or text.count("final_answer(") < 2: + return None + inner = text.rfind("final_answer(") + tail = text[inner:] + # The inner call is closed by a ``` fence (observed) or the outer + # string's own quotes — cut the tail there so rfind(')') in the + # final_answer recovery sees the INNER call's close, not the outer + # wrapper's. + fence = tail.find("```") + if fence != -1: + tail = tail[:fence] + expr = _native_call_to_python(tail) + if expr is not None and _native_expr_parses(expr): + return expr + return None + + +def _recover_final_answer_call(text: str) -> Optional[str]: + """Recover a final_answer(...) call whose string argument contains + unescaped quotes (the E4B failure: a report body with `24" Monitor` or + quoted Khmer column names inside `final_answer("...")`, which is an + unterminated string literal and fails ast.parse). The smart fallback's + non-greedy final_answer-regex would cut the payload at the + FIRST ')' inside the report, so this helper takes everything up to the + LAST ')' and re-wraps it with triple-quote escaping — the answer text + is preserved verbatim and the emitted code always parses. Returns None + when the text holds no recoverable final_answer call (normal parsing + proceeds).""" + if not text: + return None + start = text.find("final_answer(") + if start == -1: + return None + open_idx = start + len("final_answer(") + end = text.rfind(")") + if end <= open_idx: + return None + payload = text[open_idx:end] + # Strip a wrapping quote layer the model added (the call was + # final_answer("...") or final_answer("""...""")), so the payload is + # the raw report text. + payload = payload.strip() + if payload.startswith('"""') and payload.endswith('"""'): + payload = payload[3:-3] + elif payload.startswith('"') and payload.endswith('"'): + payload = payload[1:-1] + elif payload.startswith("'") and payload.endswith("'"): + payload = payload[1:-1] + payload = _strip_code_xml_tags(payload) + payload = sanitize_python_text(payload) + payload = _neutralize_invalid_escapes(payload) + escaped = payload.replace('"""', '\\"\\"\\"') + expr = f'final_answer("""{escaped}""")' + try: + import ast + ast.parse(expr) + return expr + except Exception: + return None + + +def _payload_from_final_answer_args(args_dict, args_text: str) -> Optional[str]: + """Extract the report payload from a final_answer call's parsed + arguments, PRESERVING the text verbatim (no tokenizer sanitize — this is + a displayed answer, and em-dashes / typographic quotes are legitimate + there). Handles both the JSON-braces form (preferring the conventional + `answer` / `report` / `text` keys) and the Python-kwargs form + (`final_answer(report="…")` / positional quoted strings). Returns None + when no string payload is found.""" + if args_dict is not None: + for key in ("answer", "report", "text"): + val = args_dict.get(key) + if isinstance(val, str) and val.strip(): + return val + for val in args_dict.values(): + if isinstance(val, str) and val.strip(): + return val + return None + m = re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*(.*)$", (args_text or "").strip(), re.DOTALL) + raw = (m.group(1) if m else (args_text or "")).strip() + if raw.startswith('"""') and raw.endswith('"""'): + return raw[3:-3] + if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'": + return raw[1:-1] + return raw or None + + +# ── Chat-template token leak recovery ───────────────────────────────── +# A model can leak its chat template's control tokens into a final answer +# instead of (or trailing) real content. The observed case: Muse Glimmer +# (Meta's agent model — its template frames turns as +# <|start|>role<|message|>…<|eot|> and the assistant writes answer +# channels, "to=user" for the reply, "to=self" for reasoning) — a +# community "-UD-" GGUF quant emitted its channel-close fragment +# "to=user<|eot|>" as the WHOLE payload of a final_answer tool call. The +# fragments below are tokenizer/control tokens and channel markers — +# never legitimate answer text — so stripping them from a delivered +# answer is safe, and the shared final-answer validator +# (agent_factory.reject_leaked_or_empty_final_answer) rejects an answer +# that becomes EMPTY after the strip (pure template garbage) instead of +# shipping it as the answer bubble. + +_TEMPLATE_TOKEN_RE = re.compile( + r"<\|?(?:" + r"start|message|eot|im_start|im_end|endoftext|eos|eot_id|eos_id|" + r"start_of_turn|end_of_turn|tool_call|/?tool_call|think|/?think|" + r"reasoning|/?reasoning" + r")\|?>|", + re.IGNORECASE, +) + +# Muse Glimmer's channel markers ("to=user" / "to=assistant" / "to=self" / +# "to="). The fragment must be STANDALONE — preceded by whitespace/ +# start (so `--to=user` or `param.to=user` in a coding answer is never +# touched) and NOT continuing into an identifier ('to=users', 'to=user_id' +# survive) — but ANY non-identifier follower is allowed, so a BARE marker +# with no trailing <|eot|> token is still caught: 'to=self```' (glued to a +# code-fence opener), 'to=user###', 'to=self' at end of text. +_CHANNEL_MARKER_RE = re.compile( + r"(?)(?![A-Za-z0-9_])", + re.IGNORECASE, +) + +# After the marker is stripped, a marker glued to a code-fence opener +# ('to=self```') leaves only the fence behind — pure-fence residue is +# still the leak, never answer content. +_FENCE_ONLY_RE = re.compile(r"^[\s`]+$") + + +def strip_template_tokens(text: str) -> str: + """Remove chat-template control tokens (Qwen3's <|eot|>, ChatML's + <|im_start|>/<|im_end|>, Llama-3's <|eot_id|>/<|eos_id|>, Gemma's + <|start_of_turn|>/<|end_of_turn|>, <|endoftext|>, , Qwen native + <|tool_call|>, Muse Glimmer's <|start|>/<|message|>/channel markers + — both with the <|eot|> token (to=user<|eot|>) and BARE with no token + at all (to=self```, to=user###, to=user at end of text; the + channel form to= is covered too). Real content around the + tokens survives ("…X.<|eot|>" → "…X."); the whole text disappears + only when it WAS the leak. Returns the text unchanged when nothing + matches. NEVER raises.""" + if not text or not isinstance(text, str): + return text + if "<" not in text and "to=" not in text: + return text + # The channel-marker pass runs BEFORE and AFTER the token pass: a + # marker only becomes standalone once a preceding token is removed + # ("to=assistant" → "to=assistant"). + text = _CHANNEL_MARKER_RE.sub("", text) + text = _TEMPLATE_TOKEN_RE.sub("", text) + text = _CHANNEL_MARKER_RE.sub("", text) + # The removals can leave doubled spaces ("… X. <|eot|>" → "… X. "). + text = re.sub(r" {2,}", " ", text) + text = text.strip() + # A bare channel marker glued to a code-fence opener ('to=self```') + # leaves only the fence behind — pure-fence residue is still the leak. + if text and _FENCE_ONLY_RE.match(text): + return "" + return text + + +# ── Degenerate-repetition detection ────────────────────────────────── +# A broken generation — e.g. a TEXT request that landed on an EMBEDDING +# model through a shared llama-server port (the observed "skills skills +# skills …" failure) — produces one token repeated until the token budget +# is exhausted. No real answer looks like that, so it can be detected +# cheaply and rejected before it is shipped as an answer or fed back as a +# giant garbage observation. +_DEGEN_MIN_TOKENS = 100 # only judge answers with enough material +_DEGEN_MAX_RUN = 30 # >30 consecutive identical tokens = loop +_DEGEN_DOMINANT_RATIO = 0.5 # one token > half of a long answer = loop +_DEGEN_MAX_CHAR_RUN = 200 # one letter/digit repeated 200+ times = loop + +# Alphanumeric only, so decorative rules ('──────', '══════') and table +# borders are never flagged; U+1780–U+17FF covers Khmer letters. +_DEGEN_CHAR_LOOP_RE = re.compile( + r"([A-Za-z0-9\u1780-\u17FF])\1{%d,}" % (_DEGEN_MAX_CHAR_RUN - 1) +) + + +def is_degenerate_repetition(text) -> bool: + """True when `text` is degenerate token repetition instead of an + answer: one word/token repeated over and over ("skills skills skills + …") until the budget ran out, or a single letter/digit repeated + hundreds of times in a row. + + Deliberately conservative so real answers are never rejected: + - fewer than _DEGEN_MIN_TOKENS whitespace tokens is never judged + (Khmer prose splits into very few whitespace tokens); + - the word-level checks need _DEGEN_MAX_RUN consecutive identical + tokens, or one token filling more than half of a long answer; + - the character-level check fires only on ALPHANUMERIC runs of + _DEGEN_MAX_CHAR_RUN+ — decorative rules survive. + NEVER raises.""" + try: + if not text or not isinstance(text, str): + return False + tokens = text.split() + if len(tokens) >= _DEGEN_MIN_TOKENS: + norm = [t.lower() for t in tokens] + run = best = 1 + for i in range(1, len(norm)): + run = run + 1 if norm[i] == norm[i - 1] else 1 + if run > best: + best = run + if best >= _DEGEN_MAX_RUN: + return True + counts = {} + for t in norm: + counts[t] = counts.get(t, 0) + 1 + if max(counts.values()) / len(norm) > _DEGEN_DOMINANT_RATIO: + return True + return bool(_DEGEN_CHAR_LOOP_RE.search(text)) + except Exception: + return False + + +def _payload_from_openai_call(call) -> Optional[str]: + """Extract the payload of a final_answer call from ONE OpenAI-style + tool-call dict (the shape smolagents prints in its 'Calling tools:' + line). `arguments` may be a dict or a JSON-encoded string; the payload + key may be `answer` / `report` / `text` / `answer_text`.""" + if not isinstance(call, dict): + return None + fn = call.get("function") + if not isinstance(fn, dict): + return None + if str(fn.get("name", "")).strip() != "final_answer": + return None + arguments = fn.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except Exception: + arguments = None + if not isinstance(arguments, dict): + return None + payload = _payload_from_final_answer_args(arguments, "") + return payload if payload and payload.strip() else None + + +_CALLING_TOOLS_ENVELOPE_RE = re.compile( + r"Calling tools\s*:\s*(\[.*\])", re.DOTALL | re.IGNORECASE) + + +def _payload_from_calling_tools_envelope(text) -> Optional[str]: + """Recover the final_answer payload from smolagents' OWN 'Calling + tools:' line followed by a Python-repr list of OpenAI-style tool calls + — the shape a ToolCallingAgent model (observed: Muse Glimmer via + llama-server) emits when it writes the final_answer call as PLAIN TEXT + instead of a structured tool call: + + Calling tools: + [{'id': 'a1b2c3d4-…', 'type': 'function', + 'function': {'name': 'final_answer', + 'arguments': {'answer_text': '### …'}}}] + + The max-steps fallback then ships that text verbatim as the answer + bubble. Returns the payload string, or None when the text isn't such + an envelope (normal parsing proceeds). The literal_eval path handles + the complete list; a tolerant scan handles a cut-off tail (the + observed Muse Glimmer output is truncated mid-dict with NO closing + ']').""" + if not text or not isinstance(text, str): + return None + stripped = text.strip() + m = _CALLING_TOOLS_ENVELOPE_RE.search(stripped) + if m: + block = m.group(1).strip() + else: + # No closing ']' — the output was cut mid-envelope. Everything + # after the 'Calling tools:' label is the fragment to scan. + head = re.split(r"Calling tools\s*:", stripped, maxsplit=1, + flags=re.IGNORECASE) + block = head[1].strip() if len(head) == 2 and head[1].strip() else None + if not block: + return None + calls = None + try: + import ast + calls = ast.literal_eval(block) + except Exception: + calls = None + if isinstance(calls, list): + for call in calls: + payload = _payload_from_openai_call(call) + if payload: + return payload + # Tolerant fallback: literal_eval fails on a truncated list tail — + # scan the raw fragment for a final_answer call's arguments dict. + if "final_answer" not in block: + return None + args_m = re.search(r"['\"]arguments['\"]\s*:\s*(\{.*)", block, re.DOTALL) + if args_m: + brace = args_m.group(1).strip() + # Best-effort: pass the dict CONTENT (drop the outer brace and a + # truncated trailing '}'/']') so _braces_to_dict sees clean pairs. + if brace.startswith("{"): + brace = brace[1:] + brace = brace.rstrip("}]") + args_dict = _braces_to_dict(brace) + if args_dict: + payload = _payload_from_final_answer_args(args_dict, "") + if payload: + return payload + return None + + +_PREAMBLE_TRANSITION_RE = re.compile( + r"(?:\b(?:I have sufficient info(?:rmation)?|I have enough info(?:rmation)?|" + r"I will now write the (?:final )?answer|Here is the (?:final )?(?:answer|summary|response|report)|" + r"I will compile the answer in Khmer|I will write the response in(?: natural)? Khmer|" + r"Constructing (?:Final )?Output|Final Output)\b[.:\s]*)" + r"(.*)$", + re.IGNORECASE | re.DOTALL, +) + +_KHMER_CHAR_RE = re.compile(r"[\u1780-\u17FF]") + +_META_ENGLISH_STARTS = ( + "the user is", "the user wants", "the user asked", "user is asking", "the user's query", + "the user's message", "the greeting is", "this is a", "this is simply", "since this is", + "the search results provide", "search results show", "key themes:", "summary structure", + "plan:", "refined summary:", "wait, i should", "i will compile the answer", "i will write the response", + "i should respond", "i need to respond", "let's respond", "let me respond", + "analyze the request", "analyzing the request", "analyze the input", "analyzing the input", + "drafting the content", "input: ", + # GLM-4.7-Flash and similar reasoning GGUFs often open their final answer + # with a long English planning monologue instead of a block. These + # openings identify that monologue so the answer after it can be extracted. + "i need to analyze", "let me understand", "let me analyze", "i need to understand", + "let me think", "let me break", "the task is", "i'm being asked", "i should figure", + "let's analyze", "i will analyze", "the instructions are", "the task says", + "i'm supposed to", "here is my analysis", "my task is", "the prompt is", + "step 1:", + # GLM-4.7-Flash also opens with a third-person summary of what it was + # given ("The user has provided a task in Khmer. The task appears to be + # asking me to respond...") before either its answer or a full echo of + # the task text. + "the user has", "the task appears", +) +# NOTE: deliberately NOT meta-starts (too generic — legit answers open with +# them and stripping would chop real content): "looking at the", "first, i", +# "to answer this". + +# Khmer meta-reasoning / prompt-analysis phrases — third-person reference to +# the user's question, tool-usage decisions, or response planning in Khmer. +# When the model outputs its chain-of-thought in Khmer (instead of wrapping +# it in tags), these patterns identify the reasoning preamble so the +# actual answer following it can be extracted. +_META_KHMER_PHRASES = ( + "សំណួររបស់អ្នកប្រើគឺ", # "The user's question is" + "សំណួររបស់អ្នកគឺ", # "Your question is" + "សំណួរនេះគឺ", # "This question is" + "នេះគឺជាសំណួរ", # "This is a question" + "នេះគឺជា", # "This is" + "វាគឺជា", # "It is" + "ដូច្នេះខ្ញុំគិតថា", # "So I think" + "ដូច្នេះខ្ញុំគ្រាន់", # "So I just" + "ដូច្នេះខ្ញុំនឹង", # "So I will" + "ខ្ញុំមិនត្រូវការប្រើ", # "I don't need to use" + "ខ្ញុំត្រូវតែឆ្លើយ", # "I need to answer" + "ខ្ញុំនឹងឆ្លើយ", # "I will answer" + "សម្រាប់សំណួរនេះ", # "For this question" + "សម្រាប់សំណួរសាកល្បង", # "For this test question" + "កុំប្រើ", # "Don't use" + "មិនចាំបាច់ប្រើ", # "No need to use" + "ខ្ញុំគិតថា", # "I think that" + "ខ្ញុំនឹងផ្តល់", # "I will provide" + "ដូច្នេះខ្ញុំគ្រាន់តែ", # "So I just" + "នេះមិនមែនជា", # "This is not" + "គ្មានការស្វែងរក", # "No search needed" + "មិនត្រូវការស្វែងរក", # "No need to search" +) + + +# Deliberation-shaped SENTENCE markers for English-only leaks — third-person +# narration of what the user said / tool-usage decisions / output planning. +# Only whole leading sentences carrying one of these are ever dropped, so a +# legitimate answer sentence without them is never eaten. +_META_ENGLISH_SENTENCE_MARKERS = ( + "i should respond", "i should follow", "i should not include", + "i don't need to use any tools", "no tools are needed", "i don't need any tool", + "this is a simple greeting", "this is a straightforward", + "the user has just said", "the user has provided a task", + "the user wants me to", "they want me to respond", + "i'll just give", "i will give a natural", "i will provide a direct", + "not output internal plan", "internal planning or thinking", +) + + +def _strip_leading_english_meta_sentences(text, max_sentences=15): + """Drop leading deliberation sentences from an ENGLISH-only leak (meta + monologue followed by an English answer — no Khmer anywhere, so the + Khmer-block extraction paths can never fire). Each dropped chunk must + contain a deliberation marker and end at a real sentence/line terminator; + the walk stops at the first sentence without one. Returns '' when nothing + survives (caller keeps the original text).""" + tail = text.strip() + low = "" + for _ in range(max_sentences): + low = tail.lower() + hit = -1 + for marker in _META_ENGLISH_SENTENCE_MARKERS: + idx = low.find(marker) + if idx != -1 and (hit == -1 or idx < hit): + hit = idx + if hit == -1: + break + end = len(tail) + for j in range(hit, len(tail)): + if tail[j] in ".!?\n": + end = j + 1 + break + if end >= len(tail): + break + while end < len(tail) and tail[end] in ".!?\n \t\r": + end += 1 + tail = tail[end:].lstrip() + return tail if tail and len(tail.strip()) >= 4 else "" + + +def _strip_deliberation_preamble(text: str) -> str: + """Strip internal chain-of-thought / deliberation / scratchpad preambles + from final answer text when an actual answer follows. + + Handles cases where a model (e.g. Gemma-4, GLM, Qwen) outputs internal + English monologue or planning notes (e.g. 'The search results provide a good overview... + Plan: ... Refined Summary: ... I have sufficient info.', 'Analyze the Request: ... + Constructing Final Output.', or 'The user is greeting me in Khmer. I should respond in Khmer... + Since this is a simple greeting. សួស្តី!...') before transitioning into the actual answer. + + Returns the stripped, clean answer. If no preamble is detected or the text + is pure scratchpad without an answer, returns the original text unchanged. + """ + if not text or not isinstance(text, str): + return text + + # 1. Direct transition phrase (e.g. "I have sufficient info. នេះគឺជា...", + # "Constructing Final Output. # ចំណងជើង...", "Here is the summary: ...") + m = _PREAMBLE_TRANSITION_RE.search(text) + if m: + tail = m.group(1).strip() + if tail and not any(tail.lower().startswith(s) for s in _META_ENGLISH_STARTS): + return tail + + # 2. English planning / prompt-analysis scratchpad followed by a Khmer answer: + low = text.lower().strip() + is_meta_start = any(low.startswith(s) for s in _META_ENGLISH_STARTS) + has_meta_phrase = any(s in low[:2500] for s in ( + "plan:", "refined summary:", "analyze the request:", "drafting the content", + "constructing final output", "i should respond in", "the user is greeting", + "the greeting is simply", + # GLM-4.7-Flash planning-monologue markers (often appear mid-text, not + # at the very start of the answer): + "i need to analyze", "let me understand what's being asked", "let me analyze", + "i should not include any planning", "i should respond directly", + "the instructions are asking", "the task says", "i'm supposed to respond", + "i need to respond in", "i should respond in", "let me think about", + "let me break this down", "here is my analysis", + )) + + if (is_meta_start or has_meta_phrase) and _KHMER_CHAR_RE.search(text): + # Look for terminal Khmer text block (after all English meta-talk) + m_khmer = re.search(r"(?:^|[.!?\n]\s*)([\u1780-\u17FF][^\n]*(?:[.!?\n]|\Z).*)$", text, re.DOTALL) + if m_khmer: + candidate = m_khmer.group(1).strip() + if candidate and not any(candidate.lower().startswith(s) for s in _META_ENGLISH_STARTS): + if len(_KHMER_CHAR_RE.findall(candidate)) >= 5: + return candidate + + # Also check inline transition: e.g. "...greeting.សួស្តី!..." + m_inline = re.search(r"[a-zA-Z0-9_\-'\"]+[.!?:\s]+([\u1780-\u17FF].*)$", text, re.DOTALL) + if m_inline: + candidate = m_inline.group(1).strip() + if candidate and len(_KHMER_CHAR_RE.findall(candidate)) >= 5: + return candidate + + # Line-by-line fallback + lines = text.splitlines() + cut_idx = None + for idx in range(len(lines) - 1, -1, -1): + line_s = lines[idx].strip() + if not line_s: + continue + if _KHMER_CHAR_RE.search(line_s) and not any(line_s.lower().startswith(s) for s in _META_ENGLISH_STARTS): + cut_idx = idx + break + + if cut_idx is not None and cut_idx > 0: + candidate = "\n".join(lines[cut_idx:]).strip() + m_inline_fallback = re.search(r"[a-zA-Z0-9_\-'\"]+[.!?:\s]+([\u1780-\u17FF].*)$", candidate, re.DOTALL) + if m_inline_fallback: + candidate = m_inline_fallback.group(1).strip() + if candidate: + return candidate + + # 2b. ENGLISH-ONLY deliberation leak — same monologue class but the + # actual answer is English too (no Khmer anywhere), so every + # Khmer-block extraction above can never fire. Drop each leading + # sentence that itself carries a deliberation marker and return what + # remains (e.g. GLM's 'The user has just said "hi". ... response.' + + # 'Hi there! ...' → 'Hi there! ...'). + if (is_meta_start or has_meta_phrase) and not _KHMER_CHAR_RE.search(text): + tail = _strip_leading_english_meta_sentences(text) + if tail: + return tail + + # 3. Khmer-only meta-reasoning / prompt-analysis scratchpad: + # GLM-4.7-Flash and similar models sometimes output their entire + # chain-of-thought in Khmer instead of wrapping it in tags. + # The text is ALL Khmer (no English meta-starts), but the first + # paragraph(s) reference the user's question in third person or + # discuss tool-usage decisions. Extract the first non-meta paragraph + # as the actual answer. + if _KHMER_CHAR_RE.search(text) and not is_meta_start: + low_full = text.lower() + has_kh_meta = any(p in low_full[:2500] for p in _META_KHMER_PHRASES) + if has_kh_meta: + # Split into paragraphs (double-newline or paragraph boundaries) + paragraphs = re.split(r"\n\s*\n", text) + for i, para in enumerate(paragraphs): + para_strip = para.strip() + if not para_strip: + continue + para_low = para_strip.lower() + # If this paragraph does NOT start with a Khmer meta-phrase, + # it's likely the actual answer. + if not any(p in para_low[:80] for p in _META_KHMER_PHRASES): + if len(_KHMER_CHAR_RE.findall(para_strip)) >= 3: + return para_strip + # Fallback: look for a Khmer text block after the last + # meta-reasoning paragraph (same pattern as step 2). + m_khmer = re.search( + r"(?:^|[.!?\u17D4\n]\s*)([\u1780-\u17FF][^\n]*(?:[.!?\u17D4\n]|\Z).*)$", + text, re.DOTALL) + if m_khmer: + candidate = m_khmer.group(1).strip() + if candidate and not any( + p in candidate.lower()[:80] for p in _META_KHMER_PHRASES): + if len(_KHMER_CHAR_RE.findall(candidate)) >= 3: + return candidate + + return text + + +def sanitize_surrogates(text: str) -> str: + """Sanitize invalid Unicode surrogate code points (U+D800 - U+DFFF) + so that strings can safely be encoded to UTF-8 without raising UnicodeEncodeError.""" + if not isinstance(text, str): + return str(text) if text is not None else "" + try: + return text.encode("utf-8", errors="replace").decode("utf-8") + except Exception: + return "".join(c for c in text if not (0xD800 <= ord(c) <= 0xDFFF)) + + +def _unwrap_leaked_final_answer(text) -> str: + """Wrapper around _unwrap_leaked_final_answer_raw: after the leaked + envelope is unwrapped (or plain text passes through), strip any + chat-template control tokens from whatever survived (see + strip_template_tokens) and any internal thinking/scratchpad preamble + (see _strip_deliberation_preamble) — ensuring that the delivered answer + bubble is clean, structured, and free of meta-planning/scratchpad noise.""" + if not text or not isinstance(text, str): + return text + result = _unwrap_leaked_final_answer_raw(text) + if isinstance(result, str) and result: + result = strip_template_tokens(result) + result = _strip_deliberation_preamble(result) + result = sanitize_surrogates(result) + return result + + +def _unwrap_leaked_final_answer_raw(text) -> str: + """Recover the real answer/report from a final-answer string that leaked + the model's tool-call envelope instead of its payload. + + The step-parsing path is covered by the parse_json_blob patch, but + smolagents' max-steps fallback (`_handle_max_steps_reached` → + `provide_final_answer`) takes the model's RAW text as the final answer + WITHOUT any tool-call parsing. A transformers model trained on + smolagents transcripts answers the "give your final answer" prompt with + its trained call format as plain text — the observed E2B shape + `call:final_answer{answer: "### …"}` (and `…} />` variants) — which + then renders verbatim as the answer bubble. Shapes handled: + call:final_answer{answer: "..."} (native call, quoted/unquoted keys) + call:final_answer(report="...") (native call, kwargs) + final_answer("...") / triple-quoted final_answer(...) / final_answer(report="…") + Action: {final_answer: "..."} (ReAct envelope) + Non-envelope text is returned unchanged — a plain answer is never + touched.""" + if not text or not isinstance(text, str): + return text + stripped = text.strip() + if not stripped: + return text + + # A trailing self-close marker (…} />) some models append after the + # envelope's closing brace would break the anchored parse — drop it. + cleaned = stripped[:-2].strip() if stripped.endswith("/>") else stripped + + # 1) Whole-text native call / final_answer(...) — anchored, so prose + # that merely mentions a call is never touched. + parsed = _parse_native_call(cleaned) + if parsed is not None: + name, args_text, args_dict = parsed + if name == "final_answer": + payload = _payload_from_final_answer_args(args_dict, args_text) + if payload is not None and payload.strip(): + return payload + + # 2) Tolerant non-anchored recovery for the wrapped/`/>`-terminated + # shapes the anchored parse rejects — recover the arguments dict the + # same way _smart_parse_json_blob does. + m = re.search(r"call\s*:\s*final_answer\s*\{(.*)\}", cleaned, re.DOTALL) + if m: + args_dict = _braces_to_dict(m.group(1)) or {} + for key in ("answer", "report", "text"): + val = args_dict.get(key) + if isinstance(val, str) and val.strip(): + return val.strip() + for val in args_dict.values(): + if isinstance(val, str) and val.strip(): + return val.strip() + + # 3) ReAct 'Action:' envelope (searched anywhere — the model narrates + # and leaks fragments around it, and smolagents' step log trails it). + react = _parse_react_envelope(stripped) + if react is not None: + payload = (react.get("arguments") or {}).get("answer") + if isinstance(payload, str) and payload.strip(): + return payload.strip() + + # 3.5) smolagents' own 'Calling tools:' line + OpenAI-style call list + # — the shape Muse Glimmer writes its final_answer call in as plain + # text (no structured tool call), which the max-steps fallback then + # ships verbatim. + envelope_payload = _payload_from_calling_tools_envelope(cleaned) + if envelope_payload is not None: + return envelope_payload + + # 4) A model-narrated 'Final answer:' label with no envelope at all — + # strip the label so it doesn't render as the bubble's first line. + prefix_stripped = _strip_final_answer_prefix(text) + return prefix_stripped if prefix_stripped != text else text + + +def _rewrite_native_tool_calls(text: str) -> Optional[str]: + """Detect Qwen/Gemma native <|tool_call|> blocks in model output and + rewrite them into plain Python tool calls for the CodeAgent path. + Returns the rewritten program (one tool call per line) or None when + the text contains no parseable native call — so normal parsing + proceeds. Runs BEFORE smolagents' own parser because the wrapped shape + (a native call inside a final_answer(...) string) is VALID Python that the + original parser happily returns as a leaked final answer.""" + if not text or "<" not in text: + return None + if not re.search(r"<\|?tool_call", text): + return None + # Gemma-family `call:` envelopes closed by a ``` code fence (or a + # tag), two observed E4B shapes: + # * `call:python\n` — the body IS executable Python + # (assignment + print of the managed-agent call), so extract and + # run it as-is; + # * `call:list_columns(file_path='…')``` — a BARE call whose + # envelope is closed by a fence instead of a `` tag, + # which the old _NATIVE_TOOL_CALL_RE below never matched and the + # whole block leaked as the final answer. + lines = [] + for block in _CALL_BLOCK_RE.finditer(text): + kind = block.group(1) + body = block.group(2).strip() + if kind == "python": + # Raw single-backslash Windows paths ('G:\user_data\…' — a + # '\u' unicodeescape SyntaxError) get the same backslash + # doubling cure as the bare-call shape. + if not _native_expr_parses(body): + fixed = body.replace("\\", "\\\\") + if _native_expr_parses(fixed): + body = fixed + if _native_expr_parses(body): + lines.append(body) + else: + expr = _native_call_to_python(f"call:{kind}{body}") + if expr is not None: + lines.append(expr) + if lines: + return "\n".join(lines) + # Tag-closed bare calls / JSON-object / brace-style shapes (the + # original handling) — _CALL_BLOCK_RE above already covered the + # `call:`-prefixed ones, this catches the rest. + lines = [] + for block in _NATIVE_TOOL_CALL_RE.finditer(text): + expr = _native_call_to_python(block.group(1)) + if expr is None: + continue + lines.append(expr) + if not lines: + return None + return "\n".join(lines) + + +def _parse_native_tool_call_blob(text: str) -> Optional[dict]: + """Recover the FIRST native tool call from model output as a + normalized tool-call dict (the same shape the ReAct envelope recovery + returns) for the ToolCallingAgent JSON path. Returns None when no + native call is present.""" + if not text or "<" not in text: + return None + m = _NATIVE_TOOL_CALL_RE.search(text) + if not m: + return None + parsed = _parse_native_call(m.group(1)) + if parsed is None: + return None + name, args_text, args_dict = parsed + if args_dict is not None: + arguments = args_dict + else: + # Verbatim Python kwargs ('file_path="..."') — split into a dict + # the same way the existing call:tool{...} fallback does. The parens + # form uses '=' (Python kwargs) while the brace form uses ':', so + # both separators are accepted. + arguments = {} + try: + arguments = json.loads("{" + args_text + "}", strict=False) + except Exception: + pairs = re.findall( + r'([a-zA-Z0-9_]+)\s*[:=]\s*(".*?"|\'.*?\'|[^,}]+)', args_text, re.DOTALL + ) + for key, val in pairs: + arguments[key] = val.strip().strip('\"\'') + return _tool_call_dict(name, arguments) + + +def _strip_react_envelope(text: str) -> str: + """Strip a leading ReAct 'Action: {...}' envelope (or a truncated + fragment of one) from plain text, so raw JSON can never leak into a + final answer even if full recovery fails. Plain sentences that merely + start with the word "Action:" are left untouched.""" + m = re.match(r'^\s*Action:?\s*', text, re.DOTALL | re.IGNORECASE) + if not m: + return text + rest = text[m.end():] + if not rest.lstrip().startswith("{"): + return text + end = rest.rfind("}") + if end != -1: + return rest[end + 1:].lstrip() + # Truncated envelope with no closing brace — discard the fragment. + return "" + + +def _strip_final_answer_prefix(text: str) -> str: + """Cut a model-narrated 'Final answer:' / 'final_answer:' / 'Final + Answer:' prefix from the START of a final-answer text. Small models + announce their answer with this label before writing it; without the + strip the label renders as the first line of the bubble. Plain text + without the prefix is returned unchanged.""" + m = re.match(r'(?is)^\s*(?:final\s*_?answer)\s*:\s*', text) + if not m: + return text + rest = text[m.end():].lstrip() + return rest or text + + +def _patch_smolagents_code_parser(): + """Patch smolagents.utils.parse_code_blobs and smolagents.utils.parse_json_blob + with smart fallback parsers. + Handles: + 1. CodeAgent: Plain text final answers without ```python ... ``` code block tags. + 2. ToolCallingAgent: Model tool calls output in call:tool_name{key: val} format + or unquoted JSON key format (common with Gemma-4 and local LLMs). + """ + try: + import smolagents.utils as su + if getattr(su, "_smart_parser_installed", False): + return + _orig_parse_code_blobs = su.parse_code_blobs + _orig_parse_json_blob = su.parse_json_blob + + def _smart_parse_code_blobs(text: str, code_block_tags: tuple) -> str: + # Qwen3-4B emits a `from tools import list_columns` tutorial idiom + # that parses fine but FAILS at runtime (the sandbox exposes tools + # as plain callables, not via a `tools` module). Normalize it to + # bare-name calls BEFORE the original parser extracts the code, so + # the runtime InterpreterError never happens (see + # _normalize_tools_module_idiom). + text = _normalize_tools_module_idiom(text) + # Qwen/Gemma native tool calls FIRST (see _rewrite_native_tool_calls): + # the wrapped shape — a native call inside final_answer("""…""") — is + # VALID Python, so the original parser returns the leaked call as the + # final answer and this smart fallback never runs. Pre-scanning + # rewrites the call into executed Python for both the wrapped and the + # raw shapes, so the Data Analysis tools actually run. + native = _rewrite_native_tool_calls(text) + if native is not None: + try: + res = _orig_parse_code_blobs(native, code_block_tags) + cleaned = _strip_code_xml_tags(res) + if cleaned != res: + try: + import ast + ast.parse(cleaned) + return cleaned + except Exception: + pass + return res + except Exception: + return _strip_code_xml_tags(native) + # E2B manager shape: the REAL report is a nested + # final_answer(report="...") call INSIDE an outer + # final_answer("""Thought: ...""") wrapper string — valid Python, + # so the original parser would return the whole leaked narration + # as the final answer (rejected by the leaked-code validator). + # Unwrap the innermost call BEFORE the original parser runs. + unwrapped = _unwrap_nested_final_answer(text) + if unwrapped is not None: + return _strip_code_xml_tags(unwrapped) + try: + res = _orig_parse_code_blobs(text, code_block_tags) + cleaned = _strip_code_xml_tags(res) + if cleaned != res: + try: + import ast + ast.parse(cleaned) + return cleaned + except Exception: + pass + return res + except Exception: + if not text or not isinstance(text, str): + return 'final_answer("")' + clean_text = text.strip() + clean_text = _strip_code_xml_tags(clean_text) + + # DeepSeek DSML fence unwrap FIRST — the inner code IS the + # real program (e.g. "import pandas as pd …"), so feeding it + # back through the normal parser lets the analysis actually + # run instead of being swallowed as a "final answer". Without + # this, a DeepSeek-V4 step hard-fails with a unicode-escape + # SyntaxError (a Windows raw path inside the wrapped string) + # and the model burns its whole step budget retrying. + dsml_code = _unwrap_dsml_fence(clean_text) + if dsml_code is not None: + try: + return _orig_parse_code_blobs(dsml_code, code_block_tags) + except Exception: + return dsml_code + + # Windows-path escape recovery: a REAL code block (the Data + # manager delegating to data_worker with the dataset path) can + # fail ast.parse ONLY because a raw single-backslash path in a + # string literal trips a unicodeescape SyntaxError ('\u' in + # '\uploads'). The program is genuinely executable — neutralize + # the invalid escapes and retry the REAL parser so the code + # RUNS, instead of the whole block being mis-wrapped into a + # final_answer string the model then sees as "code snippets, + # not results". + fixed_text = _neutralize_invalid_escapes(clean_text) + if fixed_text != clean_text: + try: + return _orig_parse_code_blobs(fixed_text, code_block_tags) + except Exception: + pass + + if "final_answer(" in clean_text: + m = re.search(r"final_answer\(.*?\)", clean_text, re.DOTALL) + if m: + # Fast path: a cleanly-quoted call (final_answer("…") + # or final_answer("""…""")) is returned as-is. + try: + import ast + ast.parse(m.group(0)) + return m.group(0) + except SyntaxError: + pass + # The model wrapped its report in final_answer("...") but + # the report body contains unescaped quotes (e.g. a product + # named 24" Monitor, or quoted Khmer column names), so the + # string literal is unterminated and ast.parse fails — and + # the non-greedy regex above would cut the payload at the + # FIRST ')' inside the report, returning a fragment that is + # STILL an unterminated string (the observed E4B final- + # answer failure: "Code parsing failed … unterminated + # string literal"). Recover the FULL payload (up to the + # last ')') and re-wrap it with the same triple-quote + # escaping the plain-text path uses, so the answer is + # always parseable. + recovered = _recover_final_answer_call(clean_text) + if recovered is not None: + return recovered + + # ReAct 'Action:' envelope recovery — same bug class as the + # JSON parser below. If the model wrapped its output in a + # raw ReAct envelope, answer with the envelope's payload + # instead of leaking the raw JSON into the final answer. + react = _parse_react_envelope(clean_text) + if react is not None: + payload = (react.get("arguments") or {}).get("answer") + if isinstance(payload, str) and payload.strip(): + clean_text = payload.strip() + else: + clean_text = _strip_react_envelope(clean_text) + + clean_text = _strip_final_answer_prefix(clean_text) + + # Tokenizer-rejected characters (em-dash etc. copied from + # scraped search results) and invalid backslash escapes (raw + # Windows paths) must be normalized BEFORE the text is wrapped + # into a Python string — otherwise the wrapped + # 'final_answer("""...""")' fails ast.parse() in the executor + # with 'invalid character' / a truncated-\u unicodeescape + # error and the whole step hard-fails. + clean_text = sanitize_python_text(clean_text) + clean_text = _neutralize_invalid_escapes(clean_text) + escaped = clean_text.replace('"""', '\\"\\"\\"') + return f'final_answer("""{escaped}""")' + + def _smart_parse_json_blob(json_blob: str) -> tuple: + try: + return _orig_parse_json_blob(json_blob) + except Exception as orig_err: + if not json_blob or not isinstance(json_blob, str): + clean_text = "" + else: + clean_text = json_blob.strip() + + # Qwen/Gemma native <|tool_call|> recovery — same leak class + # as the CodeAgent path: a local GGUF emits its own native + # tool-call syntax instead of smolagents' ReAct envelope; + # recover the real call instead of wrapping the raw markers + # into the final answer. + native = _parse_native_tool_call_blob(clean_text) + if native is not None: + return native, "" + + # Match call:tool_name{key: val} format used by Gemma-4 and local LLMs + call_match = re.search(r'call:([a-zA-Z0-9_]+)\s*\{(.*)\}', clean_text, re.DOTALL) + if call_match: + tool_name = call_match.group(1).strip() + args_str = call_match.group(2).strip() + args_dict = {} + if args_str: + try: + args_dict = json.loads("{" + args_str + "}", strict=False) + except Exception: + pairs = re.findall(r'([a-zA-Z0-9_]+)\s*:\s*(".*?"|\'.*?\'|[^,}]+)', args_str, re.DOTALL) + for k, v in pairs: + v = v.strip().strip('"\'') + args_dict[k] = v + + res_dict = { + "name": tool_name, + "arguments": args_dict, + "action": tool_name, + "action_input": args_dict, + } + return res_dict, clean_text[:call_match.start()] + + # ReAct 'Action:' envelope — recover the real tool call from + # a malformed envelope (unescaped quotes / unquoted keys in + # small local GGUF output) instead of leaking the raw + # envelope text into the final answer. + react = _parse_react_envelope(clean_text) + if react is not None: + return react, "" + + # Fallback for plain text or markdown model outputs without a JSON blob. + # Belt-and-braces: strip any leading envelope fragment that full + # recovery couldn't unwrap, so raw JSON never shows in the answer. + clean_text = _strip_react_envelope(clean_text) + clean_text = _strip_final_answer_prefix(clean_text) + + res_dict = { + "name": "final_answer", + "arguments": {"answer": clean_text}, + "action": "final_answer", + "action_input": {"answer": clean_text}, + } + return res_dict, "" + + su.parse_code_blobs = _smart_parse_code_blobs + su.parse_json_blob = _smart_parse_json_blob + + # CodeAgent executor resilience: smolagents' evaluate_python_code() + # runs ast.parse() on the model's code block and, on ANY SyntaxError, + # hard-fails the whole step with "Code parsing failed on line N ...". + # A small GGUF (e.g. Gemma-4-E2B) that copies a scraped title with an + # em-dash into its Python block triggers exactly that — an invalid- + # character SyntaxError that is really just "prose, not code". Retry + # once with the sanitized text (see sanitize_python_text) so the step + # executes instead of wasting a whole generation on a parse error. + try: + import smolagents.local_python_executor as lpe + _orig_evaluate_python_code = lpe.evaluate_python_code + if not getattr(lpe, "_smart_sanitize_installed", False): + + def _smart_evaluate_python_code(code: str, *args, **kwargs): + try: + return _orig_evaluate_python_code(code, *args, **kwargs) + except Exception as e: + err_text = str(e) + # The `from import X` mangled-import class + # (Qwen3-4B observed: `from list_columns import + # list_columns` and `from tools import list_columns` — + # smolagents tutorial idioms) fails at runtime because + # there is no such MODULE: import_module() raises + # ModuleNotFoundError; when the name isn't in the + # authorized list the executor raises an "Import from + # X is not allowed" InterpreterError first. Either way + # the bare name IS available (evaluate_name resolves + # it from static_tools), so strip the import line and + # retry. Only do this when the imported module name + # is a REAL static tool — a genuine missing-package + # import must keep its error. + is_mangled_tool_import = "ModuleNotFoundError: No module named" in err_text or ( + "Import from" in err_text and "is not allowed" in err_text + ) + if is_mangled_tool_import and not getattr(lpe, "_smart_tools_import_retried", False): + static_tools = kwargs.get("static_tools") + if static_tools is None and args: + static_tools = args[0] + if isinstance(static_tools, dict): + import ast as _ast + try: + tree = _ast.parse(code) + except Exception: + tree = None + if tree is not None: + tool_names = set(static_tools.keys()) + bad_lines = set() + for node in _ast.walk(tree): + if isinstance(node, _ast.ImportFrom) and node.module in tool_names: + bad_lines.add(node.lineno) + if bad_lines: + lines = code.split("\n") + cleaned = "\n".join( + ln for i, ln in enumerate(lines, 1) if i not in bad_lines + ) + if cleaned.strip() != code.strip(): + lpe._smart_tools_import_retried = True + try: + return _orig_evaluate_python_code(cleaned, *args, **kwargs) + finally: + lpe._smart_tools_import_retried = False + # Syntax / tokenizer / parsing error recovery: + # 1. Leaked XML / special tool-call tags (e.g. from GLM-4.7-Flash) + # 2. Tokenizer-rejected characters (em-dashes, typographic quotes) + # 3. Raw Windows paths in string literals (truncated \u in \uploads) + cleaned = _strip_code_xml_tags(code) + cleaned = sanitize_python_text(cleaned) + cleaned = _neutralize_invalid_escapes(cleaned) + if cleaned != code: + try: + import ast + ast.parse(cleaned) + return _orig_evaluate_python_code(cleaned, *args, **kwargs) + except Exception: + pass + raise + + lpe.evaluate_python_code = _smart_evaluate_python_code + lpe._orig_evaluate_python_code = _orig_evaluate_python_code + lpe._smart_sanitize_installed = True + except Exception: + pass + + try: + import smolagents.models as sm + sm.parse_json_blob = _smart_parse_json_blob + except Exception: + pass + + try: + import smolagents.agents as sa + sa.parse_json_blob = _smart_parse_json_blob + # CodeAgent._step_stream calls its OWN module-level binding + # `parse_code_blobs` (captured from smolagents.utils at agents.py + # import time), NOT smolagents.utils.parse_code_blobs — so the + # smart fallback above never fired for CodeAgent tabs (Data + # Analysis) and a model that emitted no ```python fence (e.g. a + # Gemma-4 "thought…" stream) hard-failed the step with the raw + # "Your code snippet is invalid" ValueError. Rebind the agents + # module's copy to the smart wrapper too. + sa.parse_code_blobs = _smart_parse_code_blobs + except Exception: + pass + + # Smart tool execution & argument normalization patch + try: + import smolagents.agents as sa + if hasattr(sa, "ToolCallingAgent") and not getattr(sa.ToolCallingAgent, "_smart_tool_call_installed", False): + _orig_execute_tool_call = sa.ToolCallingAgent.execute_tool_call + + def _smart_execute_tool_call(self, tool_name: str, arguments): + available_tools = {**self.tools, **self.managed_agents} + if tool_name not in available_tools: + lower_map = {k.lower(): k for k in available_tools} + if tool_name.lower() in lower_map: + tool_name = lower_map[tool_name.lower()] + else: + return _orig_execute_tool_call(self, tool_name, arguments) + + tool = available_tools[tool_name] + is_managed = tool_name in self.managed_agents + + if not isinstance(arguments, dict): + if arguments is None: + arguments = {} + elif isinstance(arguments, str): + arguments = {"task": arguments} if is_managed else {"answer": arguments} if tool_name == "final_answer" else {"query": arguments} + else: + arguments = {} + else: + arguments = dict(arguments) + + # Small-model schema-echo recovery — see the module-level + # helpers above. A value (or the whole arguments object) + # that is really the tool's JSON Schema (the model pasted + # the schema instead of the value, putting the real + # question in the description) must be unwrapped BEFORE + # execution, or the tool hard-fails on an argument-type + # error and burns a whole step. + arguments = _normalize_schema_echo(arguments) + + if is_managed: + if "task" not in arguments or not arguments.get("task"): + for alias in ("query", "question", "search", "search_query", "search_task", "keywords", "prompt", "text", "input", "topic", "q", "contract", "doc", "document"): + if alias in arguments and arguments[alias]: + arguments["task"] = str(arguments.pop(alias)) + break + if not arguments.get("task"): + task_str = getattr(self, "task", "") or "search the indexed knowledge base" + if "Question:" in task_str: + task_str = task_str.split("Question:", 1)[1].split("\n\n", 1)[0].strip() + arguments["task"] = task_str + allowed = set(getattr(tool, "inputs", {}).keys()) | {"task", "additional_args"} + arguments = {k: v for k, v in arguments.items() if k in allowed} + elif tool_name == "final_answer": + if "answer" not in arguments or not arguments.get("answer"): + for alias in ("answer_text", "text", "content", "markdown", "response", "report"): + if alias in arguments and arguments[alias]: + arguments["answer"] = str(arguments.pop(alias)) + break + if not arguments.get("answer"): + for k, v in list(arguments.items()): + if v and isinstance(v, str): + arguments["answer"] = v + break + if not arguments.get("answer"): + arguments["answer"] = "" + allowed = set(getattr(tool, "inputs", {}).keys()) | {"answer"} + arguments = {k: v for k, v in arguments.items() if k in allowed} + else: + tool_inputs = getattr(tool, "inputs", {}) + custom_aliases = getattr(tool, "input_aliases", None) + for req_k in tool_inputs.keys(): + if req_k not in arguments: + aliases = (custom_aliases.get(req_k) if isinstance(custom_aliases, dict) else None) or { + "source": ("doc", "document", "file", "filename", "path", "source_file", "name", "title"), + "theme": ("topic", "category", "theme_name", "name"), + "subtheme": ("sub_theme", "subtopic", "sub_category"), + "query": ("question", "search", "search_query", "keywords", "task", "text", "prompt", "q"), + "file_path": ("filepath", "file", "path", "data_path", "filename"), + }.get(req_k, ()) + for a in aliases: + if a in arguments and arguments[a]: + arguments[req_k] = arguments.pop(a) + break + if tool_inputs: + arguments = {k: v for k, v in arguments.items() if k in tool_inputs} + + return _orig_execute_tool_call(self, tool_name, arguments) + + sa.ToolCallingAgent.execute_tool_call = _smart_execute_tool_call + sa.ToolCallingAgent._smart_tool_call_installed = True + except Exception: + pass + + try: + import smolagents.agents as sa + if hasattr(sa, "MultiStepAgent") and not getattr(sa.MultiStepAgent, "_smart_agent_call_installed", False): + _orig_agent_call = sa.MultiStepAgent.__call__ + + def _smart_agent_call(self, task: str = "", **kwargs): + if not task: + for alias in ("query", "question", "search", "search_query", "search_task", "keywords", "prompt", "text", "input", "topic", "q", "contract", "doc", "document"): + if alias in kwargs and kwargs[alias]: + task = str(kwargs.pop(alias)) + break + if not task: + task = getattr(self, "default_task", "") or getattr(self, "task", "") or "search the indexed knowledge base" + if "Question:" in task: + task = task.split("Question:", 1)[1].split("\n\n", 1)[0].strip() + return _orig_agent_call(self, task=task, **kwargs) + + sa.MultiStepAgent.__call__ = _smart_agent_call + sa.MultiStepAgent._smart_agent_call_installed = True + except Exception: + pass + + su._smart_parser_installed = True + except Exception: + pass + + +_patch_smolagents_code_parser() + + +def _truncate(text, limit: int = 1500, lang_key: str = "kh") -> str: + text = str(text or "") + if len(text) <= limit: + return text + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + suffix = l.get("agent_step_truncated", "…(truncated)") + return text[:limit].rstrip() + "\n" + suffix + + +def _step_error_bubble(e, lang_key: str = "kh") -> str: + """Bilingual error bubble for a failed agentic run: the localized + 'Execution Error:' prefix frames the (inherently English) Python + traceback so a Khmer UI doesn't open with a bare English '❌ …'.""" + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + prefix = l.get("agent_step_error_bubble", "❌ Execution Error:") + return f"{prefix} {e}\n\n{traceback.format_exc()}" + + +def _step_error_text(e, lang_key: str = "kh") -> str: + """The plain-error slot of the failed run's final yield (no traceback, + no HTML) — same localized prefix as _step_error_bubble.""" + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + prefix = l.get("agent_step_error_bubble", "❌ Execution Error:") + return f"{prefix} {e}" + + +def _error_snippet(e, limit: int = 500) -> str: + """A compact single-line rendering of a step's failure for the abort + diagnostics (`last_error`): the exception message with its type (e.g. + `KeyError: 'Quantity'`), truncated so a giant traceback-like error can + never bloat the abort message. Returns '' for empty/None errors.""" + if e is None: + return "" + text = str(e) + if not text: + text = e.__class__.__name__ + else: + text = f"{e.__class__.__name__}: {text}" + text = " ".join(text.split()) + if len(text) > limit: + text = text[:limit] + "…" + return text + + +def _format_tool_calls(tool_calls, lang_key: str = "kh") -> str: + if not tool_calls: + return "" + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + exec_label = l.get("agent_step_tool_execution", "🛠️ Tool Execution:") + truncated = l.get("agent_step_truncated", "…(truncated)") + lines = [] + for tc in tool_calls: + name = ( + getattr(tc, "name", None) + or (tc.get("name") if isinstance(tc, dict) else None) + or "tool" + ) + if name == "final_answer": + continue + args = getattr(tc, "arguments", None) + if args is None and isinstance(tc, dict): + args = tc.get("arguments") + args_str = str(args) if args is not None else "" + if len(args_str) > 800: + args_str = args_str[:800] + truncated + name_esc = html.escape(str(name)) + args_esc = html.escape(args_str) + lines.append( + f'
{exec_label} {name_esc}
\n' + f'
{args_esc}
' + ) + return "\n".join(lines) + + +def _format_step(step, lang_key: str = "kh") -> Optional[str]: + """Best-effort human-readable rendition of one smolagents memory step + (ActionStep / PlanningStep / ...) formatted with distinct step log styling. + All user-visible labels are bilingual (ui.i18n), so a Khmer UI streams + Khmer step headers and an English UI English ones. + Dynamic output fields are HTML-escaped for safety. + """ + try: + cls_name = step.__class__.__name__ + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + planning_label = l.get("agent_step_planning", "🗺️ Planning & Strategy Step") + strategy_label = l.get("agent_step_strategy", "🗺️ Strategy") + header_tpl = l.get("agent_step_header", "⚙️ Step {n} — Execution Log & Tools") + header_plain = l.get("agent_step_header_plain", "⚙️ Agent Step — Execution Log") + reasoning_label = l.get("agent_step_reasoning", "🧠 Reasoning:") + obs_label = l.get("agent_step_observations", "📝 Execution Logs & Terminal Output") + err_label = l.get("agent_step_error", "⚠️ Execution Error") + + if cls_name == "PlanningStep": + plan = getattr(step, "plan", None) or getattr(step, "facts", None) + if not plan: + return None + plan_esc = html.escape(_truncate(plan, lang_key=lang_key)) + return ( + '
\n' + f'{planning_label}\n' + '
\n' + f'
{strategy_label}
{plan_esc}
\n' + '
\n
' + ) + + if cls_name in ("TaskStep", "SystemPromptStep"): + return None + + step_number = getattr(step, "step_number", None) + try: + header_text = header_tpl.format(n=step_number) if step_number is not None else header_plain + except (KeyError, ValueError): + # A future translation edit that drops the {n} placeholder must + # never blank the whole step header — fall back to the plain one. + header_text = header_plain + + # Timing breakdown badge (if step.timing exposes generation / execution durations) + timing = getattr(step, "timing", None) + timing_badge = "" + if timing is not None: + gen_d = getattr(timing, "generation_duration", None) + if gen_d is None: + gen_d = getattr(timing, "model_time", None) + exec_d = getattr(timing, "execution_duration", None) + if exec_d is None: + exec_d = getattr(timing, "tool_time", None) + durs = [] + if isinstance(gen_d, (int, float)) and gen_d > 0: + durs.append(f"🧠 {gen_d:.1f}s") + if isinstance(exec_d, (int, float)) and exec_d > 0: + durs.append(f"🛠️ {exec_d:.1f}s") + if durs: + timing_badge = f' ({", ".join(durs)})' + + tool_calls = getattr(step, "tool_calls", None) + is_final_call = bool( + tool_calls + and all( + (getattr(tc, "name", None) or (tc.get("name") if isinstance(tc, dict) else None)) == "final_answer" + for tc in tool_calls + ) + ) + error = getattr(step, "error", None) + if is_final_call and not error: + return None + + parts = [] + + model_output = getattr(step, "model_output", None) + if model_output: + cleaned_out = _truncate(model_output, lang_key=lang_key) + cleaned_esc = html.escape(cleaned_out) + parts.append(f'
{reasoning_label}\n{cleaned_esc}
') + + has_real_tool = any( + (getattr(tc, "name", None) or (tc.get("name") if isinstance(tc, dict) else None)) != "final_answer" + for tc in (tool_calls or []) + ) + tc_str = _format_tool_calls(tool_calls, lang_key=lang_key) + if tc_str: + parts.append(f'
{tc_str}
') + + observations = getattr(step, "observations", None) + if observations and (has_real_tool or not tool_calls): + obs_text = _truncate(observations, 1200, lang_key=lang_key) + obs_esc = html.escape(obs_text) + parts.append( + f'
\n' + f'
{obs_label}
\n' + f'
{obs_esc}
\n' + '
' + ) + + error = getattr(step, "error", None) + if error: + err_text = _truncate(str(error), 800, lang_key=lang_key) + err_esc = html.escape(err_text) + parts.append( + f'
\n' + f'
{err_label}
\n' + f'
{err_esc}
\n' + '
' + ) + + if not parts: + return None + + body_html = "\n".join(parts) + rendered = ( + f'
\n' + f'{header_text}{timing_badge}\n' + f'
\n{body_html}\n
\n' + '
' + ) + return sanitize_surrogates(rendered) + except Exception: + # Never let a formatting glitch break the whole streamed run + return None + + +def _is_memory_step(item) -> bool: + """Distinguish a smolagents memory-step object (ActionStep, + PlanningStep, ...) from the final answer itself. smolagents' own + streaming run yields the plain final answer, UNWRAPPED, as the very + last item — so anything that isn't recognizably a memory step is + treated as the final answer by the caller (see stream_agent_steps()). + """ + if _MEMORY_STEP_TYPES and isinstance(item, _MEMORY_STEP_TYPES): + return True + return item.__class__.__name__ in _MEMORY_STEP_CLASS_NAMES + + +# ── Fail-fast guard & run diagnostics ─────────────────────────────────── +# A model stuck in a loop of errored steps (tool-call parse failures, tool +# exceptions, failed final-answer checks…) burns its whole step budget one +# slow generation at a time — on a large local GGUF each failed step can +# take a minute or more. The stream loop below tracks CONSECUTIVE errored +# steps and aborts early with bilingual guidance once the threshold is +# hit, instead of grinding through every remaining step. The per-run +# diagnostics dict is read back by the chat handlers (chat.py) to surface +# a soft "consider a larger model" hint when a run COMPLETES but still +# stumbled repeatedly. +_ERROR_ABORT_THRESHOLD = 3 +_STUMBLE_HINT_THRESHOLD = 2 + +# ── Repetition-loop guard ────────────────────────────────────────────── +# A model stuck repeating the SAME tool call over and over (a degenerate +# repetition loop — the observation is sitting right there in its context, +# but it keeps re-emitting the identical call, then surrenders with +# meta-commentary like "I don't see any observations") burns the whole +# step budget one slow generation at a time. Unlike the error guard above +# (which keys on FAILED steps), this loop produces successful steps, so it +# needs its own detector: N identical consecutive tool-call signatures. On +# the threshold the run first INJECTS a corrective reminder into the +# agent's memory (the fresh context breaks the deterministic +# re-generation — the standard cure); if the model still repeats the same +# call after that, the run aborts with the same bilingual machinery as the +# error guard. +# +# A stuck model often VARIES its code slightly each time (drops a +# try/except, switches path escaping, re-imports) while still re-reading +# the SAME data file with the SAME tool — each variant's full signature +# differs, so the exact-signature channel above never fires. A second, +# coarser channel counts consecutive same-tool + same-file accesses +# (parsed out of the code text / call arguments and path-normalized), so +# a model grinding on one file is caught even when the surrounding code +# changes every step. Both channels share the nudge-once-then-abort +# lifecycle. +_LOOP_NUDGE_THRESHOLD = 3 + +_last_run_local = threading.local() + + +def get_last_run() -> dict: + """Thread-local per-run diagnostics for the most recent agentic run on + THIS thread: {total_steps, max_consecutive_errors, aborted, last_error}. + + Thread-local so two agentic tabs running concurrently (parallel + workers) can never cross-wire each other's failure data — each run's + chat handler reads back exactly the diagnostics its own thread just + produced, even when a run on another thread is aborting/stumbling at + the same time.""" + d = getattr(_last_run_local, "last_run", None) + if d is None: + d = {"total_steps": 0, "max_consecutive_errors": 0, "aborted": False, + "last_error": "", "loop_detected": False, "loop_call": ""} + _last_run_local.last_run = d + return d + + +def _tool_calls_signature(step): + """Canonical identity of the tool call(s) a step executed — the loop + guard's equality key. On the CodeAgent path every step's tool_calls is + [ToolCall(name='python_interpreter', arguments=)], so an + identical repeated code block yields an identical signature; on the + ToolCallingAgent path it's the real tool name + normalized arguments + (dict ordering ignored — the same call with keys in a different order + is still the same call). Returns None when the step carries no + readable tool call (final-answer steps, parse failures) — nothing to + compare, so the guard stands down. Never raises: any odd step shape + just returns None.""" + try: + tcs = getattr(step, "tool_calls", None) + if not tcs: + return None + sigs = [] + for tc in tcs: + name = getattr(tc, "name", None) + if name is None and isinstance(tc, dict): + name = tc.get("name") + args = getattr(tc, "arguments", None) + if args is None and isinstance(tc, dict): + args = tc.get("arguments") + if name is None: + return None + if isinstance(args, dict): + args_sig = tuple(sorted((str(k), str(v)) for k, v in args.items())) + else: + args_sig = str(args) + sigs.append((str(name), args_sig)) + return tuple(sigs) + except Exception: + return None + + +def _signature_call_names(sig) -> str: + """Human-readable label of a loop signature for the abort message: the + first call's tool name (with a '+N more' suffix when the step carried + several calls). On the CodeAgent path the executor name is the generic + 'python_interpreter', so the first function called inside the code text + (e.g. 'list_columns' from `list_columns("G:\\data.xlsx")`) is surfaced + instead — that's the tool the user actually sees looping. Returns '' + for empty/unreadable signatures.""" + try: + if not sig: + return "" + first_name, first_args = sig[0] + if first_name == "python_interpreter" and isinstance(first_args, str): + m = re.match(r"\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\(", first_args.strip()) + if m: + first_name = m.group(1) + names = [first_name] + [s[0] for s in sig[1:]] + label = names[0] + if len(names) > 1: + label += f" (+{len(names) - 1} more)" + return label + except Exception: + return "" + + +# ── Same-tool + same-file loop channel ───────────────────────────────── +# The exact-signature guard above catches a model re-emitting the +# IDENTICAL call, but a stuck model often VARIES its code slightly each +# time (drops a try/except, switches escaping, re-imports) while still +# re-reading the SAME data file with the SAME tool — each variant's full +# signature differs, so the exact channel never fires. These helpers +# derive a coarser fingerprint: every call in the step that accesses a +# data file, keyed on (tool name, normalized path, effective arguments). +# Path normalization unifies the same file written as a raw string, an +# escaped string, or via a variable (G:\x vs g:/x), so the variants +# collapse to one fingerprint the guard can count; the effective +# arguments (everything but the file itself) keep DIFFERENT operations on +# the same file (aggregate by ខេត្ត vs by ភេទ) distinct — a thorough +# multi-step EDA never trips the channel. +# +# Incidental SETUP/utility calls are filtered OUT of the fingerprint so +# they can't break a genuine read loop: a model that re-reads the SAME +# data file with read_excel while also calling os.makedirs on the outputs +# dir (or os.path.join / os.path.exists / mkdir / …) is still doing the +# same repeated read — the makedirs call is noise, not a different +# operation. Only calls that touch a DATA file (reads, aggregates, chart +# saves, exports) contribute to the fingerprint. +_INCIDENTAL_TOOL_NAMES = frozenset({ + # filesystem setup / teardown / listing — never the data read itself + "makedirs", "mkdir", "mkdirs", "rmdir", "removedirs", + "listdir", "scandir", "walk", "glob", "iglob", + "exists", "lexists", "isfile", "isdir", "islink", "isabs", + "remove", "unlink", "rename", "replace", "rmtree", + "copytree", "copy", "copy2", "move", "chdir", "getcwd", + # path construction / munging / metadata + "join", "abspath", "normpath", "realpath", "expanduser", + "expandvars", "basename", "dirname", "splitext", + "commonpath", "relpath", "getsize", "getmtime", "stat", "lstat", + # generic chatter / setup that can carry a path-shaped string + "print", "set_option", "reset_option", "get_option", + "install_package", "check_call", "run", "call", "system", "Popen", +}) + +_FILE_PATH_ARG_KEYS = ( + "file_path", "filepath", "path", "file", "filename", + "source", "src", "doc", "document", "data_path", "input_file", +) + +_PATH_LIKE_RE = re.compile( + r"[\\/]|\.(?:xlsx?|csv|tsv|json|parquet|txt|png|jpe?g|pdf)$", + re.IGNORECASE, +) + + +def _path_like(value) -> bool: + """True when a string reads as a file path — contains a path + separator, or ends with a data-file extension (so bare 'data.xlsx' + counts, but 'sum' / 'ខេត្ត' never do). Non-strings and empty strings + are never paths.""" + if not isinstance(value, str) or not value.strip(): + return False + return bool(_PATH_LIKE_RE.search(value)) + + +def _normalize_path(path: str) -> str: + """Canonical form of a file path for fingerprint comparison: strip + quotes, unify separators to '/', lowercase everything (Windows paths + are case-insensitive — this app ships on the Microsoft Store) and + collapse duplicate slashes — so the same file written as + 'G:\\\\Data\\\\A.XLSX', r'G:\\data\\a.xlsx' or 'g:/data/a.xlsx' all compare + equal. Never raises; garbage input degrades to its stripped self.""" + try: + p = (path or "").strip().strip("\"'") + p = p.replace("\\", "/") + p = p.lower() + p = re.sub(r"/+", "/", p) + return p.rstrip("/") + except Exception: + return str(path or "") + + +def _arg_value_str(value, consts) -> str: + """Stringify one call argument for the fingerprint's 'effective + arguments' slot: constants and simple variable assignments resolve to + their real values (so a literal 'sum' and a variable holding 'sum' + compare equal); anything unparseable degrades to its AST node type — + never raises.""" + try: + if isinstance(value, ast.Constant): + return repr(value.value) + if isinstance(value, ast.Name) and value.id in consts: + return repr(consts[value.id]) + return repr(ast.literal_eval(value)) + except Exception: + return f"<{type(value).__name__}>" + + +def _call_func_name(func) -> Optional[str]: + """Bare name of the function a Call invokes: 'list_columns' for a + plain Name, 'read_excel' for 'pd.read_excel' (attribute calls are + normalized to their method name so the same tool imported directly or + via a module compares equal). None for anything odd.""" + if isinstance(func, ast.Name): + return func.id + if isinstance(func, ast.Attribute): + return func.attr + return None + + +def _call_file_path(node, consts): + """The data-file path a Call reads/writes, or None. The curated Data + tools' first positional argument IS the file path; path-named + keywords (file_path=/path=/file=...) are also accepted. Name + arguments resolve through simple string assignments ('path = + "G:\\..."; list_columns(path)'). Returns (path, True) when the path + was positional, (path, False) when it came from a keyword — the + caller uses that to know which arguments are the 'effective + arguments' and which was the file itself.""" + def _str_of(v): + if isinstance(v, ast.Constant) and isinstance(v.value, str): + return v.value + if isinstance(v, ast.Name) and v.id in consts: + return consts[v.id] + return None + + if node.args: + p = _str_of(node.args[0]) + if p is not None: + return p, True + for kw in node.keywords: + if kw.arg in _FILE_PATH_ARG_KEYS: + p = _str_of(kw.value) + if p is not None: + return p, False + return None + + +def _code_file_access_fps(code_text: str) -> tuple: + """Parse a Python program and return the sorted tuple of + (tool, normalized_path, effective_args) fingerprints for EVERY call + that accesses a data file with a resolvable string path. The + 'effective arguments' (everything but the file itself) make two calls + to the SAME file with DIFFERENT operations (aggregate by ខេត្ត vs by + ភេទ) distinct fingerprints — only a genuinely repeated operation on + the same file collapses. Returns () when the code doesn't parse or + nothing touches a file — the caller treats that as 'no file loop', + never a crash.""" + if not code_text: + return () + try: + tree = ast.parse(code_text) + except Exception: + return () + # Resolve simple module-level string assignments ('path = "G:\\..."') + # so calls passing the file via a variable fingerprint identically to + # calls inlining the literal. + consts = {} + for node in ast.walk(tree): + if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) \ + and isinstance(node.value.value, str) and len(node.targets) == 1 \ + and isinstance(node.targets[0], ast.Name): + consts[node.targets[0].id] = node.value.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.value, ast.Constant) \ + and isinstance(node.value.value, str) and isinstance(node.target, ast.Name): + consts[node.target.id] = node.value.value + pairs = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + name = _call_func_name(node.func) + if name is None: + continue + name_l = name.lower() + # Incidental setup/utility calls (os.makedirs, os.path.join, …) + # are noise — they never represent the repeated data access, and a + # model that interleaves one with its re-reads must still collapse + # to the same fingerprint (see the section comment). + if name_l in _INCIDENTAL_TOOL_NAMES: + continue + found = _call_file_path(node, consts) + if found is None: + continue + path, path_pos = found + # Only a real path (separator or data-file extension) is a file + # access — a bare column name, an agg value or a print() string + # must never count as 'reading the file'. + if not _path_like(path): + continue + if path_pos: + rest = list(node.args[1:]) + else: + rest = list(node.args) + vals = [_arg_value_str(a, consts) for a in rest] + vals.extend( + f"{kw.arg}={_arg_value_str(kw.value, consts)}" + for kw in node.keywords if kw.arg not in _FILE_PATH_ARG_KEYS) + pairs.add((name.lower(), _normalize_path(path), tuple(sorted(vals)))) + return tuple(sorted(pairs)) + + +def _file_access_fingerprint(step): + """Coarser loop key than `_tool_calls_signature`: a sorted tuple of + (tool, normalized_path, effective_args) for every call in the step + that accesses a data file. CodeAgent steps (python_interpreter) are + parsed from the code text; ToolCallingAgent steps read path-named + string values from their arguments dict. Returns None when the step + carries no file access — the file loop channel stands down. Never + raises; odd step shapes just return None.""" + try: + tcs = getattr(step, "tool_calls", None) + if not tcs: + return None + pairs = [] + for tc in tcs: + name = getattr(tc, "name", None) + if name is None and isinstance(tc, dict): + name = tc.get("name") + args = getattr(tc, "arguments", None) + if args is None and isinstance(tc, dict): + args = tc.get("arguments") + if name is None: + continue + if name == "python_interpreter": + if isinstance(args, str): + pairs.extend(_code_file_access_fps(args)) + continue + if isinstance(args, dict): + name_l = str(name).lower() + if name_l in _INCIDENTAL_TOOL_NAMES: + continue + path_key = next( + (k for k in _FILE_PATH_ARG_KEYS + if _path_like(args.get(k))), None) + if path_key is not None: + sem = tuple(sorted( + str(v) for k, v in args.items() if k != path_key)) + pairs.append( + (name_l, _normalize_path(args[path_key]), sem)) + if not pairs: + return None + return tuple(sorted(set(pairs))) + except Exception: + return None + + +def _file_fp_call_names(ffp) -> str: + """Human-readable label of a repeated (tool, file) fingerprint for the + loop abort message: the tool name plus the data file's basename (e.g. + 'list_columns on data.xlsx') — far more actionable than the generic + python_interpreter executor name when the model is stuck re-reading + one file. Returns '' for empty fingerprints.""" + try: + if not ffp: + return "" + name, path, _sem = ffp[0] + base = path.rstrip("/").rsplit("/", 1)[-1] or path + if len(base) > 60: + base = base[:57] + "…" + return f"{name} on {base}" + except Exception: + return "" + + +def _inject_loop_nudge(agent, lang_key: str = "kh") -> bool: + """Append a corrective assistant message to the agent's memory telling + the model the repeated call's output is already in its context — the + standard cure for the degenerate repetition loop (fresh context breaks + the deterministic re-generation). The appended step renders as a plain + assistant message in the model's next prompt (ActionStep.to_messages + turns model_output into an assistant ChatMessage). Returns False when + the memory isn't writable (never raises).""" + try: + if agent is None: + return False + memory = getattr(agent, "memory", None) + if memory is None or not hasattr(memory, "steps"): + return False + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + nudge = l.get("agent_loop_nudge", "") + if not nudge: + return False + try: + from smolagents.memory import ActionStep + except Exception: + return False + memory.steps.append(ActionStep(step_number=len(memory.steps) or 1, + timing=None, model_output=nudge)) + return True + except Exception: + return False + + +def _loop_nudge_bubble(lang_key: str = "kh") -> str: + """User-visible line shown when the loop guard injected the corrective + reminder — so the streamed log shows the app intervened, not just the + model's identical steps.""" + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + return l.get("agent_loop_nudge_bubble", + "⚠️ The model repeated the same tool call — a reminder was sent to continue.") + + +def _rejected_at_delivery(text) -> bool: + """True when `text` fails the shared final-answer validator at the + DELIVERY choke point. smolagents only runs `final_answer_checks` + against an EXPLICIT final_answer() tool call — the max-steps fallback + (provide_final_answer) ships the model's raw last output with NO + validation, which is exactly how the Muse-Glimmer deliberation + monologue ("We need to gather more detailed info … Let's call + web_search_agent …") reached the answer bubble after burning all 12 + steps. Re-checking here closes that gap; a validator hiccup must + never block delivery, so any exception passes the text through.""" + try: + from agents.agent_factory import reject_leaked_or_empty_final_answer + return not reject_leaked_or_empty_final_answer(text) + except Exception: + return False + + +def _rejected_answer_bubble(lang_key: str = "kh") -> str: + """Honest bilingual replacement for a final answer that failed the + delivery-time validation — never ship the raw garbage instead.""" + l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"]) + return l.get( + "agent_final_answer_rejected", + "⚠️ The model could not produce a valid final answer — its last " + "output was internal task reasoning, not an actual report (the run " + "reached its step limit). Try running the research again, or use a " + "stronger model (e.g. Gemma-4-E4B or above).") + + +def _agent_steps_budget_txt(agent) -> str: + """The EFFECTIVE step budget(s) the built agent actually runs with — the + number that really capped this turn, read off the agent object + (agent.max_steps, plus each managed sub-agent's max_steps: RAG's + knowledge_searcher, Deep Research's web_search_agent, Data Analysis's + data_worker). This is what + 'what actually ran' means: when the per-tab Max Steps control is on + 'auto', the builder applied the model-scaled default (see + model_registry.get_max_steps_for_model) inside get_*_agent, so the + request value passed in was None while the agent runs a scaled number — + the footer must reflect the latter. Returns 'steps: N' or + 'steps: N (+M